Move `org-key' and `org-defkey' into "org-macs.el"
[org-mode.git] / lisp / org-macs.el
blobf55c07f5bbb6c79348c303d5844755d7fda4b3aa
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:
34 (defvar org-disputed-keys)
35 (defvar org-replace-disputed-keys)
38 ;;; Macros
40 (defmacro org-with-gensyms (symbols &rest body)
41 (declare (debug (sexp body)) (indent 1))
42 `(let ,(mapcar (lambda (s)
43 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
44 symbols)
45 ,@body))
47 (defmacro org-preserve-lc (&rest body)
48 (declare (debug (body)))
49 (org-with-gensyms (line col)
50 `(let ((,line (org-current-line))
51 (,col (current-column)))
52 (unwind-protect
53 (progn ,@body)
54 (org-goto-line ,line)
55 (org-move-to-column ,col)))))
57 ;; Use `org-with-silent-modifications' to ignore cosmetic changes and
58 ;; `org-unmodified' to ignore real text modifications
59 (defmacro org-unmodified (&rest body)
60 "Run BODY while preserving the buffer's `buffer-modified-p' state."
61 (declare (debug (body)))
62 (org-with-gensyms (was-modified)
63 `(let ((,was-modified (buffer-modified-p)))
64 (unwind-protect
65 (let ((buffer-undo-list t)
66 (inhibit-modification-hooks t))
67 ,@body)
68 (set-buffer-modified-p ,was-modified)))))
70 (defmacro org-without-partial-completion (&rest body)
71 (declare (debug (body)))
72 `(if (and (boundp 'partial-completion-mode)
73 partial-completion-mode
74 (fboundp 'partial-completion-mode))
75 (unwind-protect
76 (progn
77 (partial-completion-mode -1)
78 ,@body)
79 (partial-completion-mode 1))
80 ,@body))
82 (defmacro org-with-point-at (pom &rest body)
83 "Move to buffer and point of point-or-marker POM for the duration of BODY."
84 (declare (debug (form body)) (indent 1))
85 (org-with-gensyms (mpom)
86 `(let ((,mpom ,pom))
87 (save-excursion
88 (if (markerp ,mpom) (set-buffer (marker-buffer ,mpom)))
89 (org-with-wide-buffer
90 (goto-char (or ,mpom (point)))
91 ,@body)))))
93 (defmacro org-with-remote-undo (buffer &rest body)
94 "Execute BODY while recording undo information in two buffers."
95 (declare (debug (form body)) (indent 1))
96 (org-with-gensyms (cline cmd buf1 buf2 undo1 undo2 c1 c2)
97 `(let ((,cline (org-current-line))
98 (,cmd this-command)
99 (,buf1 (current-buffer))
100 (,buf2 ,buffer)
101 (,undo1 buffer-undo-list)
102 (,undo2 (with-current-buffer ,buffer buffer-undo-list))
103 ,c1 ,c2)
104 ,@body
105 (when org-agenda-allow-remote-undo
106 (setq ,c1 (org-verify-change-for-undo
107 ,undo1 (with-current-buffer ,buf1 buffer-undo-list))
108 ,c2 (org-verify-change-for-undo
109 ,undo2 (with-current-buffer ,buf2 buffer-undo-list)))
110 (when (or ,c1 ,c2)
111 ;; make sure there are undo boundaries
112 (and ,c1 (with-current-buffer ,buf1 (undo-boundary)))
113 (and ,c2 (with-current-buffer ,buf2 (undo-boundary)))
114 ;; remember which buffer to undo
115 (push (list ,cmd ,cline ,buf1 ,c1 ,buf2 ,c2)
116 org-agenda-undo-list))))))
118 (defmacro org-no-read-only (&rest body)
119 "Inhibit read-only for BODY."
120 (declare (debug (body)))
121 `(let ((inhibit-read-only t)) ,@body))
123 (defmacro org-save-outline-visibility (use-markers &rest body)
124 "Save and restore outline visibility around BODY.
125 If USE-MARKERS is non-nil, use markers for the positions.
126 This means that the buffer may change while running BODY,
127 but it also means that the buffer should stay alive
128 during the operation, because otherwise all these markers will
129 point nowhere."
130 (declare (debug (form body)) (indent 1))
131 (org-with-gensyms (data)
132 `(let ((,data (org-outline-overlay-data ,use-markers)))
133 (unwind-protect
134 (prog1 (progn ,@body)
135 (org-set-outline-overlay-data ,data))
136 (when ,use-markers
137 (dolist (c ,data)
138 (when (markerp (car c)) (move-marker (car c) nil))
139 (when (markerp (cdr c)) (move-marker (cdr c) nil))))))))
141 (defmacro org-with-wide-buffer (&rest body)
142 "Execute body while temporarily widening the buffer."
143 (declare (debug (body)))
144 `(save-excursion
145 (save-restriction
146 (widen)
147 ,@body)))
149 (defmacro org-with-limited-levels (&rest body)
150 "Execute BODY with limited number of outline levels."
151 (declare (debug (body)))
152 `(progn
153 (defvar org-called-with-limited-levels)
154 (defvar org-outline-regexp)
155 (defvar outline-regexp)
156 (defvar org-outline-regexp-bol)
157 (let* ((org-called-with-limited-levels t)
158 (org-outline-regexp (org-get-limited-outline-regexp))
159 (outline-regexp org-outline-regexp)
160 (org-outline-regexp-bol (concat "^" org-outline-regexp)))
161 ,@body)))
163 (defmacro org-eval-in-environment (environment form)
164 (declare (debug (form form)) (indent 1))
165 `(eval (list 'let ,environment ',form)))
167 ;;;###autoload
168 (defmacro org-load-noerror-mustsuffix (file)
169 "Load FILE with optional arguments NOERROR and MUSTSUFFIX."
170 `(load ,file 'noerror nil nil 'mustsuffix))
174 ;;; Input
176 (defun org-read-function (prompt &optional allow-empty?)
177 "Prompt for a function.
178 If ALLOW-EMPTY? is non-nil, return nil rather than raising an
179 error when the user input is empty."
180 (let ((func (completing-read prompt obarray #'fboundp t)))
181 (cond ((not (string= func ""))
182 (intern func))
183 (allow-empty? nil)
184 (t (user-error "Empty input is not valid")))))
186 (defun org-completing-read (&rest args)
187 "Completing-read with SPACE being a normal character."
188 (let ((enable-recursive-minibuffers t)
189 (minibuffer-local-completion-map
190 (copy-keymap minibuffer-local-completion-map)))
191 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
192 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
193 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
194 'org-time-stamp-inactive)
195 (apply #'completing-read args)))
199 ;;; Logic
201 (defsubst org-xor (a b)
202 "Exclusive `or'."
203 (if a (not b) b))
207 ;;; Keybinding
209 (defun org-key (key)
210 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
211 Or return the original if not disputed."
212 (when org-replace-disputed-keys
213 (let* ((nkey (key-description key))
214 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
215 org-disputed-keys)))
216 (setq key (if x (cdr x) key))))
217 key)
219 (defun org-defkey (keymap key def)
220 "Define a key, possibly translated, as returned by `org-key'."
221 (define-key keymap (org-key key) def))
225 ;;; String manipulation
227 (defsubst org-trim (s &optional keep-lead)
228 "Remove whitespace at the beginning and the end of string S.
229 When optional argument KEEP-LEAD is non-nil, removing blank lines
230 at the beginning of the string does not affect leading indentation."
231 (replace-regexp-in-string
232 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
233 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
235 (defun org-string-nw-p (s)
236 "Return S if S is a string containing a non-blank character.
237 Otherwise, return nil."
238 (and (stringp s)
239 (string-match-p "[^ \r\t\n]" s)
242 (defun org-split-string (string &optional separators)
243 "Splits STRING into substrings at SEPARATORS.
245 SEPARATORS is a regular expression. When nil, it defaults to
246 \"[ \f\t\n\r\v]+\".
248 Unlike to `split-string', matching SEPARATORS at the beginning
249 and end of string are ignored."
250 (let ((separators (or separators "[ \f\t\n\r\v]+")))
251 (when (string-match (concat "\\`" separators) string)
252 (setq string (replace-match "" nil nil string)))
253 (when (string-match (concat separators "\\'") string)
254 (setq string (replace-match "" nil nil string)))
255 (split-string string separators)))
257 (defun org-string-display (string)
258 "Return STRING as it is displayed in the current buffer.
259 This function takes into consideration `invisible' and `display'
260 text properties."
261 (let* ((build-from-parts
262 (lambda (s property filter)
263 ;; Build a new string out of string S. On every group of
264 ;; contiguous characters with the same PROPERTY value,
265 ;; call FILTER on the properties list at the beginning of
266 ;; the group. If it returns a string, replace the
267 ;; characters in the group with it. Otherwise, preserve
268 ;; those characters.
269 (let ((len (length s))
270 (new "")
271 (i 0)
272 (cursor 0))
273 (while (setq i (text-property-not-all i len property nil s))
274 (let ((end (next-single-property-change i property s len))
275 (value (funcall filter (text-properties-at i s))))
276 (when value
277 (setq new (concat new (substring s cursor i) value))
278 (setq cursor end))
279 (setq i end)))
280 (concat new (substring s cursor)))))
281 (prune-invisible
282 (lambda (s)
283 (funcall build-from-parts s 'invisible
284 (lambda (props)
285 ;; If `invisible' property in PROPS means text
286 ;; is to be invisible, return the empty string.
287 ;; Otherwise return nil so that the part is
288 ;; skipped.
289 (and (or (eq t buffer-invisibility-spec)
290 (assoc-string (plist-get props 'invisible)
291 buffer-invisibility-spec))
292 "")))))
293 (replace-display
294 (lambda (s)
295 (funcall build-from-parts s 'display
296 (lambda (props)
297 ;; If there is any string specification in
298 ;; `display' property return it. Also attach
299 ;; other text properties on the part to that
300 ;; string (face...).
301 (let* ((display (plist-get props 'display))
302 (value (if (stringp display) display
303 (cl-some #'stringp display))))
304 (when value
305 (apply
306 #'propertize
307 ;; Displayed string could contain
308 ;; invisible parts, but no nested display.
309 (funcall prune-invisible value)
310 (plist-put props
311 'display
312 (and (not (stringp display))
313 (cl-remove-if #'stringp
314 display)))))))))))
315 ;; `display' property overrides `invisible' one. So we first
316 ;; replace characters with `display' property. Then we remove
317 ;; invisible characters.
318 (funcall prune-invisible (funcall replace-display string))))
320 (defun org-string-width (string)
321 "Return width of STRING when displayed in the current buffer.
322 Unlike to `string-width', this function takes into consideration
323 `invisible' and `display' text properties."
324 (string-width (org-string-display string)))
326 (defun org-not-nil (v)
327 "If V not nil, and also not the string \"nil\", then return V.
328 Otherwise return nil."
329 (and v (not (equal v "nil")) v))
331 (defun org-unbracket-string (pre post string)
332 "Remove PRE/POST from the beginning/end of STRING.
333 Both PRE and POST must be pre-/suffixes of STRING, or neither is
334 removed."
335 (if (and (string-prefix-p pre string)
336 (string-suffix-p post string))
337 (substring string (length pre) (- (length post)))
338 string))
340 (defsubst org-current-line-string (&optional to-here)
341 (buffer-substring (point-at-bol) (if to-here (point) (point-at-eol))))
345 ;;; List manipulation
347 (defsubst org-get-alist-option (option key)
348 (cond ((eq key t) t)
349 ((eq option t) t)
350 ((assoc key option) (cdr (assoc key option)))
351 (t (let ((r (cdr (assq 'default option))))
352 (if (listp r) (delq nil r) r)))))
354 (defsubst org-last (list)
355 "Return the last element of LIST."
356 (car (last list)))
358 (defun org-plist-delete (plist property)
359 "Delete PROPERTY from PLIST.
360 This is in contrast to merely setting it to 0."
361 (let (p)
362 (while plist
363 (if (not (eq property (car plist)))
364 (setq p (plist-put p (car plist) (nth 1 plist))))
365 (setq plist (cddr plist)))
368 (defsubst org-uniquify (list)
369 "Non-destructively remove duplicate elements from LIST."
370 (let ((res (copy-sequence list))) (delete-dups res)))
374 ;;; Regexp matching
376 (defsubst org-pos-in-match-range (pos n)
377 (and (match-beginning n)
378 (<= (match-beginning n) pos)
379 (>= (match-end n) pos)))
381 (defun org-match-line (regexp)
382 "Match REGEXP at the beginning of the current line."
383 (save-excursion
384 (beginning-of-line)
385 (looking-at regexp)))
389 ;;; Motion
391 (defsubst org-goto-line (N)
392 (save-restriction
393 (widen)
394 (goto-char (point-min))
395 (forward-line (1- N))))
397 (defsubst org-current-line (&optional pos)
398 (save-excursion
399 (and pos (goto-char pos))
400 ;; works also in narrowed buffer, because we start at 1, not point-min
401 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
405 ;;; Text properties
407 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
408 rear-nonsticky t mouse-map t fontified t
409 org-emphasis t)
410 "Properties to remove when a string without properties is wanted.")
412 (defsubst org-no-properties (s &optional restricted)
413 "Remove all text properties from string S.
414 When RESTRICTED is non-nil, only remove the properties listed
415 in `org-rm-props'."
416 (if restricted (remove-text-properties 0 (length s) org-rm-props s)
417 (set-text-properties 0 (length s) nil s))
420 (defun org-make-parameter-alist (flat)
421 "Return alist based on FLAT.
422 FLAT is a list with alternating symbol names and values. The
423 returned alist is a list of lists with the symbol name in car and
424 the value in cdr."
425 (when flat
426 (cons (list (car flat) (cadr flat))
427 (org-make-parameter-alist (cddr flat)))))
429 (defsubst org-get-at-bol (property)
430 "Get text property PROPERTY at the beginning of line."
431 (get-text-property (point-at-bol) property))
435 ;;; Local variables
437 (defconst org-unique-local-variables
438 '(org-element--cache
439 org-element--cache-objects
440 org-element--cache-sync-keys
441 org-element--cache-sync-requests
442 org-element--cache-sync-timer)
443 "List of local variables that cannot be transferred to another buffer.")
445 (defun org-get-local-variables ()
446 "Return a list of all local variables in an Org mode buffer."
447 (delq nil
448 (mapcar
449 (lambda (x)
450 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
451 (name (car binding)))
452 (and (not (get name 'org-state))
453 (not (memq name org-unique-local-variables))
454 (string-match-p
455 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
456 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
457 (symbol-name name))
458 binding)))
459 (with-temp-buffer
460 (org-mode)
461 (buffer-local-variables)))))
463 (defun org-clone-local-variables (from-buffer &optional regexp)
464 "Clone local variables from FROM-BUFFER.
465 Optional argument REGEXP selects variables to clone."
466 (dolist (pair (buffer-local-variables from-buffer))
467 (pcase pair
468 (`(,name . ,value) ;ignore unbound variables
469 (when (and (not (memq name org-unique-local-variables))
470 (or (null regexp) (string-match-p regexp (symbol-name name))))
471 (ignore-errors (set (make-local-variable name) value)))))))
475 ;;; Miscellaneous
477 (defsubst org-check-external-command (cmd &optional use no-error)
478 "Check if external program CMD for USE exists, error if not.
479 When the program does exist, return its path.
480 When it does not exist and NO-ERROR is set, return nil.
481 Otherwise, throw an error. The optional argument USE can describe what this
482 program is needed for, so that the error message can be more informative."
483 (or (executable-find cmd)
484 (if no-error
486 (error "Can't find `%s'%s" cmd
487 (if use (format " (%s)" use) "")))))
489 (defun org-let (list &rest body)
490 (eval (cons 'let (cons list body))))
491 (put 'org-let 'lisp-indent-function 1)
493 (defun org-let2 (list1 list2 &rest body)
494 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
495 (put 'org-let2 'lisp-indent-function 2)
497 (defsubst org-call-with-arg (command arg)
498 "Call COMMAND interactively, but pretend prefix arg was ARG."
499 (let ((current-prefix-arg arg)) (call-interactively command)))
501 (defvar org-outline-regexp) ; defined in org.el
502 (defvar org-odd-levels-only) ; defined in org.el
503 (defvar org-inlinetask-min-level) ; defined in org-inlinetask.el
504 (defun org-get-limited-outline-regexp ()
505 "Return outline-regexp with limited number of levels.
506 The number of levels is controlled by `org-inlinetask-min-level'"
507 (cond ((not (derived-mode-p 'org-mode))
508 outline-regexp)
509 ((not (featurep 'org-inlinetask))
510 org-outline-regexp)
512 (let* ((limit-level (1- org-inlinetask-min-level))
513 (nstars (if org-odd-levels-only
514 (1- (* limit-level 2))
515 limit-level)))
516 (format "\\*\\{1,%d\\} " nstars)))))
519 (provide 'org-macs)
521 ;;; org-macs.el ends here