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