org-macs.el 56 KB

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