org-macs.el 54 KB

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