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