Move `org-completing-read' into "org-macs.el"
[org-mode.git] / lisp / org-macs.el
blob196a2ce22ce9c31d6006fc6b56d279f3837a2a27
1 ;;; org-macs.el --- Top-level Definitions for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://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.
123 This means that the buffer may change while running BODY,
124 but it also means that the buffer should stay alive
125 during the operation, because otherwise all these markers will
126 point nowhere."
127 (declare (debug (form body)) (indent 1))
128 (org-with-gensyms (data)
129 `(let ((,data (org-outline-overlay-data ,use-markers)))
130 (unwind-protect
131 (prog1 (progn ,@body)
132 (org-set-outline-overlay-data ,data))
133 (when ,use-markers
134 (dolist (c ,data)
135 (when (markerp (car c)) (move-marker (car c) nil))
136 (when (markerp (cdr c)) (move-marker (cdr c) nil))))))))
138 (defmacro org-with-wide-buffer (&rest body)
139 "Execute body while temporarily widening the buffer."
140 (declare (debug (body)))
141 `(save-excursion
142 (save-restriction
143 (widen)
144 ,@body)))
146 (defmacro org-with-limited-levels (&rest body)
147 "Execute BODY with limited number of outline levels."
148 (declare (debug (body)))
149 `(progn
150 (defvar org-called-with-limited-levels)
151 (defvar org-outline-regexp)
152 (defvar outline-regexp)
153 (defvar org-outline-regexp-bol)
154 (let* ((org-called-with-limited-levels t)
155 (org-outline-regexp (org-get-limited-outline-regexp))
156 (outline-regexp org-outline-regexp)
157 (org-outline-regexp-bol (concat "^" org-outline-regexp)))
158 ,@body)))
160 (defmacro org-eval-in-environment (environment form)
161 (declare (debug (form form)) (indent 1))
162 `(eval (list 'let ,environment ',form)))
164 ;;;###autoload
165 (defmacro org-load-noerror-mustsuffix (file)
166 "Load FILE with optional arguments NOERROR and MUSTSUFFIX."
167 `(load ,file 'noerror nil nil 'mustsuffix))
171 ;;; Input
173 (defun org-read-function (prompt &optional allow-empty?)
174 "Prompt for a function.
175 If ALLOW-EMPTY? is non-nil, return nil rather than raising an
176 error when the user input is empty."
177 (let ((func (completing-read prompt obarray #'fboundp t)))
178 (cond ((not (string= func ""))
179 (intern func))
180 (allow-empty? nil)
181 (t (user-error "Empty input is not valid")))))
183 (defun org-completing-read (&rest args)
184 "Completing-read with SPACE being a normal character."
185 (let ((enable-recursive-minibuffers t)
186 (minibuffer-local-completion-map
187 (copy-keymap minibuffer-local-completion-map)))
188 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
189 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
190 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
191 'org-time-stamp-inactive)
192 (apply #'completing-read args)))
196 ;;; Logic
198 (defsubst org-xor (a b)
199 "Exclusive `or'."
200 (if a (not b) b))
204 ;;; String manipulation
206 (defsubst org-trim (s &optional keep-lead)
207 "Remove whitespace at the beginning and the end of string S.
208 When optional argument KEEP-LEAD is non-nil, removing blank lines
209 at the beginning of the string does not affect leading indentation."
210 (replace-regexp-in-string
211 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
212 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
214 (defun org-string-nw-p (s)
215 "Return S if S is a string containing a non-blank character.
216 Otherwise, return nil."
217 (and (stringp s)
218 (string-match-p "[^ \r\t\n]" s)
221 (defun org-split-string (string &optional separators)
222 "Splits STRING into substrings at SEPARATORS.
224 SEPARATORS is a regular expression. When nil, it defaults to
225 \"[ \f\t\n\r\v]+\".
227 Unlike to `split-string', matching SEPARATORS at the beginning
228 and end of string are ignored."
229 (let ((separators (or separators "[ \f\t\n\r\v]+")))
230 (when (string-match (concat "\\`" separators) string)
231 (setq string (replace-match "" nil nil string)))
232 (when (string-match (concat separators "\\'") string)
233 (setq string (replace-match "" nil nil string)))
234 (split-string string separators)))
236 (defun org-string-display (string)
237 "Return STRING as it is displayed in the current buffer.
238 This function takes into consideration `invisible' and `display'
239 text properties."
240 (let* ((build-from-parts
241 (lambda (s property filter)
242 ;; Build a new string out of string S. On every group of
243 ;; contiguous characters with the same PROPERTY value,
244 ;; call FILTER on the properties list at the beginning of
245 ;; the group. If it returns a string, replace the
246 ;; characters in the group with it. Otherwise, preserve
247 ;; those characters.
248 (let ((len (length s))
249 (new "")
250 (i 0)
251 (cursor 0))
252 (while (setq i (text-property-not-all i len property nil s))
253 (let ((end (next-single-property-change i property s len))
254 (value (funcall filter (text-properties-at i s))))
255 (when value
256 (setq new (concat new (substring s cursor i) value))
257 (setq cursor end))
258 (setq i end)))
259 (concat new (substring s cursor)))))
260 (prune-invisible
261 (lambda (s)
262 (funcall build-from-parts s 'invisible
263 (lambda (props)
264 ;; If `invisible' property in PROPS means text
265 ;; is to be invisible, return the empty string.
266 ;; Otherwise return nil so that the part is
267 ;; skipped.
268 (and (or (eq t buffer-invisibility-spec)
269 (assoc-string (plist-get props 'invisible)
270 buffer-invisibility-spec))
271 "")))))
272 (replace-display
273 (lambda (s)
274 (funcall build-from-parts s 'display
275 (lambda (props)
276 ;; If there is any string specification in
277 ;; `display' property return it. Also attach
278 ;; other text properties on the part to that
279 ;; string (face...).
280 (let* ((display (plist-get props 'display))
281 (value (if (stringp display) display
282 (cl-some #'stringp display))))
283 (when value
284 (apply
285 #'propertize
286 ;; Displayed string could contain
287 ;; invisible parts, but no nested display.
288 (funcall prune-invisible value)
289 (plist-put props
290 'display
291 (and (not (stringp display))
292 (cl-remove-if #'stringp
293 display)))))))))))
294 ;; `display' property overrides `invisible' one. So we first
295 ;; replace characters with `display' property. Then we remove
296 ;; invisible characters.
297 (funcall prune-invisible (funcall replace-display string))))
299 (defun org-string-width (string)
300 "Return width of STRING when displayed in the current buffer.
301 Unlike to `string-width', this function takes into consideration
302 `invisible' and `display' text properties."
303 (string-width (org-string-display string)))
305 (defun org-not-nil (v)
306 "If V not nil, and also not the string \"nil\", then return V.
307 Otherwise return nil."
308 (and v (not (equal v "nil")) v))
310 (defun org-unbracket-string (pre post string)
311 "Remove PRE/POST from the beginning/end of STRING.
312 Both PRE and POST must be pre-/suffixes of STRING, or neither is
313 removed."
314 (if (and (string-prefix-p pre string)
315 (string-suffix-p post string))
316 (substring string (length pre) (- (length post)))
317 string))
319 (defsubst org-current-line-string (&optional to-here)
320 (buffer-substring (point-at-bol) (if to-here (point) (point-at-eol))))
324 ;;; List manipulation
326 (defsubst org-get-alist-option (option key)
327 (cond ((eq key t) t)
328 ((eq option t) t)
329 ((assoc key option) (cdr (assoc key option)))
330 (t (let ((r (cdr (assq 'default option))))
331 (if (listp r) (delq nil r) r)))))
333 (defsubst org-last (list)
334 "Return the last element of LIST."
335 (car (last list)))
337 (defun org-plist-delete (plist property)
338 "Delete PROPERTY from PLIST.
339 This is in contrast to merely setting it to 0."
340 (let (p)
341 (while plist
342 (if (not (eq property (car plist)))
343 (setq p (plist-put p (car plist) (nth 1 plist))))
344 (setq plist (cddr plist)))
347 (defsubst org-uniquify (list)
348 "Non-destructively remove duplicate elements from LIST."
349 (let ((res (copy-sequence list))) (delete-dups res)))
353 ;;; Regexp matching
355 (defsubst org-pos-in-match-range (pos n)
356 (and (match-beginning n)
357 (<= (match-beginning n) pos)
358 (>= (match-end n) pos)))
360 (defun org-match-line (regexp)
361 "Match REGEXP at the beginning of the current line."
362 (save-excursion
363 (beginning-of-line)
364 (looking-at regexp)))
368 ;;; Motion
370 (defsubst org-goto-line (N)
371 (save-restriction
372 (widen)
373 (goto-char (point-min))
374 (forward-line (1- N))))
376 (defsubst org-current-line (&optional pos)
377 (save-excursion
378 (and pos (goto-char pos))
379 ;; works also in narrowed buffer, because we start at 1, not point-min
380 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
384 ;;; Text properties
386 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
387 rear-nonsticky t mouse-map t fontified t
388 org-emphasis t)
389 "Properties to remove when a string without properties is wanted.")
391 (defsubst org-no-properties (s &optional restricted)
392 "Remove all text properties from string S.
393 When RESTRICTED is non-nil, only remove the properties listed
394 in `org-rm-props'."
395 (if restricted (remove-text-properties 0 (length s) org-rm-props s)
396 (set-text-properties 0 (length s) nil s))
399 (defun org-make-parameter-alist (flat)
400 "Return alist based on FLAT.
401 FLAT is a list with alternating symbol names and values. The
402 returned alist is a list of lists with the symbol name in car and
403 the value in cdr."
404 (when flat
405 (cons (list (car flat) (cadr flat))
406 (org-make-parameter-alist (cddr flat)))))
408 (defsubst org-get-at-bol (property)
409 "Get text property PROPERTY at the beginning of line."
410 (get-text-property (point-at-bol) property))
414 ;;; Local variables
416 (defconst org-unique-local-variables
417 '(org-element--cache
418 org-element--cache-objects
419 org-element--cache-sync-keys
420 org-element--cache-sync-requests
421 org-element--cache-sync-timer)
422 "List of local variables that cannot be transferred to another buffer.")
424 (defun org-get-local-variables ()
425 "Return a list of all local variables in an Org mode buffer."
426 (delq nil
427 (mapcar
428 (lambda (x)
429 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
430 (name (car binding)))
431 (and (not (get name 'org-state))
432 (not (memq name org-unique-local-variables))
433 (string-match-p
434 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
435 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
436 (symbol-name name))
437 binding)))
438 (with-temp-buffer
439 (org-mode)
440 (buffer-local-variables)))))
442 (defun org-clone-local-variables (from-buffer &optional regexp)
443 "Clone local variables from FROM-BUFFER.
444 Optional argument REGEXP selects variables to clone."
445 (dolist (pair (buffer-local-variables from-buffer))
446 (pcase pair
447 (`(,name . ,value) ;ignore unbound variables
448 (when (and (not (memq name org-unique-local-variables))
449 (or (null regexp) (string-match-p regexp (symbol-name name))))
450 (ignore-errors (set (make-local-variable name) value)))))))
454 ;;; Miscellaneous
456 (defsubst org-check-external-command (cmd &optional use no-error)
457 "Check if external program CMD for USE exists, error if not.
458 When the program does exist, return its path.
459 When it does not exist and NO-ERROR is set, return nil.
460 Otherwise, throw an error. The optional argument USE can describe what this
461 program is needed for, so that the error message can be more informative."
462 (or (executable-find cmd)
463 (if no-error
465 (error "Can't find `%s'%s" cmd
466 (if use (format " (%s)" use) "")))))
468 (defun org-let (list &rest body)
469 (eval (cons 'let (cons list body))))
470 (put 'org-let 'lisp-indent-function 1)
472 (defun org-let2 (list1 list2 &rest body)
473 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
474 (put 'org-let2 'lisp-indent-function 2)
476 (defsubst org-call-with-arg (command arg)
477 "Call COMMAND interactively, but pretend prefix arg was ARG."
478 (let ((current-prefix-arg arg)) (call-interactively command)))
480 (defvar org-outline-regexp) ; defined in org.el
481 (defvar org-odd-levels-only) ; defined in org.el
482 (defvar org-inlinetask-min-level) ; defined in org-inlinetask.el
483 (defun org-get-limited-outline-regexp ()
484 "Return outline-regexp with limited number of levels.
485 The number of levels is controlled by `org-inlinetask-min-level'"
486 (cond ((not (derived-mode-p 'org-mode))
487 outline-regexp)
488 ((not (featurep 'org-inlinetask))
489 org-outline-regexp)
491 (let* ((limit-level (1- org-inlinetask-min-level))
492 (nstars (if org-odd-levels-only
493 (1- (* limit-level 2))
494 limit-level)))
495 (format "\\*\\{1,%d\\} " nstars)))))
498 (provide 'org-macs)
500 ;;; org-macs.el ends here