org-macs.el 45 KB

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