org-macs.el 55 KB

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