org-macs.el 39 KB

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