org-macs.el 53 KB

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