org-macs.el 54 KB

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