org-macs.el 54 KB

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