org-macs.el 45 KB

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