org-macs.el 55 KB

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