org-macs.el 45 KB

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