org-macs.el 41 KB

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