org-macs.el 45 KB

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