org-macs.el 39 KB

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