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