test files: use cl- prefixed functions, and require cl-lib
[org-mode/org-tableheadings.git] / lisp / org-macs.el
blob91a98aaf78733588316cb722f2aa61b362d34840
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))
205 ;;; Buffer and windows
207 (defun org-base-buffer (buffer)
208 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
209 (when buffer
210 (or (buffer-base-buffer buffer)
211 buffer)))
213 (defun org-find-base-buffer-visiting (file)
214 "Like `find-buffer-visiting' but always return the base buffer and
215 not an indirect buffer."
216 (let ((buf (or (get-file-buffer file)
217 (find-buffer-visiting file))))
218 (org-base-buffer buf)))
220 (defun org-switch-to-buffer-other-window (&rest args)
221 "Switch to buffer in a second window on the current frame.
222 In particular, do not allow pop-up frames.
223 Returns the newly created buffer."
224 (org-no-popups (apply #'switch-to-buffer-other-window args)))
226 (defun org-fit-window-to-buffer (&optional window max-height min-height
227 shrink-only)
228 "Fit WINDOW to the buffer, but only if it is not a side-by-side window.
229 WINDOW defaults to the selected window. MAX-HEIGHT and MIN-HEIGHT are
230 passed through to `fit-window-to-buffer'. If SHRINK-ONLY is set, call
231 `shrink-window-if-larger-than-buffer' instead, the height limit is
232 ignored in this case."
233 (cond ((if (fboundp 'window-full-width-p)
234 (not (window-full-width-p window))
235 ;; Do nothing if another window would suffer.
236 (> (frame-width) (window-width window))))
237 ((and (fboundp 'fit-window-to-buffer) (not shrink-only))
238 (fit-window-to-buffer window max-height min-height))
239 ((fboundp 'shrink-window-if-larger-than-buffer)
240 (shrink-window-if-larger-than-buffer window)))
241 (or window (selected-window)))
245 ;;; File
247 (defun org-file-newer-than-p (file time)
248 "Non-nil if FILE is newer than TIME.
249 FILE is a filename, as a string, TIME is a list of integers, as
250 returned by, e.g., `current-time'."
251 (and (file-exists-p file)
252 ;; Only compare times up to whole seconds as some file-systems
253 ;; (e.g. HFS+) do not retain any finer granularity. As
254 ;; a consequence, make sure we return non-nil when the two
255 ;; times are equal.
256 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
257 (cl-subseq time 0 2)))))
259 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
260 "Compile a SOURCE file using PROCESS.
262 PROCESS is either a function or a list of shell commands, as
263 strings. EXT is a file extension, without the leading dot, as
264 a string. It is used to check if the process actually succeeded.
266 PROCESS must create a file with the same base name and directory
267 as SOURCE, but ending with EXT. The function then returns its
268 filename. Otherwise, it raises an error. The error message can
269 then be refined by providing string ERR-MSG, which is appended to
270 the standard message.
272 If PROCESS is a function, it is called with a single argument:
273 the SOURCE file.
275 If it is a list of commands, each of them is called using
276 `shell-command'. By default, in each command, %b, %f, %F, %o and
277 %O are replaced with, respectively, SOURCE base name, name, full
278 name, directory and absolute output file name. It is possible,
279 however, to use more place-holders by specifying them in optional
280 argument SPEC, as an alist following the pattern
282 (CHARACTER . REPLACEMENT-STRING).
284 When PROCESS is a list of commands, optional argument LOG-BUF can
285 be set to a buffer or a buffer name. `shell-command' then uses
286 it for output."
287 (let* ((base-name (file-name-base source))
288 (full-name (file-truename source))
289 (out-dir (or (file-name-directory source) "./"))
290 (output (expand-file-name (concat base-name "." ext) out-dir))
291 (time (current-time))
292 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
293 (save-window-excursion
294 (pcase process
295 ((pred functionp) (funcall process (shell-quote-argument source)))
296 ((pred consp)
297 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
298 (spec (append spec
299 `((?b . ,(shell-quote-argument base-name))
300 (?f . ,(shell-quote-argument source))
301 (?F . ,(shell-quote-argument full-name))
302 (?o . ,(shell-quote-argument out-dir))
303 (?O . ,(shell-quote-argument output))))))
304 (dolist (command process)
305 (shell-command (format-spec command spec) log-buf))
306 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
307 (_ (error "No valid command to process %S%s" source err-msg))))
308 ;; Check for process failure. Output file is expected to be
309 ;; located in the same directory as SOURCE.
310 (unless (org-file-newer-than-p output time)
311 (error (format "File %S wasn't produced%s" output err-msg)))
312 output))
316 ;;; Indentation
318 (defun org-do-remove-indentation (&optional n)
319 "Remove the maximum common indentation from the buffer.
320 When optional argument N is a positive integer, remove exactly
321 that much characters from indentation, if possible. Return nil
322 if it fails."
323 (catch :exit
324 (goto-char (point-min))
325 ;; Find maximum common indentation, if not specified.
326 (let ((n (or n
327 (let ((min-ind (point-max)))
328 (save-excursion
329 (while (re-search-forward "^[ \t]*\\S-" nil t)
330 (let ((ind (1- (current-column))))
331 (if (zerop ind) (throw :exit nil)
332 (setq min-ind (min min-ind ind))))))
333 min-ind))))
334 (if (zerop n) (throw :exit nil)
335 ;; Remove exactly N indentation, but give up if not possible.
336 (while (not (eobp))
337 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
338 (cond ((eolp) (delete-region (line-beginning-position) (point)))
339 ((< ind n) (throw :exit nil))
340 (t (indent-line-to (- ind n))))
341 (forward-line)))
342 ;; Signal success.
343 t))))
347 ;;; Input
349 (defun org-read-function (prompt &optional allow-empty?)
350 "Prompt for a function.
351 If ALLOW-EMPTY? is non-nil, return nil rather than raising an
352 error when the user input is empty."
353 (let ((func (completing-read prompt obarray #'fboundp t)))
354 (cond ((not (string= func ""))
355 (intern func))
356 (allow-empty? nil)
357 (t (user-error "Empty input is not valid")))))
359 (defun org-completing-read (&rest args)
360 "Completing-read with SPACE being a normal character."
361 (let ((enable-recursive-minibuffers t)
362 (minibuffer-local-completion-map
363 (copy-keymap minibuffer-local-completion-map)))
364 (define-key minibuffer-local-completion-map " " 'self-insert-command)
365 (define-key minibuffer-local-completion-map "?" 'self-insert-command)
366 (define-key minibuffer-local-completion-map (kbd "C-c !")
367 'org-time-stamp-inactive)
368 (apply #'completing-read args)))
370 (defun org--mks-read-key (allowed-keys prompt)
371 "Read a key and ensure it is a member of ALLOWED-KEYS.
372 TAB, SPC and RET are treated equivalently."
373 (let* ((key (char-to-string
374 (pcase (read-char-exclusive prompt)
375 ((or ?\s ?\t ?\r) ?\t)
376 (char char)))))
377 (if (member key allowed-keys)
379 (message "Invalid key: `%s'" key)
380 (sit-for 1)
381 (org--mks-read-key allowed-keys prompt))))
383 (defun org-mks (table title &optional prompt specials)
384 "Select a member of an alist with multiple keys.
386 TABLE is the alist which should contain entries where the car is a string.
387 There should be two types of entries.
389 1. prefix descriptions like (\"a\" \"Description\")
390 This indicates that `a' is a prefix key for multi-letter selection, and
391 that there are entries following with keys like \"ab\", \"ax\"...
393 2. Select-able members must have more than two elements, with the first
394 being the string of keys that lead to selecting it, and the second a
395 short description string of the item.
397 The command will then make a temporary buffer listing all entries
398 that can be selected with a single key, and all the single key
399 prefixes. When you press the key for a single-letter entry, it is selected.
400 When you press a prefix key, the commands (and maybe further prefixes)
401 under this key will be shown and offered for selection.
403 TITLE will be placed over the selection in the temporary buffer,
404 PROMPT will be used when prompting for a key. SPECIALS is an
405 alist with (\"key\" \"description\") entries. When one of these
406 is selected, only the bare key is returned."
407 (save-window-excursion
408 (let ((inhibit-quit t)
409 (buffer (org-switch-to-buffer-other-window "*Org Select*"))
410 (prompt (or prompt "Select: "))
411 current)
412 (unwind-protect
413 (catch 'exit
414 (while t
415 (erase-buffer)
416 (insert title "\n\n")
417 (let ((des-keys nil)
418 (allowed-keys '("\C-g"))
419 (tab-alternatives '("\s" "\t" "\r"))
420 (cursor-type nil))
421 ;; Populate allowed keys and descriptions keys
422 ;; available with CURRENT selector.
423 (let ((re (format "\\`%s\\(.\\)\\'"
424 (if current (regexp-quote current) "")))
425 (prefix (if current (concat current " ") "")))
426 (dolist (entry table)
427 (pcase entry
428 ;; Description.
429 (`(,(and key (pred (string-match re))) ,desc)
430 (let ((k (match-string 1 key)))
431 (push k des-keys)
432 ;; Keys ending in tab, space or RET are equivalent.
433 (if (member k tab-alternatives)
434 (push "\t" allowed-keys)
435 (push k allowed-keys))
436 (insert prefix "[" k "]" "..." " " desc "..." "\n")))
437 ;; Usable entry.
438 (`(,(and key (pred (string-match re))) ,desc . ,_)
439 (let ((k (match-string 1 key)))
440 (insert prefix "[" k "]" " " desc "\n")
441 (push k allowed-keys)))
442 (_ nil))))
443 ;; Insert special entries, if any.
444 (when specials
445 (insert "----------------------------------------------------\
446 ---------------------------\n")
447 (pcase-dolist (`(,key ,description) specials)
448 (insert (format "[%s] %s\n" key description))
449 (push key allowed-keys)))
450 ;; Display UI and let user select an entry or
451 ;; a sub-level prefix.
452 (goto-char (point-min))
453 (unless (pos-visible-in-window-p (point-max))
454 (org-fit-window-to-buffer))
455 (let ((pressed (org--mks-read-key allowed-keys prompt)))
456 (setq current (concat current pressed))
457 (cond
458 ((equal pressed "\C-g") (user-error "Abort"))
459 ;; Selection is a prefix: open a new menu.
460 ((member pressed des-keys))
461 ;; Selection matches an association: return it.
462 ((let ((entry (assoc current table)))
463 (and entry (throw 'exit entry))))
464 ;; Selection matches a special entry: return the
465 ;; selection prefix.
466 ((assoc current specials) (throw 'exit current))
467 (t (error "No entry available")))))))
468 (when buffer (kill-buffer buffer))))))
471 ;;; List manipulation
473 (defsubst org-get-alist-option (option key)
474 (cond ((eq key t) t)
475 ((eq option t) t)
476 ((assoc key option) (cdr (assoc key option)))
477 (t (let ((r (cdr (assq 'default option))))
478 (if (listp r) (delq nil r) r)))))
480 (defsubst org-last (list)
481 "Return the last element of LIST."
482 (car (last list)))
484 (defsubst org-uniquify (list)
485 "Non-destructively remove duplicate elements from LIST."
486 (let ((res (copy-sequence list))) (delete-dups res)))
488 (defun org-uniquify-alist (alist)
489 "Merge elements of ALIST with the same key.
491 For example, in this alist:
493 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
494 => \\='((a 1 3) (b 2))
496 merge (a 1) and (a 3) into (a 1 3).
498 The function returns the new ALIST."
499 (let (rtn)
500 (dolist (e alist rtn)
501 (let (n)
502 (if (not (assoc (car e) rtn))
503 (push e rtn)
504 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
505 (setq rtn (assq-delete-all (car e) rtn))
506 (push n rtn))))))
508 (defun org-delete-all (elts list)
509 "Remove all elements in ELTS from LIST.
510 Comparison is done with `equal'. It is a destructive operation
511 that may remove elements by altering the list structure."
512 (while elts
513 (setq list (delete (pop elts) list)))
514 list)
516 (defun org-plist-delete (plist property)
517 "Delete PROPERTY from PLIST.
518 This is in contrast to merely setting it to 0."
519 (let (p)
520 (while plist
521 (if (not (eq property (car plist)))
522 (setq p (plist-put p (car plist) (nth 1 plist))))
523 (setq plist (cddr plist)))
526 (defun org-combine-plists (&rest plists)
527 "Create a single property list from all plists in PLISTS.
528 The process starts by copying the first list, and then setting properties
529 from the other lists. Settings in the last list are the most significant
530 ones and overrule settings in the other lists."
531 (let ((rtn (copy-sequence (pop plists)))
532 p v ls)
533 (while plists
534 (setq ls (pop plists))
535 (while ls
536 (setq p (pop ls) v (pop ls))
537 (setq rtn (plist-put rtn p v))))
538 rtn))
542 ;;; Local variables
544 (defconst org-unique-local-variables
545 '(org-element--cache
546 org-element--cache-objects
547 org-element--cache-sync-keys
548 org-element--cache-sync-requests
549 org-element--cache-sync-timer)
550 "List of local variables that cannot be transferred to another buffer.")
552 (defun org-get-local-variables ()
553 "Return a list of all local variables in an Org mode buffer."
554 (delq nil
555 (mapcar
556 (lambda (x)
557 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
558 (name (car binding)))
559 (and (not (get name 'org-state))
560 (not (memq name org-unique-local-variables))
561 (string-match-p
562 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
563 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
564 (symbol-name name))
565 binding)))
566 (with-temp-buffer
567 (org-mode)
568 (buffer-local-variables)))))
570 (defun org-clone-local-variables (from-buffer &optional regexp)
571 "Clone local variables from FROM-BUFFER.
572 Optional argument REGEXP selects variables to clone."
573 (dolist (pair (buffer-local-variables from-buffer))
574 (pcase pair
575 (`(,name . ,value) ;ignore unbound variables
576 (when (and (not (memq name org-unique-local-variables))
577 (or (null regexp) (string-match-p regexp (symbol-name name))))
578 (ignore-errors (set (make-local-variable name) value)))))))
582 ;;; Logic
584 (defsubst org-xor (a b)
585 "Exclusive `or'."
586 (if a (not b) b))
590 ;;; Miscellaneous
592 (defsubst org-call-with-arg (command arg)
593 "Call COMMAND interactively, but pretend prefix arg was ARG."
594 (let ((current-prefix-arg arg)) (call-interactively command)))
596 (defsubst org-check-external-command (cmd &optional use no-error)
597 "Check if external program CMD for USE exists, error if not.
598 When the program does exist, return its path.
599 When it does not exist and NO-ERROR is set, return nil.
600 Otherwise, throw an error. The optional argument USE can describe what this
601 program is needed for, so that the error message can be more informative."
602 (or (executable-find cmd)
603 (if no-error
605 (error "Can't find `%s'%s" cmd
606 (if use (format " (%s)" use) "")))))
608 (defun org-display-warning (message)
609 "Display the given MESSAGE as a warning."
610 (display-warning 'org message :warning))
612 (defun org-unlogged-message (&rest args)
613 "Display a message, but avoid logging it in the *Messages* buffer."
614 (let ((message-log-max nil))
615 (apply #'message args)))
617 (defun org-let (list &rest body)
618 (eval (cons 'let (cons list body))))
619 (put 'org-let 'lisp-indent-function 1)
621 (defun org-let2 (list1 list2 &rest body)
622 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
623 (put 'org-let2 'lisp-indent-function 2)
625 (defun org-eval (form)
626 "Eval FORM and return result."
627 (condition-case error
628 (eval form)
629 (error (format "%%![Error: %s]" error))))
631 (defvar org-outline-regexp) ; defined in org.el
632 (defvar org-odd-levels-only) ; defined in org.el
633 (defvar org-inlinetask-min-level) ; defined in org-inlinetask.el
634 (defun org-get-limited-outline-regexp ()
635 "Return outline-regexp with limited number of levels.
636 The number of levels is controlled by `org-inlinetask-min-level'"
637 (cond ((not (derived-mode-p 'org-mode))
638 outline-regexp)
639 ((not (featurep 'org-inlinetask))
640 org-outline-regexp)
642 (let* ((limit-level (1- org-inlinetask-min-level))
643 (nstars (if org-odd-levels-only
644 (1- (* limit-level 2))
645 limit-level)))
646 (format "\\*\\{1,%d\\} " nstars)))))
649 (provide 'org-macs)
651 ;;; Motion
653 (defsubst org-goto-line (N)
654 (save-restriction
655 (widen)
656 (goto-char (point-min))
657 (forward-line (1- N))))
659 (defsubst org-current-line (&optional pos)
660 (save-excursion
661 (and pos (goto-char pos))
662 ;; works also in narrowed buffer, because we start at 1, not point-min
663 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
667 ;;; Overlays
669 (defun org-overlay-display (ovl text &optional face evap)
670 "Make overlay OVL display TEXT with face FACE."
671 (overlay-put ovl 'display text)
672 (when face (overlay-put ovl 'face face))
673 (when evap (overlay-put ovl 'evaporate t)))
675 (defun org-overlay-before-string (ovl text &optional face evap)
676 "Make overlay OVL display TEXT with face FACE."
677 (when face (org-add-props text nil 'face face))
678 (overlay-put ovl 'before-string text)
679 (when evap (overlay-put ovl 'evaporate t)))
681 (defun org-find-overlays (prop &optional pos delete)
682 "Find all overlays specifying PROP at POS or point.
683 If DELETE is non-nil, delete all those overlays."
684 (let (found)
685 (dolist (ov (overlays-at (or pos (point))) found)
686 (cond ((not (overlay-get ov prop)))
687 (delete (delete-overlay ov))
688 (t (push ov found))))))
690 (defun org-flag-region (from to flag spec)
691 "Hide or show lines from FROM to TO, according to FLAG.
692 SPEC is the invisibility spec, as a symbol."
693 (remove-overlays from to 'invisible spec)
694 ;; Use `front-advance' since text right before to the beginning of
695 ;; the overlay belongs to the visible line than to the contents.
696 (when flag
697 (let ((o (make-overlay from to nil 'front-advance)))
698 (overlay-put o 'evaporate t)
699 (overlay-put o 'invisible spec)
700 (overlay-put o 'isearch-open-invisible #'delete-overlay))))
704 ;;; Regexp matching
706 (defsubst org-pos-in-match-range (pos n)
707 (and (match-beginning n)
708 (<= (match-beginning n) pos)
709 (>= (match-end n) pos)))
711 (defun org-skip-whitespace ()
712 "Skip over space, tabs and newline characters."
713 (skip-chars-forward " \t\n\r"))
715 (defun org-match-line (regexp)
716 "Match REGEXP at the beginning of the current line."
717 (save-excursion
718 (beginning-of-line)
719 (looking-at regexp)))
721 (defun org-match-any-p (re list)
722 "Non-nil if regexp RE matches an element in LIST."
723 (cl-some (lambda (x) (string-match-p re x)) list))
725 (defun org-in-regexp (regexp &optional nlines visually)
726 "Check if point is inside a match of REGEXP.
728 Normally only the current line is checked, but you can include
729 NLINES extra lines around point into the search. If VISUALLY is
730 set, require that the cursor is not after the match but really
731 on, so that the block visually is on the match.
733 Return nil or a cons cell (BEG . END) where BEG and END are,
734 respectively, the positions at the beginning and the end of the
735 match."
736 (catch :exit
737 (let ((pos (point))
738 (eol (line-end-position (if nlines (1+ nlines) 1))))
739 (save-excursion
740 (beginning-of-line (- 1 (or nlines 0)))
741 (while (and (re-search-forward regexp eol t)
742 (<= (match-beginning 0) pos))
743 (let ((end (match-end 0)))
744 (when (or (> end pos) (and (= end pos) (not visually)))
745 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
747 (defun org-point-in-group (point group &optional context)
748 "Check if POINT is in match-group GROUP.
749 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
750 match. If the match group does not exist or point is not inside it,
751 return nil."
752 (and (match-beginning group)
753 (>= point (match-beginning group))
754 (<= point (match-end group))
755 (if context
756 (list context (match-beginning group) (match-end group))
757 t)))
761 ;;; String manipulation
763 (defun org-string< (a b)
764 (org-string-collate-lessp a b))
766 (defun org-string<= (a b)
767 (or (string= a b) (org-string-collate-lessp a b)))
769 (defun org-string>= (a b)
770 (not (org-string-collate-lessp a b)))
772 (defun org-string> (a b)
773 (and (not (string= a b))
774 (not (org-string-collate-lessp a b))))
776 (defun org-string<> (a b)
777 (not (string= a b)))
779 (defsubst org-trim (s &optional keep-lead)
780 "Remove whitespace at the beginning and the end of string S.
781 When optional argument KEEP-LEAD is non-nil, removing blank lines
782 at the beginning of the string does not affect leading indentation."
783 (replace-regexp-in-string
784 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
785 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
787 (defun org-string-nw-p (s)
788 "Return S if S is a string containing a non-blank character.
789 Otherwise, return nil."
790 (and (stringp s)
791 (string-match-p "[^ \r\t\n]" s)
794 (defun org-reverse-string (string)
795 "Return the reverse of STRING."
796 (apply #'string (nreverse (string-to-list string))))
798 (defun org-split-string (string &optional separators)
799 "Splits STRING into substrings at SEPARATORS.
801 SEPARATORS is a regular expression. When nil, it defaults to
802 \"[ \f\t\n\r\v]+\".
804 Unlike `split-string', matching SEPARATORS at the beginning and
805 end of string are ignored."
806 (let ((separators (or separators "[ \f\t\n\r\v]+")))
807 (when (string-match (concat "\\`" separators) string)
808 (setq string (replace-match "" nil nil string)))
809 (when (string-match (concat separators "\\'") string)
810 (setq string (replace-match "" nil nil string)))
811 (split-string string separators)))
813 (defun org-string-display (string)
814 "Return STRING as it is displayed in the current buffer.
815 This function takes into consideration `invisible' and `display'
816 text properties."
817 (let* ((build-from-parts
818 (lambda (s property filter)
819 ;; Build a new string out of string S. On every group of
820 ;; contiguous characters with the same PROPERTY value,
821 ;; call FILTER on the properties list at the beginning of
822 ;; the group. If it returns a string, replace the
823 ;; characters in the group with it. Otherwise, preserve
824 ;; those characters.
825 (let ((len (length s))
826 (new "")
827 (i 0)
828 (cursor 0))
829 (while (setq i (text-property-not-all i len property nil s))
830 (let ((end (next-single-property-change i property s len))
831 (value (funcall filter (text-properties-at i s))))
832 (when value
833 (setq new (concat new (substring s cursor i) value))
834 (setq cursor end))
835 (setq i end)))
836 (concat new (substring s cursor)))))
837 (prune-invisible
838 (lambda (s)
839 (funcall build-from-parts s 'invisible
840 (lambda (props)
841 ;; If `invisible' property in PROPS means text
842 ;; is to be invisible, return the empty string.
843 ;; Otherwise return nil so that the part is
844 ;; skipped.
845 (and (or (eq t buffer-invisibility-spec)
846 (assoc-string (plist-get props 'invisible)
847 buffer-invisibility-spec))
848 "")))))
849 (replace-display
850 (lambda (s)
851 (funcall build-from-parts s 'display
852 (lambda (props)
853 ;; If there is any string specification in
854 ;; `display' property return it. Also attach
855 ;; other text properties on the part to that
856 ;; string (face...).
857 (let* ((display (plist-get props 'display))
858 (value (if (stringp display) display
859 (cl-some #'stringp display))))
860 (when value
861 (apply #'propertize
862 ;; Displayed string could contain
863 ;; invisible parts, but no nested
864 ;; display.
865 (funcall prune-invisible value)
866 'display
867 (and (not (stringp display))
868 (cl-remove-if #'stringp display))
869 props))))))))
870 ;; `display' property overrides `invisible' one. So we first
871 ;; replace characters with `display' property. Then we remove
872 ;; invisible characters.
873 (funcall prune-invisible (funcall replace-display string))))
875 (defun org-string-width (string)
876 "Return width of STRING when displayed in the current buffer.
877 Unlike `string-width', this function takes into consideration
878 `invisible' and `display' text properties."
879 (string-width (org-string-display string)))
881 (defun org-not-nil (v)
882 "If V not nil, and also not the string \"nil\", then return V.
883 Otherwise return nil."
884 (and v (not (equal v "nil")) v))
886 (defun org-unbracket-string (pre post string)
887 "Remove PRE/POST from the beginning/end of STRING.
888 Both PRE and POST must be pre-/suffixes of STRING, or neither is
889 removed."
890 (if (and (string-prefix-p pre string)
891 (string-suffix-p post string))
892 (substring string (length pre) (- (length post)))
893 string))
895 (defsubst org-current-line-string (&optional to-here)
896 (buffer-substring (point-at-bol) (if to-here (point) (point-at-eol))))
898 (defun org-shorten-string (s maxlength)
899 "Shorten string S so that it is no longer than MAXLENGTH characters.
900 If the string is shorter or has length MAXLENGTH, just return the
901 original string. If it is longer, the functions finds a space in the
902 string, breaks this string off at that locations and adds three dots
903 as ellipsis. Including the ellipsis, the string will not be longer
904 than MAXLENGTH. If finding a good breaking point in the string does
905 not work, the string is just chopped off in the middle of a word
906 if necessary."
907 (if (<= (length s) maxlength)
909 (let* ((n (max (- maxlength 4) 1))
910 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
911 (if (string-match re s)
912 (concat (match-string 1 s) "...")
913 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
915 (defun org-remove-tabs (s &optional width)
916 "Replace tabulators in S with spaces.
917 Assumes that s is a single line, starting in column 0."
918 (setq width (or width tab-width))
919 (while (string-match "\t" s)
920 (setq s (replace-match
921 (make-string
922 (- (* width (/ (+ (match-beginning 0) width) width))
923 (match-beginning 0)) ?\ )
924 t t s)))
927 (defun org-wrap (string &optional width lines)
928 "Wrap string to either a number of lines, or a width in characters.
929 If WIDTH is non-nil, the string is wrapped to that width, however many lines
930 that costs. If there is a word longer than WIDTH, the text is actually
931 wrapped to the length of that word.
932 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
933 many lines, whatever width that takes.
934 The return value is a list of lines, without newlines at the end."
935 (let* ((words (split-string string))
936 (maxword (apply 'max (mapcar 'org-string-width words)))
937 w ll)
938 (cond (width
939 (org--do-wrap words (max maxword width)))
940 (lines
941 (setq w maxword)
942 (setq ll (org--do-wrap words maxword))
943 (if (<= (length ll) lines)
945 (setq ll words)
946 (while (> (length ll) lines)
947 (setq w (1+ w))
948 (setq ll (org--do-wrap words w)))
949 ll))
950 (t (error "Cannot wrap this")))))
952 (defun org--do-wrap (words width)
953 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
954 (let (lines line)
955 (while words
956 (setq line (pop words))
957 (while (and words (< (+ (length line) (length (car words))) width))
958 (setq line (concat line " " (pop words))))
959 (setq lines (push line lines)))
960 (nreverse lines)))
962 (defun org-remove-indentation (code &optional n)
963 "Remove maximum common indentation in string CODE and return it.
964 N may optionally be the number of columns to remove. Return CODE
965 as-is if removal failed."
966 (with-temp-buffer
967 (insert code)
968 (if (org-do-remove-indentation n) (buffer-string) code)))
972 ;;; Text properties
974 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
975 rear-nonsticky t mouse-map t fontified t
976 org-emphasis t)
977 "Properties to remove when a string without properties is wanted.")
979 (defsubst org-no-properties (s &optional restricted)
980 "Remove all text properties from string S.
981 When RESTRICTED is non-nil, only remove the properties listed
982 in `org-rm-props'."
983 (if restricted (remove-text-properties 0 (length s) org-rm-props s)
984 (set-text-properties 0 (length s) nil s))
986 (defun org-add-props (string plist &rest props)
987 "Add text properties to entire string, from beginning to end.
988 PLIST may be a list of properties, PROPS are individual properties and values
989 that will be added to PLIST. Returns the string that was modified."
990 (declare (indent 2))
991 (add-text-properties
992 0 (length string) (if props (append plist props) plist) string)
993 string)
995 (defun org-make-parameter-alist (flat)
996 "Return alist based on FLAT.
997 FLAT is a list with alternating symbol names and values. The
998 returned alist is a list of lists with the symbol name in car and
999 the value in cdr."
1000 (when flat
1001 (cons (list (car flat) (cadr flat))
1002 (org-make-parameter-alist (cddr flat)))))
1004 (defsubst org-get-at-bol (property)
1005 "Get text property PROPERTY at the beginning of line."
1006 (get-text-property (point-at-bol) property))
1008 (defun org-get-at-eol (property n)
1009 "Get text property PROPERTY at the end of line less N characters."
1010 (get-text-property (- (point-at-eol) n) property))
1012 (defun org-find-text-property-in-string (prop s)
1013 "Return the first non-nil value of property PROP in string S."
1014 (or (get-text-property 0 prop s)
1015 (get-text-property (or (next-single-property-change 0 prop s) 0)
1016 prop s)))
1018 (defun org-invisible-p (&optional pos)
1019 "Non-nil if the character after POS is invisible.
1020 If POS is nil, use `point' instead."
1021 (get-char-property (or pos (point)) 'invisible))
1023 (defun org-truely-invisible-p ()
1024 "Check if point is at a character currently not visible.
1025 This version does not only check the character property, but also
1026 `visible-mode'."
1027 (unless (bound-and-true-p visible-mode)
1028 (org-invisible-p)))
1030 (defun org-invisible-p2 ()
1031 "Check if point is at a character currently not visible.
1032 If the point is at EOL (and not at the beginning of a buffer too),
1033 move it back by one char before doing this check."
1034 (save-excursion
1035 (when (and (eolp) (not (bobp)))
1036 (backward-char 1))
1037 (org-invisible-p)))
1040 ;;; Tables
1042 ;; This macro is placed here because it is used in org.el.
1043 ;; org-table.el requires org.el. So, if we put this macro in its
1044 ;; natural place (org-table), a require loop would result.
1045 (defmacro org-table-with-shrunk-field (&rest body)
1046 "Save field shrunk state, execute BODY and restore state."
1047 (declare (debug (body)))
1048 (org-with-gensyms (end shrunk size)
1049 `(let* ((,shrunk (save-match-data (org-table--shrunk-field)))
1050 (,end (and ,shrunk (copy-marker (overlay-end ,shrunk) t)))
1051 (,size (and ,shrunk (- ,end (overlay-start ,shrunk)))))
1052 (when ,shrunk (delete-overlay ,shrunk))
1053 (unwind-protect (progn ,@body)
1054 (when ,shrunk (move-overlay ,shrunk (- ,end ,size) ,end))))))
1057 ;;; Time
1059 (defun org-2ft (s)
1060 "Convert S to a floating point time.
1061 If S is already a number, just return it. If it is a string,
1062 parse it as a time string and apply `float-time' to it. If S is
1063 nil, just return 0."
1064 (cond
1065 ((numberp s) s)
1066 ((stringp s)
1067 (condition-case nil
1068 (float-time (apply #'encode-time (org-parse-time-string s)))
1069 (error 0.)))
1070 (t 0.)))
1072 (defun org-time= (a b)
1073 (let ((a (org-2ft a))
1074 (b (org-2ft b)))
1075 (and (> a 0) (> b 0) (= a b))))
1077 (defun org-time< (a b)
1078 (let ((a (org-2ft a))
1079 (b (org-2ft b)))
1080 (and (> a 0) (> b 0) (< a b))))
1082 (defun org-time<= (a b)
1083 (let ((a (org-2ft a))
1084 (b (org-2ft b)))
1085 (and (> a 0) (> b 0) (<= a b))))
1087 (defun org-time> (a b)
1088 (let ((a (org-2ft a))
1089 (b (org-2ft b)))
1090 (and (> a 0) (> b 0) (> a b))))
1092 (defun org-time>= (a b)
1093 (let ((a (org-2ft a))
1094 (b (org-2ft b)))
1095 (and (> a 0) (> b 0) (>= a b))))
1097 (defun org-time<> (a b)
1098 (let ((a (org-2ft a))
1099 (b (org-2ft b)))
1100 (and (> a 0) (> b 0) (\= a b))))
1102 (defun org-parse-time-string (s &optional nodefault)
1103 "Parse Org time string S.
1105 If time is not given, defaults to 0:00. However, with optional
1106 NODEFAULT, hour and minute fields are nil if not given.
1108 Throw an error if S in not a valid Org time string.
1110 This should be a lot faster than the `parse-time-string'."
1111 (cond ((string-match org-ts-regexp0 s)
1112 (list 0
1113 (when (or (match-beginning 8) (not nodefault))
1114 (string-to-number (or (match-string 8 s) "0")))
1115 (when (or (match-beginning 7) (not nodefault))
1116 (string-to-number (or (match-string 7 s) "0")))
1117 (string-to-number (match-string 4 s))
1118 (string-to-number (match-string 3 s))
1119 (string-to-number (match-string 2 s))
1120 nil nil nil))
1121 ((string-match "\\`<[^>]+>\\'" s)
1122 (decode-time (seconds-to-time (org-matcher-time s))))
1123 (t (error "Not an Org time string: %s" s))))
1125 (defun org-matcher-time (s)
1126 "Interpret a time comparison value S."
1127 (let ((today (float-time (apply #'encode-time
1128 (append '(0 0 0) (nthcdr 3 (decode-time)))))))
1129 (save-match-data
1130 (cond
1131 ((string= s "<now>") (float-time))
1132 ((string= s "<today>") today)
1133 ((string= s "<tomorrow>") (+ 86400.0 today))
1134 ((string= s "<yesterday>") (- today 86400.0))
1135 ((string-match "\\`<\\([-+][0-9]+\\)\\([hdwmy]\\)>\\'" s)
1136 (+ today
1137 (* (string-to-number (match-string 1 s))
1138 (cdr (assoc (match-string 2 s)
1139 '(("d" . 86400.0) ("w" . 604800.0)
1140 ("m" . 2678400.0) ("y" . 31557600.0)))))))
1141 (t (org-2ft s))))))
1145 ;;; org-macs.el ends here