org-macs.el 55 KB

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