org-macs.el 55 KB

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