org-macs.el 37 KB

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