Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-macs.el
blob78c841453e5ee4f566c5a21d3f9b071948e601fb
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 ;;; Input
226 (defun org-read-function (prompt &optional allow-empty?)
227 "Prompt for a function.
228 If ALLOW-EMPTY? is non-nil, return nil rather than raising an
229 error when the user input is empty."
230 (let ((func (completing-read prompt obarray #'fboundp t)))
231 (cond ((not (string= func ""))
232 (intern func))
233 (allow-empty? nil)
234 (t (user-error "Empty input is not valid")))))
236 (defun org-completing-read (&rest args)
237 "Completing-read with SPACE being a normal character."
238 (let ((enable-recursive-minibuffers t)
239 (minibuffer-local-completion-map
240 (copy-keymap minibuffer-local-completion-map)))
241 (define-key minibuffer-local-completion-map " " 'self-insert-command)
242 (define-key minibuffer-local-completion-map "?" 'self-insert-command)
243 (define-key minibuffer-local-completion-map (kbd "C-c !")
244 'org-time-stamp-inactive)
245 (apply #'completing-read args)))
247 (defun org--mks-read-key (allowed-keys prompt)
248 "Read a key and ensure it is a member of ALLOWED-KEYS.
249 TAB, SPC and RET are treated equivalently."
250 (let* ((key (char-to-string
251 (pcase (read-char-exclusive prompt)
252 ((or ?\s ?\t ?\r) ?\t)
253 (char char)))))
254 (if (member key allowed-keys)
256 (message "Invalid key: `%s'" key)
257 (sit-for 1)
258 (org--mks-read-key allowed-keys prompt))))
260 (defun org-mks (table title &optional prompt specials)
261 "Select a member of an alist with multiple keys.
263 TABLE is the alist which should contain entries where the car is a string.
264 There should be two types of entries.
266 1. prefix descriptions like (\"a\" \"Description\")
267 This indicates that `a' is a prefix key for multi-letter selection, and
268 that there are entries following with keys like \"ab\", \"ax\"...
270 2. Select-able members must have more than two elements, with the first
271 being the string of keys that lead to selecting it, and the second a
272 short description string of the item.
274 The command will then make a temporary buffer listing all entries
275 that can be selected with a single key, and all the single key
276 prefixes. When you press the key for a single-letter entry, it is selected.
277 When you press a prefix key, the commands (and maybe further prefixes)
278 under this key will be shown and offered for selection.
280 TITLE will be placed over the selection in the temporary buffer,
281 PROMPT will be used when prompting for a key. SPECIAL is an
282 alist with (\"key\" \"description\") entries. When one of these
283 is selected, only the bare key is returned."
284 (save-window-excursion
285 (let ((inhibit-quit t)
286 (buffer (org-switch-to-buffer-other-window "*Org Select*"))
287 (prompt (or prompt "Select: "))
288 current)
289 (unwind-protect
290 (catch 'exit
291 (while t
292 (erase-buffer)
293 (insert title "\n\n")
294 (let ((des-keys nil)
295 (allowed-keys '("\C-g"))
296 (tab-alternatives '("\s" "\t" "\r"))
297 (cursor-type nil))
298 ;; Populate allowed keys and descriptions keys
299 ;; available with CURRENT selector.
300 (let ((re (format "\\`%s\\(.\\)\\'"
301 (if current (regexp-quote current) "")))
302 (prefix (if current (concat current " ") "")))
303 (dolist (entry table)
304 (pcase entry
305 ;; Description.
306 (`(,(and key (pred (string-match re))) ,desc)
307 (let ((k (match-string 1 key)))
308 (push k des-keys)
309 ;; Keys ending in tab, space or RET are equivalent.
310 (if (member k tab-alternatives)
311 (push "\t" allowed-keys)
312 (push k allowed-keys))
313 (insert prefix "[" k "]" "..." " " desc "..." "\n")))
314 ;; Usable entry.
315 (`(,(and key (pred (string-match re))) ,desc . ,_)
316 (let ((k (match-string 1 key)))
317 (insert prefix "[" k "]" " " desc "\n")
318 (push k allowed-keys)))
319 (_ nil))))
320 ;; Insert special entries, if any.
321 (when specials
322 (insert "----------------------------------------------------\
323 ---------------------------\n")
324 (pcase-dolist (`(,key ,description) specials)
325 (insert (format "[%s] %s\n" key description))
326 (push key allowed-keys)))
327 ;; Display UI and let user select an entry or
328 ;; a sub-level prefix.
329 (goto-char (point-min))
330 (unless (pos-visible-in-window-p (point-max))
331 (org-fit-window-to-buffer))
332 (let ((pressed (org--mks-read-key allowed-keys prompt)))
333 (setq current (concat current pressed))
334 (cond
335 ((equal pressed "\C-g") (user-error "Abort"))
336 ;; Selection is a prefix: open a new menu.
337 ((member pressed des-keys))
338 ;; Selection matches an association: return it.
339 ((let ((entry (assoc current table)))
340 (and entry (throw 'exit entry))))
341 ;; Selection matches a special entry: return the
342 ;; selection prefix.
343 ((assoc current specials) (throw 'exit current))
344 (t (error "No entry available")))))))
345 (when buffer (kill-buffer buffer))))))
348 ;;; Logic
350 (defsubst org-xor (a b)
351 "Exclusive `or'."
352 (if a (not b) b))
356 ;;; Overlays
358 (defun org-overlay-display (ovl text &optional face evap)
359 "Make overlay OVL display TEXT with face FACE."
360 (overlay-put ovl 'display text)
361 (if face (overlay-put ovl 'face face))
362 (if evap (overlay-put ovl 'evaporate t)))
364 (defun org-overlay-before-string (ovl text &optional face evap)
365 "Make overlay OVL display TEXT with face FACE."
366 (if face (org-add-props text nil 'face face))
367 (overlay-put ovl 'before-string text)
368 (if evap (overlay-put ovl 'evaporate t)))
370 (defun org-find-overlays (prop &optional pos delete)
371 "Find all overlays specifying PROP at POS or point.
372 If DELETE is non-nil, delete all those overlays."
373 (let (found)
374 (dolist (ov (overlays-at (or pos (point))) found)
375 (cond ((not (overlay-get ov prop)))
376 (delete (delete-overlay ov))
377 (t (push ov found))))))
379 (defun org-flag-region (from to flag spec)
380 "Hide or show lines from FROM to TO, according to FLAG.
381 SPEC is the invisibility spec, as a symbol."
382 (remove-overlays from to 'invisible spec)
383 ;; Use `front-advance' since text right before to the beginning of
384 ;; the overlay belongs to the visible line than to the contents.
385 (when flag
386 (let ((o (make-overlay from to nil 'front-advance)))
387 (overlay-put o 'evaporate t)
388 (overlay-put o 'invisible spec)
389 (overlay-put o 'isearch-open-invisible #'delete-overlay))))
393 ;;; Indentation
395 (defun org-get-indentation (&optional line)
396 "Get the indentation of the current line, interpreting tabs.
397 When LINE is given, assume it represents a line and compute its indentation."
398 (if line
399 (when (string-match "^ *" (org-remove-tabs line))
400 (match-end 0))
401 (save-excursion
402 (beginning-of-line 1)
403 (skip-chars-forward " \t")
404 (current-column))))
406 (defun org-do-remove-indentation (&optional n)
407 "Remove the maximum common indentation from the buffer.
408 When optional argument N is a positive integer, remove exactly
409 that much characters from indentation, if possible. Return nil
410 if it fails."
411 (catch :exit
412 (goto-char (point-min))
413 ;; Find maximum common indentation, if not specified.
414 (let ((n (or n
415 (let ((min-ind (point-max)))
416 (save-excursion
417 (while (re-search-forward "^[ \t]*\\S-" nil t)
418 (let ((ind (1- (current-column))))
419 (if (zerop ind) (throw :exit nil)
420 (setq min-ind (min min-ind ind))))))
421 min-ind))))
422 (if (zerop n) (throw :exit nil)
423 ;; Remove exactly N indentation, but give up if not possible.
424 (while (not (eobp))
425 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
426 (cond ((eolp) (delete-region (line-beginning-position) (point)))
427 ((< ind n) (throw :exit nil))
428 (t (indent-line-to (- ind n))))
429 (forward-line)))
430 ;; Signal success.
431 t))))
435 ;;; String manipulation
437 (defun org-string< (a b)
438 (org-string-collate-lessp a b))
440 (defun org-string<= (a b)
441 (or (string= a b) (org-string-collate-lessp a b)))
443 (defun org-string>= (a b)
444 (not (org-string-collate-lessp a b)))
446 (defun org-string> (a b)
447 (and (not (string= a b))
448 (not (org-string-collate-lessp a b))))
450 (defun org-string<> (a b)
451 (not (string= a b)))
453 (defsubst org-trim (s &optional keep-lead)
454 "Remove whitespace at the beginning and the end of string S.
455 When optional argument KEEP-LEAD is non-nil, removing blank lines
456 at the beginning of the string does not affect leading indentation."
457 (replace-regexp-in-string
458 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
459 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
461 (defun org-string-nw-p (s)
462 "Return S if S is a string containing a non-blank character.
463 Otherwise, return nil."
464 (and (stringp s)
465 (string-match-p "[^ \r\t\n]" s)
468 (defun org-reverse-string (string)
469 "Return the reverse of STRING."
470 (apply #'string (nreverse (string-to-list string))))
472 (defun org-split-string (string &optional separators)
473 "Splits STRING into substrings at SEPARATORS.
475 SEPARATORS is a regular expression. When nil, it defaults to
476 \"[ \f\t\n\r\v]+\".
478 Unlike `split-string', matching SEPARATORS at the beginning and
479 end of string are ignored."
480 (let ((separators (or separators "[ \f\t\n\r\v]+")))
481 (when (string-match (concat "\\`" separators) string)
482 (setq string (replace-match "" nil nil string)))
483 (when (string-match (concat separators "\\'") string)
484 (setq string (replace-match "" nil nil string)))
485 (split-string string separators)))
487 (defun org-string-display (string)
488 "Return STRING as it is displayed in the current buffer.
489 This function takes into consideration `invisible' and `display'
490 text properties."
491 (let* ((build-from-parts
492 (lambda (s property filter)
493 ;; Build a new string out of string S. On every group of
494 ;; contiguous characters with the same PROPERTY value,
495 ;; call FILTER on the properties list at the beginning of
496 ;; the group. If it returns a string, replace the
497 ;; characters in the group with it. Otherwise, preserve
498 ;; those characters.
499 (let ((len (length s))
500 (new "")
501 (i 0)
502 (cursor 0))
503 (while (setq i (text-property-not-all i len property nil s))
504 (let ((end (next-single-property-change i property s len))
505 (value (funcall filter (text-properties-at i s))))
506 (when value
507 (setq new (concat new (substring s cursor i) value))
508 (setq cursor end))
509 (setq i end)))
510 (concat new (substring s cursor)))))
511 (prune-invisible
512 (lambda (s)
513 (funcall build-from-parts s 'invisible
514 (lambda (props)
515 ;; If `invisible' property in PROPS means text
516 ;; is to be invisible, return the empty string.
517 ;; Otherwise return nil so that the part is
518 ;; skipped.
519 (and (or (eq t buffer-invisibility-spec)
520 (assoc-string (plist-get props 'invisible)
521 buffer-invisibility-spec))
522 "")))))
523 (replace-display
524 (lambda (s)
525 (funcall build-from-parts s 'display
526 (lambda (props)
527 ;; If there is any string specification in
528 ;; `display' property return it. Also attach
529 ;; other text properties on the part to that
530 ;; string (face...).
531 (let* ((display (plist-get props 'display))
532 (value (if (stringp display) display
533 (cl-some #'stringp display))))
534 (when value
535 (apply #'propertize
536 ;; Displayed string could contain
537 ;; invisible parts, but no nested
538 ;; display.
539 (funcall prune-invisible value)
540 'display
541 (and (not (stringp display))
542 (cl-remove-if #'stringp display))
543 props))))))))
544 ;; `display' property overrides `invisible' one. So we first
545 ;; replace characters with `display' property. Then we remove
546 ;; invisible characters.
547 (funcall prune-invisible (funcall replace-display string))))
549 (defun org-string-width (string)
550 "Return width of STRING when displayed in the current buffer.
551 Unlike `string-width', this function takes into consideration
552 `invisible' and `display' text properties."
553 (string-width (org-string-display string)))
555 (defun org-not-nil (v)
556 "If V not nil, and also not the string \"nil\", then return V.
557 Otherwise return nil."
558 (and v (not (equal v "nil")) v))
560 (defun org-unbracket-string (pre post string)
561 "Remove PRE/POST from the beginning/end of STRING.
562 Both PRE and POST must be pre-/suffixes of STRING, or neither is
563 removed."
564 (if (and (string-prefix-p pre string)
565 (string-suffix-p post string))
566 (substring string (length pre) (- (length post)))
567 string))
569 (defsubst org-current-line-string (&optional to-here)
570 (buffer-substring (point-at-bol) (if to-here (point) (point-at-eol))))
572 (defun org-shorten-string (s maxlength)
573 "Shorten string S so that it is no longer than MAXLENGTH characters.
574 If the string is shorter or has length MAXLENGTH, just return the
575 original string. If it is longer, the functions finds a space in the
576 string, breaks this string off at that locations and adds three dots
577 as ellipsis. Including the ellipsis, the string will not be longer
578 than MAXLENGTH. If finding a good breaking point in the string does
579 not work, the string is just chopped off in the middle of a word
580 if necessary."
581 (if (<= (length s) maxlength)
583 (let* ((n (max (- maxlength 4) 1))
584 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
585 (if (string-match re s)
586 (concat (match-string 1 s) "...")
587 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
589 (defun org-remove-tabs (s &optional width)
590 "Replace tabulators in S with spaces.
591 Assumes that s is a single line, starting in column 0."
592 (setq width (or width tab-width))
593 (while (string-match "\t" s)
594 (setq s (replace-match
595 (make-string
596 (- (* width (/ (+ (match-beginning 0) width) width))
597 (match-beginning 0)) ?\ )
598 t t s)))
601 (defun org-wrap (string &optional width lines)
602 "Wrap string to either a number of lines, or a width in characters.
603 If WIDTH is non-nil, the string is wrapped to that width, however many lines
604 that costs. If there is a word longer than WIDTH, the text is actually
605 wrapped to the length of that word.
606 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
607 many lines, whatever width that takes.
608 The return value is a list of lines, without newlines at the end."
609 (let* ((words (split-string string))
610 (maxword (apply 'max (mapcar 'org-string-width words)))
611 w ll)
612 (cond (width
613 (org--do-wrap words (max maxword width)))
614 (lines
615 (setq w maxword)
616 (setq ll (org--do-wrap words maxword))
617 (if (<= (length ll) lines)
619 (setq ll words)
620 (while (> (length ll) lines)
621 (setq w (1+ w))
622 (setq ll (org--do-wrap words w)))
623 ll))
624 (t (error "Cannot wrap this")))))
626 (defun org--do-wrap (words width)
627 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
628 (let (lines line)
629 (while words
630 (setq line (pop words))
631 (while (and words (< (+ (length line) (length (car words))) width))
632 (setq line (concat line " " (pop words))))
633 (setq lines (push line lines)))
634 (nreverse lines)))
636 (defun org-remove-indentation (code &optional n)
637 "Remove maximum common indentation in string CODE and return it.
638 N may optionally be the number of columns to remove. Return CODE
639 as-is if removal failed."
640 (with-temp-buffer
641 (insert code)
642 (if (org-do-remove-indentation n) (buffer-string) code)))
646 ;;; List manipulation
648 (defsubst org-get-alist-option (option key)
649 (cond ((eq key t) t)
650 ((eq option t) t)
651 ((assoc key option) (cdr (assoc key option)))
652 (t (let ((r (cdr (assq 'default option))))
653 (if (listp r) (delq nil r) r)))))
655 (defsubst org-last (list)
656 "Return the last element of LIST."
657 (car (last list)))
659 (defsubst org-uniquify (list)
660 "Non-destructively remove duplicate elements from LIST."
661 (let ((res (copy-sequence list))) (delete-dups res)))
663 (defun org-uniquify-alist (alist)
664 "Merge elements of ALIST with the same key.
666 For example, in this alist:
668 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
669 => \\='((a 1 3) (b 2))
671 merge (a 1) and (a 3) into (a 1 3).
673 The function returns the new ALIST."
674 (let (rtn)
675 (dolist (e alist rtn)
676 (let (n)
677 (if (not (assoc (car e) rtn))
678 (push e rtn)
679 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
680 (setq rtn (assq-delete-all (car e) rtn))
681 (push n rtn))))))
683 (defun org-delete-all (elts list)
684 "Remove all elements in ELTS from LIST.
685 Comparison is done with `equal'. It is a destructive operation
686 that may remove elements by altering the list structure."
687 (while elts
688 (setq list (delete (pop elts) list)))
689 list)
691 (defun org-plist-delete (plist property)
692 "Delete PROPERTY from PLIST.
693 This is in contrast to merely setting it to 0."
694 (let (p)
695 (while plist
696 (if (not (eq property (car plist)))
697 (setq p (plist-put p (car plist) (nth 1 plist))))
698 (setq plist (cddr plist)))
701 (defun org-combine-plists (&rest plists)
702 "Create a single property list from all plists in PLISTS.
703 The process starts by copying the first list, and then setting properties
704 from the other lists. Settings in the last list are the most significant
705 ones and overrule settings in the other lists."
706 (let ((rtn (copy-sequence (pop plists)))
707 p v ls)
708 (while plists
709 (setq ls (pop plists))
710 (while ls
711 (setq p (pop ls) v (pop ls))
712 (setq rtn (plist-put rtn p v))))
713 rtn))
717 ;;; Regexp matching
719 (defsubst org-pos-in-match-range (pos n)
720 (and (match-beginning n)
721 (<= (match-beginning n) pos)
722 (>= (match-end n) pos)))
724 (defun org-skip-whitespace ()
725 "Skip over space, tabs and newline characters."
726 (skip-chars-forward " \t\n\r"))
728 (defun org-match-line (regexp)
729 "Match REGEXP at the beginning of the current line."
730 (save-excursion
731 (beginning-of-line)
732 (looking-at regexp)))
734 (defun org-match-any-p (re list)
735 "Non-nil if regexp RE matches an element in LIST."
736 (cl-some (lambda (x) (string-match-p re x)) list))
738 (defun org-in-regexp (regexp &optional nlines visually)
739 "Check if point is inside a match of REGEXP.
741 Normally only the current line is checked, but you can include
742 NLINES extra lines around point into the search. If VISUALLY is
743 set, require that the cursor is not after the match but really
744 on, so that the block visually is on the match.
746 Return nil or a cons cell (BEG . END) where BEG and END are,
747 respectively, the positions at the beginning and the end of the
748 match."
749 (catch :exit
750 (let ((pos (point))
751 (eol (line-end-position (if nlines (1+ nlines) 1))))
752 (save-excursion
753 (beginning-of-line (- 1 (or nlines 0)))
754 (while (and (re-search-forward regexp eol t)
755 (<= (match-beginning 0) pos))
756 (let ((end (match-end 0)))
757 (when (or (> end pos) (and (= end pos) (not visually)))
758 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
760 (defun org-point-in-group (point group &optional context)
761 "Check if POINT is in match-group GROUP.
762 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
763 match. If the match group does not exist or point is not inside it,
764 return nil."
765 (and (match-beginning group)
766 (>= point (match-beginning group))
767 (<= point (match-end group))
768 (if context
769 (list context (match-beginning group) (match-end group))
770 t)))
774 ;;; Motion
776 (defsubst org-goto-line (N)
777 (save-restriction
778 (widen)
779 (goto-char (point-min))
780 (forward-line (1- N))))
782 (defsubst org-current-line (&optional pos)
783 (save-excursion
784 (and pos (goto-char pos))
785 ;; works also in narrowed buffer, because we start at 1, not point-min
786 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
790 ;;; Text properties
792 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
793 rear-nonsticky t mouse-map t fontified t
794 org-emphasis t)
795 "Properties to remove when a string without properties is wanted.")
797 (defsubst org-no-properties (s &optional restricted)
798 "Remove all text properties from string S.
799 When RESTRICTED is non-nil, only remove the properties listed
800 in `org-rm-props'."
801 (if restricted (remove-text-properties 0 (length s) org-rm-props s)
802 (set-text-properties 0 (length s) nil s))
804 (defun org-add-props (string plist &rest props)
805 "Add text properties to entire string, from beginning to end.
806 PLIST may be a list of properties, PROPS are individual properties and values
807 that will be added to PLIST. Returns the string that was modified."
808 (declare (indent 2))
809 (add-text-properties
810 0 (length string) (if props (append plist props) plist) string)
811 string)
813 (defun org-make-parameter-alist (flat)
814 "Return alist based on FLAT.
815 FLAT is a list with alternating symbol names and values. The
816 returned alist is a list of lists with the symbol name in car and
817 the value in cdr."
818 (when flat
819 (cons (list (car flat) (cadr flat))
820 (org-make-parameter-alist (cddr flat)))))
822 (defsubst org-get-at-bol (property)
823 "Get text property PROPERTY at the beginning of line."
824 (get-text-property (point-at-bol) property))
826 (defun org-get-at-eol (property n)
827 "Get text property PROPERTY at the end of line less N characters."
828 (get-text-property (- (point-at-eol) n) property))
830 (defun org-find-text-property-in-string (prop s)
831 "Return the first non-nil value of property PROP in string S."
832 (or (get-text-property 0 prop s)
833 (get-text-property (or (next-single-property-change 0 prop s) 0)
834 prop s)))
836 (defun org-invisible-p (&optional pos)
837 "Non-nil if the character after POS is invisible.
838 If POS is nil, use `point' instead."
839 (get-char-property (or pos (point)) 'invisible))
841 (defun org-truely-invisible-p ()
842 "Check if point is at a character currently not visible.
843 This version does not only check the character property, but also
844 `visible-mode'."
845 (unless (bound-and-true-p visible-mode)
846 (org-invisible-p)))
848 (defun org-invisible-p2 ()
849 "Check if point is at a character currently not visible.
850 If the point is at EOL (and not at the beginning of a buffer too),
851 move it back by one char before doing this check."
852 (save-excursion
853 (when (and (eolp) (not (bobp)))
854 (backward-char 1))
855 (org-invisible-p)))
859 ;;; Local variables
861 (defconst org-unique-local-variables
862 '(org-element--cache
863 org-element--cache-objects
864 org-element--cache-sync-keys
865 org-element--cache-sync-requests
866 org-element--cache-sync-timer)
867 "List of local variables that cannot be transferred to another buffer.")
869 (defun org-get-local-variables ()
870 "Return a list of all local variables in an Org mode buffer."
871 (delq nil
872 (mapcar
873 (lambda (x)
874 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
875 (name (car binding)))
876 (and (not (get name 'org-state))
877 (not (memq name org-unique-local-variables))
878 (string-match-p
879 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
880 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
881 (symbol-name name))
882 binding)))
883 (with-temp-buffer
884 (org-mode)
885 (buffer-local-variables)))))
887 (defun org-clone-local-variables (from-buffer &optional regexp)
888 "Clone local variables from FROM-BUFFER.
889 Optional argument REGEXP selects variables to clone."
890 (dolist (pair (buffer-local-variables from-buffer))
891 (pcase pair
892 (`(,name . ,value) ;ignore unbound variables
893 (when (and (not (memq name org-unique-local-variables))
894 (or (null regexp) (string-match-p regexp (symbol-name name))))
895 (ignore-errors (set (make-local-variable name) value)))))))
899 ;;; Miscellaneous
901 (defsubst org-call-with-arg (command arg)
902 "Call COMMAND interactively, but pretend prefix arg was ARG."
903 (let ((current-prefix-arg arg)) (call-interactively command)))
905 (defsubst org-check-external-command (cmd &optional use no-error)
906 "Check if external program CMD for USE exists, error if not.
907 When the program does exist, return its path.
908 When it does not exist and NO-ERROR is set, return nil.
909 Otherwise, throw an error. The optional argument USE can describe what this
910 program is needed for, so that the error message can be more informative."
911 (or (executable-find cmd)
912 (if no-error
914 (error "Can't find `%s'%s" cmd
915 (if use (format " (%s)" use) "")))))
917 (defun org-display-warning (message)
918 "Display the given MESSAGE as a warning."
919 (display-warning 'org message :warning))
921 (defun org-unlogged-message (&rest args)
922 "Display a message, but avoid logging it in the *Messages* buffer."
923 (let ((message-log-max nil))
924 (apply #'message args)))
926 (defun org-let (list &rest body)
927 (eval (cons 'let (cons list body))))
928 (put 'org-let 'lisp-indent-function 1)
930 (defun org-let2 (list1 list2 &rest body)
931 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
932 (put 'org-let2 'lisp-indent-function 2)
934 (defun org-eval (form)
935 "Eval FORM and return result."
936 (condition-case error
937 (eval form)
938 (error (format "%%![Error: %s]" error))))
940 (defvar org-outline-regexp) ; defined in org.el
941 (defvar org-odd-levels-only) ; defined in org.el
942 (defvar org-inlinetask-min-level) ; defined in org-inlinetask.el
943 (defun org-get-limited-outline-regexp ()
944 "Return outline-regexp with limited number of levels.
945 The number of levels is controlled by `org-inlinetask-min-level'"
946 (cond ((not (derived-mode-p 'org-mode))
947 outline-regexp)
948 ((not (featurep 'org-inlinetask))
949 org-outline-regexp)
951 (let* ((limit-level (1- org-inlinetask-min-level))
952 (nstars (if org-odd-levels-only
953 (1- (* limit-level 2))
954 limit-level)))
955 (format "\\*\\{1,%d\\} " nstars)))))
958 (provide 'org-macs)
960 ;;; org-macs.el ends here