org-macs.el 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. ;;; org-macs.el --- Top-level Definitions for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: https://orgmode.org
  6. ;;
  7. ;; This file is part of GNU Emacs.
  8. ;;
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  20. ;;
  21. ;;; Commentary:
  22. ;; This file contains macro definitions, defsubst definitions, other
  23. ;; stuff needed for compilation and top-level forms in Org mode, as
  24. ;; well lots of small functions that are not Org mode specific but
  25. ;; simply generally useful stuff.
  26. ;;; Code:
  27. ;;; Macros
  28. (defmacro org-with-gensyms (symbols &rest body)
  29. (declare (debug (sexp body)) (indent 1))
  30. `(let ,(mapcar (lambda (s)
  31. `(,s (make-symbol (concat "--" (symbol-name ',s)))))
  32. symbols)
  33. ,@body))
  34. (defmacro org-preserve-lc (&rest body)
  35. (declare (debug (body)))
  36. (org-with-gensyms (line col)
  37. `(let ((,line (org-current-line))
  38. (,col (current-column)))
  39. (unwind-protect
  40. (progn ,@body)
  41. (org-goto-line ,line)
  42. (org-move-to-column ,col)))))
  43. ;; Use `org-with-silent-modifications' to ignore cosmetic changes and
  44. ;; `org-unmodified' to ignore real text modifications
  45. (defmacro org-unmodified (&rest body)
  46. "Run BODY while preserving the buffer's `buffer-modified-p' state."
  47. (declare (debug (body)))
  48. (org-with-gensyms (was-modified)
  49. `(let ((,was-modified (buffer-modified-p)))
  50. (unwind-protect
  51. (let ((buffer-undo-list t)
  52. (inhibit-modification-hooks t))
  53. ,@body)
  54. (set-buffer-modified-p ,was-modified)))))
  55. (defmacro org-without-partial-completion (&rest body)
  56. (declare (debug (body)))
  57. `(if (and (boundp 'partial-completion-mode)
  58. partial-completion-mode
  59. (fboundp 'partial-completion-mode))
  60. (unwind-protect
  61. (progn
  62. (partial-completion-mode -1)
  63. ,@body)
  64. (partial-completion-mode 1))
  65. ,@body))
  66. (defmacro org-with-point-at (pom &rest body)
  67. "Move to buffer and point of point-or-marker POM for the duration of BODY."
  68. (declare (debug (form body)) (indent 1))
  69. (org-with-gensyms (mpom)
  70. `(let ((,mpom ,pom))
  71. (save-excursion
  72. (if (markerp ,mpom) (set-buffer (marker-buffer ,mpom)))
  73. (org-with-wide-buffer
  74. (goto-char (or ,mpom (point)))
  75. ,@body)))))
  76. (defmacro org-with-remote-undo (buffer &rest body)
  77. "Execute BODY while recording undo information in two buffers."
  78. (declare (debug (form body)) (indent 1))
  79. (org-with-gensyms (cline cmd buf1 buf2 undo1 undo2 c1 c2)
  80. `(let ((,cline (org-current-line))
  81. (,cmd this-command)
  82. (,buf1 (current-buffer))
  83. (,buf2 ,buffer)
  84. (,undo1 buffer-undo-list)
  85. (,undo2 (with-current-buffer ,buffer buffer-undo-list))
  86. ,c1 ,c2)
  87. ,@body
  88. (when org-agenda-allow-remote-undo
  89. (setq ,c1 (org-verify-change-for-undo
  90. ,undo1 (with-current-buffer ,buf1 buffer-undo-list))
  91. ,c2 (org-verify-change-for-undo
  92. ,undo2 (with-current-buffer ,buf2 buffer-undo-list)))
  93. (when (or ,c1 ,c2)
  94. ;; make sure there are undo boundaries
  95. (and ,c1 (with-current-buffer ,buf1 (undo-boundary)))
  96. (and ,c2 (with-current-buffer ,buf2 (undo-boundary)))
  97. ;; remember which buffer to undo
  98. (push (list ,cmd ,cline ,buf1 ,c1 ,buf2 ,c2)
  99. org-agenda-undo-list))))))
  100. (defmacro org-no-read-only (&rest body)
  101. "Inhibit read-only for BODY."
  102. (declare (debug (body)))
  103. `(let ((inhibit-read-only t)) ,@body))
  104. (defmacro org-save-outline-visibility (use-markers &rest body)
  105. "Save and restore outline visibility around BODY.
  106. If USE-MARKERS is non-nil, use markers for the positions. This
  107. means that the buffer may change while running BODY, but it also
  108. means that the buffer should stay alive during the operation,
  109. because otherwise all these markers will point to nowhere."
  110. (declare (debug (form body)) (indent 1))
  111. (org-with-gensyms (data invisible-types markers?)
  112. `(let* ((,invisible-types '(org-hide-block org-hide-drawer outline))
  113. (,markers? ,use-markers)
  114. (,data
  115. (mapcar (lambda (o)
  116. (let ((beg (overlay-start o))
  117. (end (overlay-end o))
  118. (type (overlay-get o 'invisible)))
  119. (and beg end
  120. (> end beg)
  121. (memq type ,invisible-types)
  122. (list (if ,markers? (copy-marker beg) beg)
  123. (if ,markers? (copy-marker end t) end)
  124. type))))
  125. (org-with-wide-buffer
  126. (overlays-in (point-min) (point-max))))))
  127. (unwind-protect (progn ,@body)
  128. (org-with-wide-buffer
  129. (dolist (type ,invisible-types)
  130. (remove-overlays (point-min) (point-max) 'invisible type))
  131. (pcase-dolist (`(,beg ,end ,type) (delq nil ,data))
  132. (org-flag-region beg end t type)
  133. (when ,markers?
  134. (set-marker beg nil)
  135. (set-marker end nil))))))))
  136. (defmacro org-with-wide-buffer (&rest body)
  137. "Execute body while temporarily widening the buffer."
  138. (declare (debug (body)))
  139. `(save-excursion
  140. (save-restriction
  141. (widen)
  142. ,@body)))
  143. (defmacro org-with-limited-levels (&rest body)
  144. "Execute BODY with limited number of outline levels."
  145. (declare (debug (body)))
  146. `(progn
  147. (defvar org-called-with-limited-levels)
  148. (defvar org-outline-regexp)
  149. (defvar outline-regexp)
  150. (defvar org-outline-regexp-bol)
  151. (let* ((org-called-with-limited-levels t)
  152. (org-outline-regexp (org-get-limited-outline-regexp))
  153. (outline-regexp org-outline-regexp)
  154. (org-outline-regexp-bol (concat "^" org-outline-regexp)))
  155. ,@body)))
  156. (defmacro org-eval-in-environment (environment form)
  157. (declare (debug (form form)) (indent 1))
  158. `(eval (list 'let ,environment ',form)))
  159. ;;;###autoload
  160. (defmacro org-load-noerror-mustsuffix (file)
  161. "Load FILE with optional arguments NOERROR and MUSTSUFFIX."
  162. `(load ,file 'noerror nil nil 'mustsuffix))
  163. (defmacro org-preserve-local-variables (&rest body)
  164. "Execute BODY while preserving local variables."
  165. (declare (debug (body)))
  166. `(let ((local-variables
  167. (org-with-wide-buffer
  168. (goto-char (point-max))
  169. (let ((case-fold-search t))
  170. (and (re-search-backward "^[ \t]*# +Local Variables:"
  171. (max (- (point) 3000) 1)
  172. t)
  173. (delete-and-extract-region (point) (point-max)))))))
  174. (unwind-protect (progn ,@body)
  175. (when local-variables
  176. (org-with-wide-buffer
  177. (goto-char (point-max))
  178. (unless (bolp) (insert "\n"))
  179. (insert local-variables))))))
  180. ;;; Buffer
  181. (defun org-base-buffer (buffer)
  182. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  183. (if (not buffer)
  184. buffer
  185. (or (buffer-base-buffer buffer)
  186. buffer)))
  187. (defun org-find-base-buffer-visiting (file)
  188. "Like `find-buffer-visiting' but always return the base buffer and
  189. not an indirect buffer."
  190. (let ((buf (or (get-file-buffer file)
  191. (find-buffer-visiting file))))
  192. (if buf
  193. (or (buffer-base-buffer buf) buf)
  194. nil)))
  195. ;;; Input
  196. (defun org-read-function (prompt &optional allow-empty?)
  197. "Prompt for a function.
  198. If ALLOW-EMPTY? is non-nil, return nil rather than raising an
  199. error when the user input is empty."
  200. (let ((func (completing-read prompt obarray #'fboundp t)))
  201. (cond ((not (string= func ""))
  202. (intern func))
  203. (allow-empty? nil)
  204. (t (user-error "Empty input is not valid")))))
  205. (defun org-completing-read (&rest args)
  206. "Completing-read with SPACE being a normal character."
  207. (let ((enable-recursive-minibuffers t)
  208. (minibuffer-local-completion-map
  209. (copy-keymap minibuffer-local-completion-map)))
  210. (define-key minibuffer-local-completion-map " " 'self-insert-command)
  211. (define-key minibuffer-local-completion-map "?" 'self-insert-command)
  212. (define-key minibuffer-local-completion-map (kbd "C-c !")
  213. 'org-time-stamp-inactive)
  214. (apply #'completing-read args)))
  215. (defun org--mks-read-key (allowed-keys prompt)
  216. "Read a key and ensure it is a member of ALLOWED-KEYS.
  217. TAB, SPC and RET are treated equivalently."
  218. (let* ((key (char-to-string
  219. (pcase (read-char-exclusive prompt)
  220. ((or ?\s ?\t ?\r) ?\t)
  221. (char char)))))
  222. (if (member key allowed-keys)
  223. key
  224. (message "Invalid key: `%s'" key)
  225. (sit-for 1)
  226. (org--mks-read-key allowed-keys prompt))))
  227. (defun org-mks (table title &optional prompt specials)
  228. "Select a member of an alist with multiple keys.
  229. TABLE is the alist which should contain entries where the car is a string.
  230. There should be two types of entries.
  231. 1. prefix descriptions like (\"a\" \"Description\")
  232. This indicates that `a' is a prefix key for multi-letter selection, and
  233. that there are entries following with keys like \"ab\", \"ax\"...
  234. 2. Select-able members must have more than two elements, with the first
  235. being the string of keys that lead to selecting it, and the second a
  236. short description string of the item.
  237. The command will then make a temporary buffer listing all entries
  238. that can be selected with a single key, and all the single key
  239. prefixes. When you press the key for a single-letter entry, it is selected.
  240. When you press a prefix key, the commands (and maybe further prefixes)
  241. under this key will be shown and offered for selection.
  242. TITLE will be placed over the selection in the temporary buffer,
  243. PROMPT will be used when prompting for a key. SPECIAL is an
  244. alist with (\"key\" \"description\") entries. When one of these
  245. is selected, only the bare key is returned."
  246. (save-window-excursion
  247. (let ((inhibit-quit t)
  248. (buffer (org-switch-to-buffer-other-window "*Org Select*"))
  249. (prompt (or prompt "Select: "))
  250. current)
  251. (unwind-protect
  252. (catch 'exit
  253. (while t
  254. (erase-buffer)
  255. (insert title "\n\n")
  256. (let ((des-keys nil)
  257. (allowed-keys '("\C-g"))
  258. (tab-alternatives '("\s" "\t" "\r"))
  259. (cursor-type nil))
  260. ;; Populate allowed keys and descriptions keys
  261. ;; available with CURRENT selector.
  262. (let ((re (format "\\`%s\\(.\\)\\'"
  263. (if current (regexp-quote current) "")))
  264. (prefix (if current (concat current " ") "")))
  265. (dolist (entry table)
  266. (pcase entry
  267. ;; Description.
  268. (`(,(and key (pred (string-match re))) ,desc)
  269. (let ((k (match-string 1 key)))
  270. (push k des-keys)
  271. ;; Keys ending in tab, space or RET are equivalent.
  272. (if (member k tab-alternatives)
  273. (push "\t" allowed-keys)
  274. (push k allowed-keys))
  275. (insert prefix "[" k "]" "..." " " desc "..." "\n")))
  276. ;; Usable entry.
  277. (`(,(and key (pred (string-match re))) ,desc . ,_)
  278. (let ((k (match-string 1 key)))
  279. (insert prefix "[" k "]" " " desc "\n")
  280. (push k allowed-keys)))
  281. (_ nil))))
  282. ;; Insert special entries, if any.
  283. (when specials
  284. (insert "----------------------------------------------------\
  285. ---------------------------\n")
  286. (pcase-dolist (`(,key ,description) specials)
  287. (insert (format "[%s] %s\n" key description))
  288. (push key allowed-keys)))
  289. ;; Display UI and let user select an entry or
  290. ;; a sub-level prefix.
  291. (goto-char (point-min))
  292. (unless (pos-visible-in-window-p (point-max))
  293. (org-fit-window-to-buffer))
  294. (let ((pressed (org--mks-read-key allowed-keys prompt)))
  295. (setq current (concat current pressed))
  296. (cond
  297. ((equal pressed "\C-g") (user-error "Abort"))
  298. ;; Selection is a prefix: open a new menu.
  299. ((member pressed des-keys))
  300. ;; Selection matches an association: return it.
  301. ((let ((entry (assoc current table)))
  302. (and entry (throw 'exit entry))))
  303. ;; Selection matches a special entry: return the
  304. ;; selection prefix.
  305. ((assoc current specials) (throw 'exit current))
  306. (t (error "No entry available")))))))
  307. (when buffer (kill-buffer buffer))))))
  308. ;;; Logic
  309. (defsubst org-xor (a b)
  310. "Exclusive `or'."
  311. (if a (not b) b))
  312. ;;; Overlays
  313. (defun org-overlay-display (ovl text &optional face evap)
  314. "Make overlay OVL display TEXT with face FACE."
  315. (overlay-put ovl 'display text)
  316. (if face (overlay-put ovl 'face face))
  317. (if evap (overlay-put ovl 'evaporate t)))
  318. (defun org-overlay-before-string (ovl text &optional face evap)
  319. "Make overlay OVL display TEXT with face FACE."
  320. (if face (org-add-props text nil 'face face))
  321. (overlay-put ovl 'before-string text)
  322. (if evap (overlay-put ovl 'evaporate t)))
  323. (defun org-find-overlays (prop &optional pos delete)
  324. "Find all overlays specifying PROP at POS or point.
  325. If DELETE is non-nil, delete all those overlays."
  326. (let (found)
  327. (dolist (ov (overlays-at (or pos (point))) found)
  328. (cond ((not (overlay-get ov prop)))
  329. (delete (delete-overlay ov))
  330. (t (push ov found))))))
  331. (defun org-flag-region (from to flag spec)
  332. "Hide or show lines from FROM to TO, according to FLAG.
  333. SPEC is the invisibility spec, as a symbol."
  334. (remove-overlays from to 'invisible spec)
  335. ;; Use `front-advance' since text right before to the beginning of
  336. ;; the overlay belongs to the visible line than to the contents.
  337. (when flag
  338. (let ((o (make-overlay from to nil 'front-advance)))
  339. (overlay-put o 'evaporate t)
  340. (overlay-put o 'invisible spec)
  341. (overlay-put o 'isearch-open-invisible #'delete-overlay))))
  342. ;;; Indentation
  343. (defun org-get-indentation (&optional line)
  344. "Get the indentation of the current line, interpreting tabs.
  345. When LINE is given, assume it represents a line and compute its indentation."
  346. (if line
  347. (when (string-match "^ *" (org-remove-tabs line))
  348. (match-end 0))
  349. (save-excursion
  350. (beginning-of-line 1)
  351. (skip-chars-forward " \t")
  352. (current-column))))
  353. (defun org-do-remove-indentation (&optional n)
  354. "Remove the maximum common indentation from the buffer.
  355. When optional argument N is a positive integer, remove exactly
  356. that much characters from indentation, if possible. Return nil
  357. if it fails."
  358. (catch :exit
  359. (goto-char (point-min))
  360. ;; Find maximum common indentation, if not specified.
  361. (let ((n (or n
  362. (let ((min-ind (point-max)))
  363. (save-excursion
  364. (while (re-search-forward "^[ \t]*\\S-" nil t)
  365. (let ((ind (1- (current-column))))
  366. (if (zerop ind) (throw :exit nil)
  367. (setq min-ind (min min-ind ind))))))
  368. min-ind))))
  369. (if (zerop n) (throw :exit nil)
  370. ;; Remove exactly N indentation, but give up if not possible.
  371. (while (not (eobp))
  372. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  373. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  374. ((< ind n) (throw :exit nil))
  375. (t (indent-line-to (- ind n))))
  376. (forward-line)))
  377. ;; Signal success.
  378. t))))
  379. ;;; String manipulation
  380. (defun org-string< (a b)
  381. (org-string-collate-lessp a b))
  382. (defun org-string<= (a b)
  383. (or (string= a b) (org-string-collate-lessp a b)))
  384. (defun org-string>= (a b)
  385. (not (org-string-collate-lessp a b)))
  386. (defun org-string> (a b)
  387. (and (not (string= a b))
  388. (not (org-string-collate-lessp a b))))
  389. (defun org-string<> (a b)
  390. (not (string= a b)))
  391. (defsubst org-trim (s &optional keep-lead)
  392. "Remove whitespace at the beginning and the end of string S.
  393. When optional argument KEEP-LEAD is non-nil, removing blank lines
  394. at the beginning of the string does not affect leading indentation."
  395. (replace-regexp-in-string
  396. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  397. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  398. (defun org-string-nw-p (s)
  399. "Return S if S is a string containing a non-blank character.
  400. Otherwise, return nil."
  401. (and (stringp s)
  402. (string-match-p "[^ \r\t\n]" s)
  403. s))
  404. (defun org-reverse-string (string)
  405. "Return the reverse of STRING."
  406. (apply #'string (nreverse (string-to-list string))))
  407. (defun org-split-string (string &optional separators)
  408. "Splits STRING into substrings at SEPARATORS.
  409. SEPARATORS is a regular expression. When nil, it defaults to
  410. \"[ \f\t\n\r\v]+\".
  411. Unlike `split-string', matching SEPARATORS at the beginning and
  412. end of string are ignored."
  413. (let ((separators (or separators "[ \f\t\n\r\v]+")))
  414. (when (string-match (concat "\\`" separators) string)
  415. (setq string (replace-match "" nil nil string)))
  416. (when (string-match (concat separators "\\'") string)
  417. (setq string (replace-match "" nil nil string)))
  418. (split-string string separators)))
  419. (defun org-string-display (string)
  420. "Return STRING as it is displayed in the current buffer.
  421. This function takes into consideration `invisible' and `display'
  422. text properties."
  423. (let* ((build-from-parts
  424. (lambda (s property filter)
  425. ;; Build a new string out of string S. On every group of
  426. ;; contiguous characters with the same PROPERTY value,
  427. ;; call FILTER on the properties list at the beginning of
  428. ;; the group. If it returns a string, replace the
  429. ;; characters in the group with it. Otherwise, preserve
  430. ;; those characters.
  431. (let ((len (length s))
  432. (new "")
  433. (i 0)
  434. (cursor 0))
  435. (while (setq i (text-property-not-all i len property nil s))
  436. (let ((end (next-single-property-change i property s len))
  437. (value (funcall filter (text-properties-at i s))))
  438. (when value
  439. (setq new (concat new (substring s cursor i) value))
  440. (setq cursor end))
  441. (setq i end)))
  442. (concat new (substring s cursor)))))
  443. (prune-invisible
  444. (lambda (s)
  445. (funcall build-from-parts s 'invisible
  446. (lambda (props)
  447. ;; If `invisible' property in PROPS means text
  448. ;; is to be invisible, return the empty string.
  449. ;; Otherwise return nil so that the part is
  450. ;; skipped.
  451. (and (or (eq t buffer-invisibility-spec)
  452. (assoc-string (plist-get props 'invisible)
  453. buffer-invisibility-spec))
  454. "")))))
  455. (replace-display
  456. (lambda (s)
  457. (funcall build-from-parts s 'display
  458. (lambda (props)
  459. ;; If there is any string specification in
  460. ;; `display' property return it. Also attach
  461. ;; other text properties on the part to that
  462. ;; string (face...).
  463. (let* ((display (plist-get props 'display))
  464. (value (if (stringp display) display
  465. (cl-some #'stringp display))))
  466. (when value
  467. (apply #'propertize
  468. ;; Displayed string could contain
  469. ;; invisible parts, but no nested
  470. ;; display.
  471. (funcall prune-invisible value)
  472. 'display
  473. (and (not (stringp display))
  474. (cl-remove-if #'stringp display))
  475. props))))))))
  476. ;; `display' property overrides `invisible' one. So we first
  477. ;; replace characters with `display' property. Then we remove
  478. ;; invisible characters.
  479. (funcall prune-invisible (funcall replace-display string))))
  480. (defun org-string-width (string)
  481. "Return width of STRING when displayed in the current buffer.
  482. Unlike `string-width', this function takes into consideration
  483. `invisible' and `display' text properties."
  484. (string-width (org-string-display string)))
  485. (defun org-not-nil (v)
  486. "If V not nil, and also not the string \"nil\", then return V.
  487. Otherwise return nil."
  488. (and v (not (equal v "nil")) v))
  489. (defun org-unbracket-string (pre post string)
  490. "Remove PRE/POST from the beginning/end of STRING.
  491. Both PRE and POST must be pre-/suffixes of STRING, or neither is
  492. removed."
  493. (if (and (string-prefix-p pre string)
  494. (string-suffix-p post string))
  495. (substring string (length pre) (- (length post)))
  496. string))
  497. (defsubst org-current-line-string (&optional to-here)
  498. (buffer-substring (point-at-bol) (if to-here (point) (point-at-eol))))
  499. (defun org-shorten-string (s maxlength)
  500. "Shorten string S so that it is no longer than MAXLENGTH characters.
  501. If the string is shorter or has length MAXLENGTH, just return the
  502. original string. If it is longer, the functions finds a space in the
  503. string, breaks this string off at that locations and adds three dots
  504. as ellipsis. Including the ellipsis, the string will not be longer
  505. than MAXLENGTH. If finding a good breaking point in the string does
  506. not work, the string is just chopped off in the middle of a word
  507. if necessary."
  508. (if (<= (length s) maxlength)
  509. s
  510. (let* ((n (max (- maxlength 4) 1))
  511. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  512. (if (string-match re s)
  513. (concat (match-string 1 s) "...")
  514. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  515. (defun org-remove-tabs (s &optional width)
  516. "Replace tabulators in S with spaces.
  517. Assumes that s is a single line, starting in column 0."
  518. (setq width (or width tab-width))
  519. (while (string-match "\t" s)
  520. (setq s (replace-match
  521. (make-string
  522. (- (* width (/ (+ (match-beginning 0) width) width))
  523. (match-beginning 0)) ?\ )
  524. t t s)))
  525. s)
  526. (defun org-wrap (string &optional width lines)
  527. "Wrap string to either a number of lines, or a width in characters.
  528. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  529. that costs. If there is a word longer than WIDTH, the text is actually
  530. wrapped to the length of that word.
  531. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  532. many lines, whatever width that takes.
  533. The return value is a list of lines, without newlines at the end."
  534. (let* ((words (split-string string))
  535. (maxword (apply 'max (mapcar 'org-string-width words)))
  536. w ll)
  537. (cond (width
  538. (org--do-wrap words (max maxword width)))
  539. (lines
  540. (setq w maxword)
  541. (setq ll (org--do-wrap words maxword))
  542. (if (<= (length ll) lines)
  543. ll
  544. (setq ll words)
  545. (while (> (length ll) lines)
  546. (setq w (1+ w))
  547. (setq ll (org--do-wrap words w)))
  548. ll))
  549. (t (error "Cannot wrap this")))))
  550. (defun org--do-wrap (words width)
  551. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  552. (let (lines line)
  553. (while words
  554. (setq line (pop words))
  555. (while (and words (< (+ (length line) (length (car words))) width))
  556. (setq line (concat line " " (pop words))))
  557. (setq lines (push line lines)))
  558. (nreverse lines)))
  559. (defun org-remove-indentation (code &optional n)
  560. "Remove maximum common indentation in string CODE and return it.
  561. N may optionally be the number of columns to remove. Return CODE
  562. as-is if removal failed."
  563. (with-temp-buffer
  564. (insert code)
  565. (if (org-do-remove-indentation n) (buffer-string) code)))
  566. ;;; List manipulation
  567. (defsubst org-get-alist-option (option key)
  568. (cond ((eq key t) t)
  569. ((eq option t) t)
  570. ((assoc key option) (cdr (assoc key option)))
  571. (t (let ((r (cdr (assq 'default option))))
  572. (if (listp r) (delq nil r) r)))))
  573. (defsubst org-last (list)
  574. "Return the last element of LIST."
  575. (car (last list)))
  576. (defsubst org-uniquify (list)
  577. "Non-destructively remove duplicate elements from LIST."
  578. (let ((res (copy-sequence list))) (delete-dups res)))
  579. (defun org-uniquify-alist (alist)
  580. "Merge elements of ALIST with the same key.
  581. For example, in this alist:
  582. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  583. => \\='((a 1 3) (b 2))
  584. merge (a 1) and (a 3) into (a 1 3).
  585. The function returns the new ALIST."
  586. (let (rtn)
  587. (dolist (e alist rtn)
  588. (let (n)
  589. (if (not (assoc (car e) rtn))
  590. (push e rtn)
  591. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  592. (setq rtn (assq-delete-all (car e) rtn))
  593. (push n rtn))))))
  594. (defun org-delete-all (elts list)
  595. "Remove all elements in ELTS from LIST.
  596. Comparison is done with `equal'. It is a destructive operation
  597. that may remove elements by altering the list structure."
  598. (while elts
  599. (setq list (delete (pop elts) list)))
  600. list)
  601. (defun org-plist-delete (plist property)
  602. "Delete PROPERTY from PLIST.
  603. This is in contrast to merely setting it to 0."
  604. (let (p)
  605. (while plist
  606. (if (not (eq property (car plist)))
  607. (setq p (plist-put p (car plist) (nth 1 plist))))
  608. (setq plist (cddr plist)))
  609. p))
  610. (defun org-combine-plists (&rest plists)
  611. "Create a single property list from all plists in PLISTS.
  612. The process starts by copying the first list, and then setting properties
  613. from the other lists. Settings in the last list are the most significant
  614. ones and overrule settings in the other lists."
  615. (let ((rtn (copy-sequence (pop plists)))
  616. p v ls)
  617. (while plists
  618. (setq ls (pop plists))
  619. (while ls
  620. (setq p (pop ls) v (pop ls))
  621. (setq rtn (plist-put rtn p v))))
  622. rtn))
  623. ;;; Regexp matching
  624. (defsubst org-pos-in-match-range (pos n)
  625. (and (match-beginning n)
  626. (<= (match-beginning n) pos)
  627. (>= (match-end n) pos)))
  628. (defun org-skip-whitespace ()
  629. "Skip over space, tabs and newline characters."
  630. (skip-chars-forward " \t\n\r"))
  631. (defun org-match-line (regexp)
  632. "Match REGEXP at the beginning of the current line."
  633. (save-excursion
  634. (beginning-of-line)
  635. (looking-at regexp)))
  636. (defun org-match-any-p (re list)
  637. "Non-nil if regexp RE matches an element in LIST."
  638. (cl-some (lambda (x) (string-match-p re x)) list))
  639. (defun org-in-regexp (regexp &optional nlines visually)
  640. "Check if point is inside a match of REGEXP.
  641. Normally only the current line is checked, but you can include
  642. NLINES extra lines around point into the search. If VISUALLY is
  643. set, require that the cursor is not after the match but really
  644. on, so that the block visually is on the match.
  645. Return nil or a cons cell (BEG . END) where BEG and END are,
  646. respectively, the positions at the beginning and the end of the
  647. match."
  648. (catch :exit
  649. (let ((pos (point))
  650. (eol (line-end-position (if nlines (1+ nlines) 1))))
  651. (save-excursion
  652. (beginning-of-line (- 1 (or nlines 0)))
  653. (while (and (re-search-forward regexp eol t)
  654. (<= (match-beginning 0) pos))
  655. (let ((end (match-end 0)))
  656. (when (or (> end pos) (and (= end pos) (not visually)))
  657. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  658. (defun org-point-in-group (point group &optional context)
  659. "Check if POINT is in match-group GROUP.
  660. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  661. match. If the match group does not exist or point is not inside it,
  662. return nil."
  663. (and (match-beginning group)
  664. (>= point (match-beginning group))
  665. (<= point (match-end group))
  666. (if context
  667. (list context (match-beginning group) (match-end group))
  668. t)))
  669. ;;; Motion
  670. (defsubst org-goto-line (N)
  671. (save-restriction
  672. (widen)
  673. (goto-char (point-min))
  674. (forward-line (1- N))))
  675. (defsubst org-current-line (&optional pos)
  676. (save-excursion
  677. (and pos (goto-char pos))
  678. ;; works also in narrowed buffer, because we start at 1, not point-min
  679. (+ (if (bolp) 1 0) (count-lines 1 (point)))))
  680. ;;; Text properties
  681. (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
  682. rear-nonsticky t mouse-map t fontified t
  683. org-emphasis t)
  684. "Properties to remove when a string without properties is wanted.")
  685. (defsubst org-no-properties (s &optional restricted)
  686. "Remove all text properties from string S.
  687. When RESTRICTED is non-nil, only remove the properties listed
  688. in `org-rm-props'."
  689. (if restricted (remove-text-properties 0 (length s) org-rm-props s)
  690. (set-text-properties 0 (length s) nil s))
  691. s)
  692. (defun org-add-props (string plist &rest props)
  693. "Add text properties to entire string, from beginning to end.
  694. PLIST may be a list of properties, PROPS are individual properties and values
  695. that will be added to PLIST. Returns the string that was modified."
  696. (declare (indent 2))
  697. (add-text-properties
  698. 0 (length string) (if props (append plist props) plist) string)
  699. string)
  700. (defun org-make-parameter-alist (flat)
  701. "Return alist based on FLAT.
  702. FLAT is a list with alternating symbol names and values. The
  703. returned alist is a list of lists with the symbol name in car and
  704. the value in cdr."
  705. (when flat
  706. (cons (list (car flat) (cadr flat))
  707. (org-make-parameter-alist (cddr flat)))))
  708. (defsubst org-get-at-bol (property)
  709. "Get text property PROPERTY at the beginning of line."
  710. (get-text-property (point-at-bol) property))
  711. (defun org-get-at-eol (property n)
  712. "Get text property PROPERTY at the end of line less N characters."
  713. (get-text-property (- (point-at-eol) n) property))
  714. (defun org-find-text-property-in-string (prop s)
  715. "Return the first non-nil value of property PROP in string S."
  716. (or (get-text-property 0 prop s)
  717. (get-text-property (or (next-single-property-change 0 prop s) 0)
  718. prop s)))
  719. (defun org-invisible-p (&optional pos)
  720. "Non-nil if the character after POS is invisible.
  721. If POS is nil, use `point' instead."
  722. (get-char-property (or pos (point)) 'invisible))
  723. (defun org-truely-invisible-p ()
  724. "Check if point is at a character currently not visible.
  725. This version does not only check the character property, but also
  726. `visible-mode'."
  727. (unless (bound-and-true-p visible-mode)
  728. (org-invisible-p)))
  729. (defun org-invisible-p2 ()
  730. "Check if point is at a character currently not visible.
  731. If the point is at EOL (and not at the beginning of a buffer too),
  732. move it back by one char before doing this check."
  733. (save-excursion
  734. (when (and (eolp) (not (bobp)))
  735. (backward-char 1))
  736. (org-invisible-p)))
  737. ;;; Local variables
  738. (defconst org-unique-local-variables
  739. '(org-element--cache
  740. org-element--cache-objects
  741. org-element--cache-sync-keys
  742. org-element--cache-sync-requests
  743. org-element--cache-sync-timer)
  744. "List of local variables that cannot be transferred to another buffer.")
  745. (defun org-get-local-variables ()
  746. "Return a list of all local variables in an Org mode buffer."
  747. (delq nil
  748. (mapcar
  749. (lambda (x)
  750. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  751. (name (car binding)))
  752. (and (not (get name 'org-state))
  753. (not (memq name org-unique-local-variables))
  754. (string-match-p
  755. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  756. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  757. (symbol-name name))
  758. binding)))
  759. (with-temp-buffer
  760. (org-mode)
  761. (buffer-local-variables)))))
  762. (defun org-clone-local-variables (from-buffer &optional regexp)
  763. "Clone local variables from FROM-BUFFER.
  764. Optional argument REGEXP selects variables to clone."
  765. (dolist (pair (buffer-local-variables from-buffer))
  766. (pcase pair
  767. (`(,name . ,value) ;ignore unbound variables
  768. (when (and (not (memq name org-unique-local-variables))
  769. (or (null regexp) (string-match-p regexp (symbol-name name))))
  770. (ignore-errors (set (make-local-variable name) value)))))))
  771. ;;; Miscellaneous
  772. (defsubst org-call-with-arg (command arg)
  773. "Call COMMAND interactively, but pretend prefix arg was ARG."
  774. (let ((current-prefix-arg arg)) (call-interactively command)))
  775. (defsubst org-check-external-command (cmd &optional use no-error)
  776. "Check if external program CMD for USE exists, error if not.
  777. When the program does exist, return its path.
  778. When it does not exist and NO-ERROR is set, return nil.
  779. Otherwise, throw an error. The optional argument USE can describe what this
  780. program is needed for, so that the error message can be more informative."
  781. (or (executable-find cmd)
  782. (if no-error
  783. nil
  784. (error "Can't find `%s'%s" cmd
  785. (if use (format " (%s)" use) "")))))
  786. (defun org-display-warning (message)
  787. "Display the given MESSAGE as a warning."
  788. (display-warning 'org message :warning))
  789. (defun org-unlogged-message (&rest args)
  790. "Display a message, but avoid logging it in the *Messages* buffer."
  791. (let ((message-log-max nil))
  792. (apply #'message args)))
  793. (defun org-let (list &rest body)
  794. (eval (cons 'let (cons list body))))
  795. (put 'org-let 'lisp-indent-function 1)
  796. (defun org-let2 (list1 list2 &rest body)
  797. (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
  798. (put 'org-let2 'lisp-indent-function 2)
  799. (defun org-eval (form)
  800. "Eval FORM and return result."
  801. (condition-case error
  802. (eval form)
  803. (error (format "%%![Error: %s]" error))))
  804. (defvar org-outline-regexp) ; defined in org.el
  805. (defvar org-odd-levels-only) ; defined in org.el
  806. (defvar org-inlinetask-min-level) ; defined in org-inlinetask.el
  807. (defun org-get-limited-outline-regexp ()
  808. "Return outline-regexp with limited number of levels.
  809. The number of levels is controlled by `org-inlinetask-min-level'"
  810. (cond ((not (derived-mode-p 'org-mode))
  811. outline-regexp)
  812. ((not (featurep 'org-inlinetask))
  813. org-outline-regexp)
  814. (t
  815. (let* ((limit-level (1- org-inlinetask-min-level))
  816. (nstars (if org-odd-levels-only
  817. (1- (* limit-level 2))
  818. limit-level)))
  819. (format "\\*\\{1,%d\\} " nstars)))))
  820. (provide 'org-macs)
  821. ;;; org-macs.el ends here