org-macs.el 56 KB

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