org-macs.el 37 KB

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