Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob23b4d62186835ab83f5779abcb6611b65a3fbcc7
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: https://orgmode.org
10 ;; Version: 9.1.12
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
46 ;; webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; https://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; https://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (defvar org-inlinetask-min-level)
72 ;;;; Require other packages
74 (require 'cl-lib)
76 (eval-when-compile (require 'gnus-sum))
78 (require 'calendar)
79 (require 'find-func)
80 (require 'format-spec)
82 (or (eq this-command 'eval-buffer)
83 (condition-case nil
84 (load (concat (file-name-directory load-file-name)
85 "org-loaddefs.el")
86 nil t t t)
87 (error
88 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
89 (sit-for 3)
90 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
91 (sit-for 3))))
93 (require 'org-macs)
94 (require 'org-compat)
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 (defvar org-outline-regexp "\\*+ "
99 "Regexp to match Org headlines.")
101 (defvar org-outline-regexp-bol "^\\*+ "
102 "Regexp to match Org headlines.
103 This is similar to `org-outline-regexp' but additionally makes
104 sure that we are at the beginning of the line.")
106 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
107 "Matches a headline, putting stars and text into groups.
108 Stars are put in group 1 and the trimmed body in group 2.")
110 (declare-function calendar-check-holidays "holidays" (date))
111 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
112 (declare-function cdlatex-math-symbol "ext:cdlatex")
113 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocking-buffer "org-clock" ())
130 (declare-function org-clocktable-shift "org-clock" (dir n))
131 (declare-function
132 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-link-parser "org-element" ())
142 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
143 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
144 (declare-function org-element-property "org-element" (property element))
145 (declare-function org-element-put-property "org-element" (element property value))
146 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
147 (declare-function org-element-type "org-element" (element))
148 (declare-function org-element-update-syntax "org-element" ())
149 (declare-function org-id-find-id-file "org-id" (id))
150 (declare-function org-id-get-create "org-id" (&optional force))
151 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
152 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
153 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
154 (declare-function org-plot/gnuplot "org-plot" (&optional params))
155 (declare-function org-table-align "org-table" ())
156 (declare-function org-table-begin "org-table" (&optional table-type))
157 (declare-function org-table-beginning-of-field "org-table" (&optional n))
158 (declare-function org-table-blank-field "org-table" ())
159 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
160 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
161 (declare-function org-table-cut-region "org-table" (beg end))
162 (declare-function org-table-edit-field "org-table" (arg))
163 (declare-function org-table-end "org-table" (&optional table-type))
164 (declare-function org-table-end-of-field "org-table" (&optional n))
165 (declare-function org-table-insert-row "org-table" (&optional arg))
166 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
167 (declare-function org-table-maybe-eval-formula "org-table" ())
168 (declare-function org-table-maybe-recalculate-line "org-table" ())
169 (declare-function org-table-next-row "org-table" ())
170 (declare-function org-table-paste-rectangle "org-table" ())
171 (declare-function org-table-recalculate "org-table" (&optional all noalign))
172 (declare-function
173 org-table-sort-lines "org-table"
174 (&optional with-case sorting-type getkey-func compare-func interactive?))
175 (declare-function org-table-shrink "org-table" (&optional begin end))
176 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp)
186 (defvar org-element-paragraph-separate)
187 (defvar org-indent-indentation-per-level)
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Ebnf2ps" ebnf2ps)
262 (const :tag "Emacs Lisp" emacs-lisp)
263 (const :tag "Forth" forth)
264 (const :tag "Fortran" fortran)
265 (const :tag "Gnuplot" gnuplot)
266 (const :tag "Haskell" haskell)
267 (const :tag "hledger" hledger)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "Vala" vala))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 \\<org-mode-map>
376 A deadline is this string, followed by a time stamp. It must be
377 a word, terminated by a colon. You can insert a schedule keyword
378 and a timestamp with `\\[org-deadline]'.")
380 (defvar org-scheduled-string "SCHEDULED:"
381 "String to mark scheduled TODO entries.
382 \\<org-mode-map>
383 A schedule is this string, followed by a time stamp. It must be
384 a word, terminated by a colon. You can insert a schedule keyword
385 and a timestamp with `\\[org-schedule]'.")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (defconst org-tag-re "[[:alnum:]_@#%]+"
525 "Regexp matching a single tag.")
527 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
528 "Regexp matching the tag group at the end of a line, with leading spaces.
529 Tags are stored in match group 1. Match group 2 stores the tags
530 without the enclosing colons.")
532 (defconst org-tag-line-re
533 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
534 "Regexp matching tags in a headline.
535 Tags are stored in match group 1. Match group 2 stores the tags
536 without the enclosing colons.")
538 (eval-and-compile
539 (defconst org-comment-string "COMMENT"
540 "Entries starting with this keyword will never be exported.
541 \\<org-mode-map>
542 An entry can be toggled between COMMENT and normal with
543 `\\[org-toggle-comment]'."))
546 ;;;; LaTeX Environments and Fragments
548 (defconst org-latex-regexps
549 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
550 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
551 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
552 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
554 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
555 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
556 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
557 "Regular expressions for matching embedded LaTeX.")
559 ;;;; Node Property
561 (defconst org-effort-property "Effort"
562 "The property that is being used to keep track of effort estimates.
563 Effort estimates given in this property need to have the format H:MM.")
565 ;;;; Table
567 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
568 "Detect an org-type or table-type table.")
570 (defconst org-table-line-regexp "^[ \t]*|"
571 "Detect an org-type table line.")
573 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
574 "Detect an org-type table line.")
576 (defconst org-table-hline-regexp "^[ \t]*|-"
577 "Detect an org-type table hline.")
579 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
580 "Detect a table-type table hline.")
582 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
583 "Detect the first line outside a table when searching from within it.
584 This works for both table types.")
586 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
587 "Detect a #+TBLFM line.")
589 ;;;; Timestamp
591 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
592 "Regular expression for fast time stamp matching.")
594 (defconst org-ts-regexp-inactive
595 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
596 "Regular expression for fast inactive time stamp matching.")
598 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
599 "Regular expression for fast time stamp matching.")
601 (defconst org-ts-regexp0
602 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
603 "Regular expression matching time strings for analysis.
604 This one does not require the space after the date, so it can be used
605 on a string that terminates immediately after the date.")
607 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
608 "Regular expression matching time strings for analysis.")
610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
611 "Regular expression matching time stamps, with groups.")
613 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
614 "Regular expression matching time stamps (also [..]), with groups.")
616 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
617 "Regular expression matching a time stamp range.")
619 (defconst org-tr-regexp-both
620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
621 "Regular expression matching a time stamp range.")
623 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
624 org-ts-regexp "\\)?")
625 "Regular expression matching a time stamp or time stamp range.")
627 (defconst org-tsr-regexp-both
628 (concat org-ts-regexp-both "\\(--?-?"
629 org-ts-regexp-both "\\)?")
630 "Regular expression matching a time stamp or time stamp range.
631 The time stamps may be either active or inactive.")
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
639 "Formats for `format-time-string' which are used for time stamps.")
642 ;;; The custom variables
644 (defgroup org nil
645 "Outline-based notes management and organizer."
646 :tag "Org"
647 :group 'outlines
648 :group 'calendar)
650 (defcustom org-mode-hook nil
651 "Mode hook for Org mode, run after the mode was turned on."
652 :group 'org
653 :type 'hook)
655 (defcustom org-load-hook nil
656 "Hook that is run after org.el has been loaded."
657 :group 'org
658 :type 'hook)
660 (defcustom org-log-buffer-setup-hook nil
661 "Hook that is run after an Org log buffer is created."
662 :group 'org
663 :version "24.1"
664 :type 'hook)
666 (defvar org-modules) ; defined below
667 (defvar org-modules-loaded nil
668 "Have the modules been loaded already?")
670 (defun org-load-modules-maybe (&optional force)
671 "Load all extensions listed in `org-modules'."
672 (when (or force (not org-modules-loaded))
673 (dolist (ext org-modules)
674 (condition-case nil (require ext)
675 (error (message "Problems while trying to load feature `%s'" ext))))
676 (setq org-modules-loaded t)))
678 (defun org-set-modules (var value)
679 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
680 (set var value)
681 (when (featurep 'org)
682 (org-load-modules-maybe 'force)
683 (org-element-cache-reset 'all)))
685 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-tempo org-eww)
686 "Modules that should always be loaded together with org.el.
688 If a description starts with <C>, the file is not part of Emacs
689 and loading it will require that you have downloaded and properly
690 installed the Org mode distribution.
692 You can also use this system to load external packages (i.e. neither Org
693 core modules, nor modules from the CONTRIB directory). Just add symbols
694 to the end of the list. If the package is called org-xyz.el, then you need
695 to add the symbol `xyz', and the package must have a call to:
697 (provide \\='org-xyz)
699 For export specific modules, see also `org-export-backends'."
700 :group 'org
701 :set 'org-set-modules
702 :version "26.1"
703 :package-version '(Org . "9.2")
704 :type
705 '(set :greedy t
706 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
707 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
708 (const :tag " crypt: Encryption of subtrees" org-crypt)
709 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
710 (const :tag " docview: Links to doc-view buffers" org-docview)
711 (const :tag " eww: Store link to url of eww" org-eww)
712 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
713 (const :tag " habit: Track your consistency with habits" org-habit)
714 (const :tag " id: Global IDs for identifying entries" org-id)
715 (const :tag " info: Links to Info nodes" org-info)
716 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
717 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
718 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
719 (const :tag " mouse: Additional mouse support" org-mouse)
720 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
721 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
722 (const :tag " tempo: Fast completion for structures" org-tempo)
723 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
725 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
726 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
727 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
728 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
729 (const :tag "C collector: Collect properties into tables" org-collector)
730 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
731 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
732 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
733 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
734 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
735 (const :tag "C eval: Include command output as text" org-eval)
736 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
737 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
738 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
739 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
740 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
741 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
742 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
743 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
744 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
745 (const :tag "C man: Support for links to manpages in Org mode" org-man)
746 (const :tag "C mew: Links to Mew folders/messages" org-mew)
747 (const :tag "C mtags: Support for muse-like tags" org-mtags)
748 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
749 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
750 (const :tag "C registry: A registry for Org links" org-registry)
751 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
752 (const :tag "C secretary: Team management with Org" org-secretary)
753 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
754 (const :tag "C toc: Table of contents for Org buffer" org-toc)
755 (const :tag "C track: Keep up with Org mode development" org-track)
756 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
757 (const :tag "C vm: Links to VM folders/messages" org-vm)
758 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
759 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
760 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
762 (defvar org-export-registered-backends) ; From ox.el.
763 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
764 (declare-function org-export-backend-name "ox" (backend) t)
765 (defcustom org-export-backends '(ascii html icalendar latex odt)
766 "List of export back-ends that should be always available.
768 If a description starts with <C>, the file is not part of Emacs
769 and loading it will require that you have downloaded and properly
770 installed the Org mode distribution.
772 Unlike to `org-modules', libraries in this list will not be
773 loaded along with Org, but only once the export framework is
774 needed.
776 This variable needs to be set before org.el is loaded. If you
777 need to make a change while Emacs is running, use the customize
778 interface or run the following code, where VAL stands for the new
779 value of the variable, after updating it:
781 (progn
782 (setq org-export-registered-backends
783 (cl-remove-if-not
784 (lambda (backend)
785 (let ((name (org-export-backend-name backend)))
786 (or (memq name val)
787 (catch \\='parentp
788 (dolist (b val)
789 (and (org-export-derived-backend-p b name)
790 (throw \\='parentp t)))))))
791 org-export-registered-backends))
792 (let ((new-list (mapcar #\\='org-export-backend-name
793 org-export-registered-backends)))
794 (dolist (backend val)
795 (cond
796 ((not (load (format \"ox-%s\" backend) t t))
797 (message \"Problems while trying to load export back-end \\=`%s\\='\"
798 backend))
799 ((not (memq backend new-list)) (push backend new-list))))
800 (set-default \\='org-export-backends new-list)))
802 Adding a back-end to this list will also pull the back-end it
803 depends on, if any."
804 :group 'org
805 :group 'org-export
806 :version "26.1"
807 :package-version '(Org . "9.0")
808 :initialize 'custom-initialize-set
809 :set (lambda (var val)
810 (if (not (featurep 'ox)) (set-default var val)
811 ;; Any back-end not required anymore (not present in VAL and not
812 ;; a parent of any back-end in the new value) is removed from the
813 ;; list of registered back-ends.
814 (setq org-export-registered-backends
815 (cl-remove-if-not
816 (lambda (backend)
817 (let ((name (org-export-backend-name backend)))
818 (or (memq name val)
819 (catch 'parentp
820 (dolist (b val)
821 (and (org-export-derived-backend-p b name)
822 (throw 'parentp t)))))))
823 org-export-registered-backends))
824 ;; Now build NEW-LIST of both new back-ends and required
825 ;; parents.
826 (let ((new-list (mapcar #'org-export-backend-name
827 org-export-registered-backends)))
828 (dolist (backend val)
829 (cond
830 ((not (load (format "ox-%s" backend) t t))
831 (message "Problems while trying to load export back-end `%s'"
832 backend))
833 ((not (memq backend new-list)) (push backend new-list))))
834 ;; Set VAR to that list with fixed dependencies.
835 (set-default var new-list))))
836 :type '(set :greedy t
837 (const :tag " ascii Export buffer to ASCII format" ascii)
838 (const :tag " beamer Export buffer to Beamer presentation" beamer)
839 (const :tag " html Export buffer to HTML format" html)
840 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
841 (const :tag " latex Export buffer to LaTeX format" latex)
842 (const :tag " man Export buffer to MAN format" man)
843 (const :tag " md Export buffer to Markdown format" md)
844 (const :tag " odt Export buffer to ODT format" odt)
845 (const :tag " org Export buffer to Org format" org)
846 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
847 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
848 (const :tag "C deck Export buffer to deck.js presentations" deck)
849 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
850 (const :tag "C groff Export buffer to Groff format" groff)
851 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
852 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
853 (const :tag "C s5 Export buffer to s5 presentations" s5)
854 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
856 (eval-after-load 'ox
857 '(dolist (backend org-export-backends)
858 (condition-case nil (require (intern (format "ox-%s" backend)))
859 (error (message "Problems while trying to load export back-end `%s'"
860 backend)))))
862 (defcustom org-support-shift-select nil
863 "Non-nil means make shift-cursor commands select text when possible.
864 \\<org-mode-map>\
866 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
867 start selecting a region, or enlarge regions started in this way.
868 In Org mode, in special contexts, these same keys are used for
869 other purposes, important enough to compete with shift selection.
870 Org tries to balance these needs by supporting `shift-select-mode'
871 outside these special contexts, under control of this variable.
873 The default of this variable is nil, to avoid confusing behavior. Shifted
874 cursor keys will then execute Org commands in the following contexts:
875 - on a headline, changing TODO state (left/right) and priority (up/down)
876 - on a time stamp, changing the time
877 - in a plain list item, changing the bullet type
878 - in a property definition line, switching between allowed values
879 - in the BEGIN line of a clock table (changing the time block).
880 Outside these contexts, the commands will throw an error.
882 When this variable is t and the cursor is not in a special
883 context, Org mode will support shift-selection for making and
884 enlarging regions. To make this more effective, the bullet
885 cycling will no longer happen anywhere in an item line, but only
886 if the cursor is exactly on the bullet.
888 If you set this variable to the symbol `always', then the keys
889 will not be special in headlines, property lines, and item lines,
890 to make shift selection work there as well. If this is what you
891 want, you can use the following alternative commands:
892 `\\[org-todo]' and `\\[org-priority]' \
893 to change TODO state and priority,
894 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
895 can be used to switch TODO sets,
896 `\\[org-ctrl-c-minus]' to cycle item bullet types,
897 and properties can be edited by hand or in column view.
899 However, when the cursor is on a timestamp, shift-cursor commands
900 will still edit the time stamp - this is just too good to give up."
901 :group 'org
902 :type '(choice
903 (const :tag "Never" nil)
904 (const :tag "When outside special context" t)
905 (const :tag "Everywhere except timestamps" always)))
907 (defcustom org-loop-over-headlines-in-active-region nil
908 "Shall some commands act upon headlines in the active region?
910 When set to t, some commands will be performed in all headlines
911 within the active region.
913 When set to `start-level', some commands will be performed in all
914 headlines within the active region, provided that these headlines
915 are of the same level than the first one.
917 When set to a string, those commands will be performed on the
918 matching headlines within the active region. Such string must be
919 a tags/property/todo match as it is used in the agenda tags view.
921 The list of commands is: `org-schedule', `org-deadline',
922 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
923 `org-archive-to-archive-sibling'. The archiving commands skip
924 already archived entries."
925 :type '(choice (const :tag "Don't loop" nil)
926 (const :tag "All headlines in active region" t)
927 (const :tag "In active region, headlines at the same level than the first one" start-level)
928 (string :tag "Tags/Property/Todo matcher"))
929 :version "24.1"
930 :group 'org-todo
931 :group 'org-archive)
933 (defcustom org-startup-folded t
934 "Non-nil means entering Org mode will switch to OVERVIEW.
936 This can also be configured on a per-file basis by adding one of
937 the following lines anywhere in the buffer:
939 #+STARTUP: fold (or `overview', this is equivalent)
940 #+STARTUP: nofold (or `showall', this is equivalent)
941 #+STARTUP: content
942 #+STARTUP: showeverything
944 Set `org-agenda-inhibit-startup' to a non-nil value if you want
945 to ignore this option when Org opens agenda files for the first
946 time."
947 :group 'org-startup
948 :type '(choice
949 (const :tag "nofold: show all" nil)
950 (const :tag "fold: overview" t)
951 (const :tag "content: all headlines" content)
952 (const :tag "show everything, even drawers" showeverything)))
954 (defcustom org-startup-truncated t
955 "Non-nil means entering Org mode will set `truncate-lines'.
956 This is useful since some lines containing links can be very long and
957 uninteresting. Also tables look terrible when wrapped.
959 The variable `org-startup-truncated' allows to configure
960 truncation for Org mode different to the other modes that use the
961 variable `truncate-lines' and as a shortcut instead of putting
962 the variable `truncate-lines' into the `org-mode-hook'. If one
963 wants to configure truncation for Org mode not statically but
964 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
965 the variable `truncate-lines' has to be used because in such a
966 case it is too late to set the variable `org-startup-truncated'."
967 :group 'org-startup
968 :type 'boolean)
970 (defcustom org-startup-indented nil
971 "Non-nil means turn on `org-indent-mode' on startup.
972 This can also be configured on a per-file basis by adding one of
973 the following lines anywhere in the buffer:
975 #+STARTUP: indent
976 #+STARTUP: noindent"
977 :group 'org-structure
978 :type '(choice
979 (const :tag "Not" nil)
980 (const :tag "Globally (slow on startup in large files)" t)))
982 (defcustom org-use-sub-superscripts t
983 "Non-nil means interpret \"_\" and \"^\" for display.
985 If you want to control how Org exports those characters, see
986 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
987 used to be an alias for `org-export-with-sub-superscripts' in
988 Org <8.0, it is not anymore.
990 When this option is turned on, you can use TeX-like syntax for
991 sub- and superscripts within the buffer. Several characters after
992 \"_\" or \"^\" will be considered as a single item - so grouping
993 with {} is normally not needed. For example, the following things
994 will be parsed as single sub- or superscripts:
996 10^24 or 10^tau several digits will be considered 1 item.
997 10^-12 or 10^-tau a leading sign with digits or a word
998 x^2-y^3 will be read as x^2 - y^3, because items are
999 terminated by almost any nonword/nondigit char.
1000 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1002 Still, ambiguity is possible. So when in doubt, use {} to enclose
1003 the sub/superscript. If you set this variable to the symbol `{}',
1004 the braces are *required* in order to trigger interpretations as
1005 sub/superscript. This can be helpful in documents that need \"_\"
1006 frequently in plain text."
1007 :group 'org-startup
1008 :version "24.4"
1009 :package-version '(Org . "8.0")
1010 :type '(choice
1011 (const :tag "Always interpret" t)
1012 (const :tag "Only with braces" {})
1013 (const :tag "Never interpret" nil)))
1015 (defcustom org-startup-with-beamer-mode nil
1016 "Non-nil means turn on `org-beamer-mode' on startup.
1017 This can also be configured on a per-file basis by adding one of
1018 the following lines anywhere in the buffer:
1020 #+STARTUP: beamer"
1021 :group 'org-startup
1022 :version "24.1"
1023 :type 'boolean)
1025 (defcustom org-startup-align-all-tables nil
1026 "Non-nil means align all tables when visiting a file.
1027 This can also be configured on a per-file basis by adding one of
1028 the following lines anywhere in the buffer:
1029 #+STARTUP: align
1030 #+STARTUP: noalign"
1031 :group 'org-startup
1032 :type 'boolean)
1034 (defcustom org-startup-shrink-all-tables nil
1035 "Non-nil means shrink all table columns with a width cookie.
1036 This can also be configured on a per-file basis by adding one of
1037 the following lines anywhere in the buffer:
1038 #+STARTUP: shrink"
1039 :group 'org-startup
1040 :type 'boolean
1041 :version "27.1"
1042 :package-version '(Org . "9.2")
1043 :safe #'booleanp)
1045 (defcustom org-startup-with-inline-images nil
1046 "Non-nil means show inline images when loading a new Org file.
1047 This can also be configured on a per-file basis by adding one of
1048 the following lines anywhere in the buffer:
1049 #+STARTUP: inlineimages
1050 #+STARTUP: noinlineimages"
1051 :group 'org-startup
1052 :version "24.1"
1053 :type 'boolean)
1055 (defcustom org-startup-with-latex-preview nil
1056 "Non-nil means preview LaTeX fragments when loading a new Org file.
1058 This can also be configured on a per-file basis by adding one of
1059 the following lines anywhere in the buffer:
1060 #+STARTUP: latexpreview
1061 #+STARTUP: nolatexpreview"
1062 :group 'org-startup
1063 :version "24.4"
1064 :package-version '(Org . "8.0")
1065 :type 'boolean)
1067 (defcustom org-insert-mode-line-in-empty-file nil
1068 "Non-nil means insert the first line setting Org mode in empty files.
1069 When the function `org-mode' is called interactively in an empty file, this
1070 normally means that the file name does not automatically trigger Org mode.
1071 To ensure that the file will always be in Org mode in the future, a
1072 line enforcing Org mode will be inserted into the buffer, if this option
1073 has been set."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-replace-disputed-keys nil
1078 "Non-nil means use alternative key bindings for some keys.
1080 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1081 These keys are also used by other packages like Shift Select mode,
1082 CUA mode or Windmove. If you want to use Org mode together with
1083 one of these other modes, or more generally if you would like to
1084 move some Org mode commands to other keys, set this variable and
1085 configure the keys with the variable `org-disputed-keys'.
1087 This option is only relevant at load-time of Org mode, and must be set
1088 *before* org.el is loaded. Changing it requires a restart of Emacs to
1089 become effective."
1090 :group 'org-startup
1091 :type 'boolean)
1093 (defcustom org-use-extra-keys nil
1094 "Non-nil means use extra key sequence definitions for certain commands.
1095 This happens automatically if `window-system' is nil. This
1096 variable lets you do the same manually. You must set it before
1097 loading Org."
1098 :group 'org-startup
1099 :type 'boolean)
1101 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1103 (defcustom org-disputed-keys
1104 '(([(shift up)] . [(meta p)])
1105 ([(shift down)] . [(meta n)])
1106 ([(shift left)] . [(meta -)])
1107 ([(shift right)] . [(meta +)])
1108 ([(control shift right)] . [(meta shift +)])
1109 ([(control shift left)] . [(meta shift -)]))
1110 "Keys for which Org mode and other modes compete.
1111 This is an alist, cars are the default keys, second element specifies
1112 the alternative to use when `org-replace-disputed-keys' is t.
1114 Keys can be specified in any syntax supported by `define-key'.
1115 The value of this option takes effect only at Org mode startup,
1116 therefore you'll have to restart Emacs to apply it after changing."
1117 :group 'org-startup
1118 :type 'alist)
1120 (defun org-key (key)
1121 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1122 Or return the original if not disputed."
1123 (when org-replace-disputed-keys
1124 (let* ((nkey (key-description key))
1125 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1126 org-disputed-keys)))
1127 (setq key (if x (cdr x) key))))
1128 key)
1130 (defun org-defkey (keymap key def)
1131 "Define a key, possibly translated, as returned by `org-key'."
1132 (define-key keymap (org-key key) def))
1134 (defcustom org-ellipsis nil
1135 "The ellipsis to use in the Org mode outline.
1137 When nil, just use the standard three dots. When a non-empty string,
1138 use that string instead.
1140 The change affects only Org mode (which will then use its own display table).
1141 Changing this requires executing `\\[org-mode]' in a buffer to become
1142 effective."
1143 :group 'org-startup
1144 :type '(choice (const :tag "Default" nil)
1145 (string :tag "String" :value "...#"))
1146 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1148 (defvar org-display-table nil
1149 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1151 (defgroup org-keywords nil
1152 "Keywords in Org mode."
1153 :tag "Org Keywords"
1154 :group 'org)
1156 (defcustom org-closed-keep-when-no-todo nil
1157 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1158 :group 'org-todo
1159 :group 'org-keywords
1160 :version "24.4"
1161 :package-version '(Org . "8.0")
1162 :type 'boolean)
1164 (defgroup org-structure nil
1165 "Options concerning the general structure of Org files."
1166 :tag "Org Structure"
1167 :group 'org)
1169 (defgroup org-reveal-location nil
1170 "Options about how to make context of a location visible."
1171 :tag "Org Reveal Location"
1172 :group 'org-structure)
1174 (defcustom org-show-context-detail '((agenda . local)
1175 (bookmark-jump . lineage)
1176 (isearch . lineage)
1177 (default . ancestors))
1178 "Alist between context and visibility span when revealing a location.
1180 \\<org-mode-map>Some actions may move point into invisible
1181 locations. As a consequence, Org always expose a neighborhood
1182 around point. How much is shown depends on the initial action,
1183 or context. Valid contexts are
1185 agenda when exposing an entry from the agenda
1186 org-goto when using the command `org-goto' (`\\[org-goto]')
1187 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1188 tags-tree when constructing a sparse tree based on tags matches
1189 link-search when exposing search matches associated with a link
1190 mark-goto when exposing the jump goal of a mark
1191 bookmark-jump when exposing a bookmark location
1192 isearch when exiting from an incremental search
1193 default default for all contexts not set explicitly
1195 Allowed visibility spans are
1197 minimal show current headline; if point is not on headline,
1198 also show entry
1200 local show current headline, entry and next headline
1202 ancestors show current headline and its direct ancestors; if
1203 point is not on headline, also show entry
1205 lineage show current headline, its direct ancestors and all
1206 their children; if point is not on headline, also show
1207 entry and first child
1209 tree show current headline, its direct ancestors and all
1210 their children; if point is not on headline, also show
1211 entry and all children
1213 canonical show current headline, its direct ancestors along with
1214 their entries and children; if point is not located on
1215 the headline, also show current entry and all children
1217 As special cases, a nil or t value means show all contexts in
1218 `minimal' or `canonical' view, respectively.
1220 Some views can make displayed information very compact, but also
1221 make it harder to edit the location of the match. In such
1222 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1223 more context."
1224 :group 'org-reveal-location
1225 :version "26.1"
1226 :package-version '(Org . "9.0")
1227 :type '(choice
1228 (const :tag "Canonical" t)
1229 (const :tag "Minimal" nil)
1230 (repeat :greedy t :tag "Individual contexts"
1231 (cons
1232 (choice :tag "Context"
1233 (const agenda)
1234 (const org-goto)
1235 (const occur-tree)
1236 (const tags-tree)
1237 (const link-search)
1238 (const mark-goto)
1239 (const bookmark-jump)
1240 (const isearch)
1241 (const default))
1242 (choice :tag "Detail level"
1243 (const minimal)
1244 (const local)
1245 (const ancestors)
1246 (const lineage)
1247 (const tree)
1248 (const canonical))))))
1250 (defcustom org-indirect-buffer-display 'other-window
1251 "How should indirect tree buffers be displayed?
1253 This applies to indirect buffers created with the commands
1254 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1256 Valid values are:
1257 current-window Display in the current window
1258 other-window Just display in another window.
1259 dedicated-frame Create one new frame, and re-use it each time.
1260 new-frame Make a new frame each time. Note that in this case
1261 previously-made indirect buffers are kept, and you need to
1262 kill these buffers yourself."
1263 :group 'org-structure
1264 :group 'org-agenda-windows
1265 :type '(choice
1266 (const :tag "In current window" current-window)
1267 (const :tag "In current frame, other window" other-window)
1268 (const :tag "Each time a new frame" new-frame)
1269 (const :tag "One dedicated frame" dedicated-frame)))
1271 (defcustom org-use-speed-commands nil
1272 "Non-nil means activate single letter commands at beginning of a headline.
1273 This may also be a function to test for appropriate locations where speed
1274 commands should be active.
1276 For example, to activate speed commands when the point is on any
1277 star at the beginning of the headline, you can do this:
1279 (setq org-use-speed-commands
1280 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1281 :group 'org-structure
1282 :type '(choice
1283 (const :tag "Never" nil)
1284 (const :tag "At beginning of headline stars" t)
1285 (function)))
1287 (defcustom org-speed-commands-user nil
1288 "Alist of additional speed commands.
1289 This list will be checked before `org-speed-commands-default'
1290 when the variable `org-use-speed-commands' is non-nil
1291 and when the cursor is at the beginning of a headline.
1292 The car of each entry is a string with a single letter, which must
1293 be assigned to `self-insert-command' in the global map.
1294 The cdr is either a command to be called interactively, a function
1295 to be called, or a form to be evaluated.
1296 An entry that is just a list with a single string will be interpreted
1297 as a descriptive headline that will be added when listing the speed
1298 commands in the Help buffer using the `?' speed command."
1299 :group 'org-structure
1300 :type '(repeat :value ("k" . ignore)
1301 (choice :value ("k" . ignore)
1302 (list :tag "Descriptive Headline" (string :tag "Headline"))
1303 (cons :tag "Letter and Command"
1304 (string :tag "Command letter")
1305 (choice
1306 (function)
1307 (sexp))))))
1309 (defcustom org-bookmark-names-plist
1310 '(:last-capture "org-capture-last-stored"
1311 :last-refile "org-refile-last-stored"
1312 :last-capture-marker "org-capture-last-stored-marker")
1313 "Names for bookmarks automatically set by some Org commands.
1314 This can provide strings as names for a number of bookmarks Org sets
1315 automatically. The following keys are currently implemented:
1316 :last-capture
1317 :last-capture-marker
1318 :last-refile
1319 When a key does not show up in the property list, the corresponding bookmark
1320 is not set."
1321 :group 'org-structure
1322 :type 'plist)
1324 (defgroup org-cycle nil
1325 "Options concerning visibility cycling in Org mode."
1326 :tag "Org Cycle"
1327 :group 'org-structure)
1329 (defcustom org-cycle-skip-children-state-if-no-children t
1330 "Non-nil means skip CHILDREN state in entries that don't have any."
1331 :group 'org-cycle
1332 :type 'boolean)
1334 (defcustom org-cycle-max-level nil
1335 "Maximum level which should still be subject to visibility cycling.
1336 Levels higher than this will, for cycling, be treated as text, not a headline.
1337 When `org-odd-levels-only' is set, a value of N in this variable actually
1338 means 2N-1 stars as the limiting headline.
1339 When nil, cycle all levels.
1340 Note that the limiting level of cycling is also influenced by
1341 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1342 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1343 than its value."
1344 :group 'org-cycle
1345 :type '(choice
1346 (const :tag "No limit" nil)
1347 (integer :tag "Maximum level")))
1349 (defcustom org-hide-block-startup nil
1350 "Non-nil means entering Org mode will fold all blocks.
1351 This can also be set in on a per-file basis with
1353 #+STARTUP: hideblocks
1354 #+STARTUP: showblocks"
1355 :group 'org-startup
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-global-at-bob nil
1360 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1362 This makes it possible to do global cycling without having to use `S-TAB'
1363 or `\\[universal-argument] TAB'. For this special case to work, the first \
1364 line of the buffer
1365 must not be a headline -- it may be empty or some other text.
1367 When used in this way, `org-cycle-hook' is disabled temporarily to make
1368 sure the cursor stays at the beginning of the buffer.
1370 When this option is nil, don't do anything special at the beginning of
1371 the buffer."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-level-after-item/entry-creation t
1376 "Non-nil means cycle entry level or item indentation in new empty entries.
1378 When the cursor is at the end of an empty headline, i.e., with only stars
1379 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1380 and then all possible ancestor states, before returning to the original state.
1381 This makes data entry extremely fast: M-RET to create a new headline,
1382 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1384 When the cursor is at the end of an empty plain list item, one TAB will
1385 make it a subitem, two or more tabs will back up to make this an item
1386 higher up in the item hierarchy."
1387 :group 'org-cycle
1388 :type 'boolean)
1390 (defcustom org-cycle-emulate-tab t
1391 "Where should `org-cycle' emulate TAB.
1392 nil Never
1393 white Only in completely white lines
1394 whitestart Only at the beginning of lines, before the first non-white char
1395 t Everywhere except in headlines
1396 exc-hl-bol Everywhere except at the start of a headline
1397 If TAB is used in a place where it does not emulate TAB, the current subtree
1398 visibility is cycled."
1399 :group 'org-cycle
1400 :type '(choice (const :tag "Never" nil)
1401 (const :tag "Only in completely white lines" white)
1402 (const :tag "Before first char in a line" whitestart)
1403 (const :tag "Everywhere except in headlines" t)
1404 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1406 (defcustom org-cycle-separator-lines 2
1407 "Number of empty lines needed to keep an empty line between collapsed trees.
1408 If you leave an empty line between the end of a subtree and the following
1409 headline, this empty line is hidden when the subtree is folded.
1410 Org mode will leave (exactly) one empty line visible if the number of
1411 empty lines is equal or larger to the number given in this variable.
1412 So the default 2 means at least 2 empty lines after the end of a subtree
1413 are needed to produce free space between a collapsed subtree and the
1414 following headline.
1416 If the number is negative, and the number of empty lines is at least -N,
1417 all empty lines are shown.
1419 Special case: when 0, never leave empty lines in collapsed view."
1420 :group 'org-cycle
1421 :type 'integer)
1422 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1424 (defcustom org-pre-cycle-hook nil
1425 "Hook that is run before visibility cycling is happening.
1426 The function(s) in this hook must accept a single argument which indicates
1427 the new state that will be set right after running this hook. The
1428 argument is a symbol. Before a global state change, it can have the values
1429 `overview', `content', or `all'. Before a local state change, it can have
1430 the values `folded', `children', or `subtree'."
1431 :group 'org-cycle
1432 :type 'hook)
1434 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1435 org-cycle-show-empty-lines
1436 org-optimize-window-after-visibility-change)
1437 "Hook that is run after `org-cycle' has changed the buffer visibility.
1438 The function(s) in this hook must accept a single argument which indicates
1439 the new state that was set by the most recent `org-cycle' command. The
1440 argument is a symbol. After a global state change, it can have the values
1441 `overview', `contents', or `all'. After a local state change, it can have
1442 the values `folded', `children', or `subtree'."
1443 :group 'org-cycle
1444 :type 'hook
1445 :version "26.1"
1446 :package-version '(Org . "8.3"))
1448 (defgroup org-edit-structure nil
1449 "Options concerning structure editing in Org mode."
1450 :tag "Org Edit Structure"
1451 :group 'org-structure)
1453 (defcustom org-odd-levels-only nil
1454 "Non-nil means skip even levels and only use odd levels for the outline.
1455 This has the effect that two stars are being added/taken away in
1456 promotion/demotion commands. It also influences how levels are
1457 handled by the exporters.
1458 Changing it requires restart of `font-lock-mode' to become effective
1459 for fontification also in regions already fontified.
1460 You may also set this on a per-file basis by adding one of the following
1461 lines to the buffer:
1463 #+STARTUP: odd
1464 #+STARTUP: oddeven"
1465 :group 'org-edit-structure
1466 :group 'org-appearance
1467 :type 'boolean)
1469 (defcustom org-adapt-indentation t
1470 "Non-nil means adapt indentation to outline node level.
1472 When this variable is set, Org assumes that you write outlines by
1473 indenting text in each node to align with the headline (after the
1474 stars). The following issues are influenced by this variable:
1476 - The indentation is increased by one space in a demotion
1477 command, and decreased by one in a promotion command. However,
1478 in the latter case, if shifting some line in the entry body
1479 would alter document structure (e.g., insert a new headline),
1480 indentation is not changed at all.
1482 - Property drawers and planning information is inserted indented
1483 when this variable is set. When nil, they will not be indented.
1485 - TAB indents a line relative to current level. The lines below
1486 a headline will be indented when this variable is set.
1488 Note that this is all about true indentation, by adding and
1489 removing space characters. See also \"org-indent.el\" which does
1490 level-dependent indentation in a virtual way, i.e. at display
1491 time in Emacs."
1492 :group 'org-edit-structure
1493 :type 'boolean
1494 :safe #'booleanp)
1496 (defcustom org-special-ctrl-a/e nil
1497 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1499 When t, `C-a' will bring back the cursor to the beginning of the
1500 headline text, i.e. after the stars and after a possible TODO
1501 keyword. In an item, this will be the position after bullet and
1502 check-box, if any. When the cursor is already at that position,
1503 another `C-a' will bring it to the beginning of the line.
1505 `C-e' will jump to the end of the headline, ignoring the presence
1506 of tags in the headline. A second `C-e' will then jump to the
1507 true end of the line, after any tags. This also means that, when
1508 this variable is non-nil, `C-e' also will never jump beyond the
1509 end of the heading of a folded section, i.e. not after the
1510 ellipses.
1512 When set to the symbol `reversed', the first `C-a' or `C-e' works
1513 normally, going to the true line boundary first. Only a directly
1514 following, identical keypress will bring the cursor to the
1515 special positions.
1517 This may also be a cons cell where the behavior for `C-a' and
1518 `C-e' is set separately."
1519 :group 'org-edit-structure
1520 :type '(choice
1521 (const :tag "off" nil)
1522 (const :tag "on: after stars/bullet and before tags first" t)
1523 (const :tag "reversed: true line boundary first" reversed)
1524 (cons :tag "Set C-a and C-e separately"
1525 (choice :tag "Special C-a"
1526 (const :tag "off" nil)
1527 (const :tag "on: after stars/bullet first" t)
1528 (const :tag "reversed: before stars/bullet first" reversed))
1529 (choice :tag "Special C-e"
1530 (const :tag "off" nil)
1531 (const :tag "on: before tags first" t)
1532 (const :tag "reversed: after tags first" reversed)))))
1533 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1535 (defcustom org-special-ctrl-k nil
1536 "Non-nil means `C-k' will behave specially in headlines.
1537 When nil, `C-k' will call the default `kill-line' command.
1538 When t, the following will happen while the cursor is in the headline:
1540 - When the cursor is at the beginning of a headline, kill the entire
1541 line and possible the folded subtree below the line.
1542 - When in the middle of the headline text, kill the headline up to the tags.
1543 - When after the headline text, kill the tags."
1544 :group 'org-edit-structure
1545 :type 'boolean)
1547 (defcustom org-ctrl-k-protect-subtree nil
1548 "Non-nil means, do not delete a hidden subtree with C-k.
1549 When set to the symbol `error', simply throw an error when C-k is
1550 used to kill (part-of) a headline that has hidden text behind it.
1551 Any other non-nil value will result in a query to the user, if it is
1552 OK to kill that hidden subtree. When nil, kill without remorse."
1553 :group 'org-edit-structure
1554 :version "24.1"
1555 :type '(choice
1556 (const :tag "Do not protect hidden subtrees" nil)
1557 (const :tag "Protect hidden subtrees with a security query" t)
1558 (const :tag "Never kill a hidden subtree with C-k" error)))
1560 (defcustom org-special-ctrl-o t
1561 "Non-nil means, make `C-o' insert a row in tables."
1562 :group 'org-edit-structure
1563 :type 'boolean)
1565 (defcustom org-catch-invisible-edits nil
1566 "Check if in invisible region before inserting or deleting a character.
1567 Valid values are:
1569 nil Do not check, so just do invisible edits.
1570 error Throw an error and do nothing.
1571 show Make point visible, and do the requested edit.
1572 show-and-error Make point visible, then throw an error and abort the edit.
1573 smart Make point visible, and do insertion/deletion if it is
1574 adjacent to visible text and the change feels predictable.
1575 Never delete a previously invisible character or add in the
1576 middle or right after an invisible region. Basically, this
1577 allows insertion and backward-delete right before ellipses.
1578 FIXME: maybe in this case we should not even show?"
1579 :group 'org-edit-structure
1580 :version "24.1"
1581 :type '(choice
1582 (const :tag "Do not check" nil)
1583 (const :tag "Throw error when trying to edit" error)
1584 (const :tag "Unhide, but do not do the edit" show-and-error)
1585 (const :tag "Show invisible part and do the edit" show)
1586 (const :tag "Be smart and do the right thing" smart)))
1588 (defcustom org-yank-folded-subtrees t
1589 "Non-nil means when yanking subtrees, fold them.
1590 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1591 it starts with a heading and all other headings in it are either children
1592 or siblings, then fold all the subtrees. However, do this only if no
1593 text after the yank would be swallowed into a folded tree by this action."
1594 :group 'org-edit-structure
1595 :type 'boolean)
1597 (defcustom org-yank-adjusted-subtrees nil
1598 "Non-nil means when yanking subtrees, adjust the level.
1599 With this setting, `org-paste-subtree' is used to insert the subtree, see
1600 this function for details."
1601 :group 'org-edit-structure
1602 :type 'boolean)
1604 (defcustom org-M-RET-may-split-line '((default . t))
1605 "Non-nil means M-RET will split the line at the cursor position.
1606 When nil, it will go to the end of the line before making a
1607 new line.
1608 You may also set this option in a different way for different
1609 contexts. Valid contexts are:
1611 headline when creating a new headline
1612 item when creating a new item
1613 table in a table field
1614 default the value to be used for all contexts not explicitly
1615 customized"
1616 :group 'org-structure
1617 :group 'org-table
1618 :type '(choice
1619 (const :tag "Always" t)
1620 (const :tag "Never" nil)
1621 (repeat :greedy t :tag "Individual contexts"
1622 (cons
1623 (choice :tag "Context"
1624 (const headline)
1625 (const item)
1626 (const table)
1627 (const default))
1628 (boolean)))))
1631 (defcustom org-insert-heading-respect-content nil
1632 "Non-nil means insert new headings after the current subtree.
1633 \\<org-mode-map>
1634 When nil, the new heading is created directly after the current line.
1635 The commands `\\[org-insert-heading-respect-content]' and \
1636 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1637 for the duration of the command."
1638 :group 'org-structure
1639 :type 'boolean)
1641 (defcustom org-blank-before-new-entry '((heading . auto)
1642 (plain-list-item . auto))
1643 "Should `org-insert-heading' leave a blank line before new heading/item?
1644 The value is an alist, with `heading' and `plain-list-item' as CAR,
1645 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1646 which case Org will look at the surrounding headings/items and try to
1647 make an intelligent decision whether to insert a blank line or not."
1648 :group 'org-edit-structure
1649 :type '(list
1650 (cons (const heading)
1651 (choice (const :tag "Never" nil)
1652 (const :tag "Always" t)
1653 (const :tag "Auto" auto)))
1654 (cons (const plain-list-item)
1655 (choice (const :tag "Never" nil)
1656 (const :tag "Always" t)
1657 (const :tag "Auto" auto)))))
1659 (defcustom org-insert-heading-hook nil
1660 "Hook being run after inserting a new heading."
1661 :group 'org-edit-structure
1662 :type 'hook)
1664 (defcustom org-enable-fixed-width-editor t
1665 "Non-nil means lines starting with \":\" are treated as fixed-width.
1666 This currently only means they are never auto-wrapped.
1667 When nil, such lines will be treated like ordinary lines."
1668 :group 'org-edit-structure
1669 :type 'boolean)
1671 (defgroup org-sparse-trees nil
1672 "Options concerning sparse trees in Org mode."
1673 :tag "Org Sparse Trees"
1674 :group 'org-structure)
1676 (defcustom org-highlight-sparse-tree-matches t
1677 "Non-nil means highlight all matches that define a sparse tree.
1678 The highlights will automatically disappear the next time the buffer is
1679 changed by an edit command."
1680 :group 'org-sparse-trees
1681 :type 'boolean)
1683 (defcustom org-remove-highlights-with-change t
1684 "Non-nil means any change to the buffer will remove temporary highlights.
1685 \\<org-mode-map>\
1686 Such highlights are created by `org-occur' and `org-clock-display'.
1687 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1688 to get rid of the highlights.
1689 The highlights created by `org-toggle-latex-fragment' always need
1690 `\\[org-toggle-latex-fragment]' to be removed."
1691 :group 'org-sparse-trees
1692 :group 'org-time
1693 :type 'boolean)
1695 (defcustom org-occur-case-fold-search t
1696 "Non-nil means `org-occur' should be case-insensitive.
1697 If set to `smart' the search will be case-insensitive only if it
1698 doesn't specify any upper case character."
1699 :group 'org-sparse-trees
1700 :version "26.1"
1701 :type '(choice
1702 (const :tag "Case-sensitive" nil)
1703 (const :tag "Case-insensitive" t)
1704 (const :tag "Case-insensitive for lower case searches only" smart)))
1706 (defcustom org-occur-hook '(org-first-headline-recenter)
1707 "Hook that is run after `org-occur' has constructed a sparse tree.
1708 This can be used to recenter the window to show as much of the structure
1709 as possible."
1710 :group 'org-sparse-trees
1711 :type 'hook)
1713 (defgroup org-table nil
1714 "Options concerning tables in Org mode."
1715 :tag "Org Table"
1716 :group 'org)
1718 (defcustom org-self-insert-cluster-for-undo nil
1719 "Non-nil means cluster self-insert commands for undo when possible.
1720 If this is set, then, like in the Emacs command loop, 20 consecutive
1721 characters will be undone together.
1722 This is configurable, because there is some impact on typing performance."
1723 :group 'org-table
1724 :type 'boolean)
1726 (defcustom org-table-tab-recognizes-table.el t
1727 "Non-nil means TAB will automatically notice a table.el table.
1728 When it sees such a table, it moves point into it and - if necessary -
1729 calls `table-recognize-table'."
1730 :group 'org-table-editing
1731 :type 'boolean)
1733 (defgroup org-link nil
1734 "Options concerning links in Org mode."
1735 :tag "Org Link"
1736 :group 'org)
1738 (defvar-local org-link-abbrev-alist-local nil
1739 "Buffer-local version of `org-link-abbrev-alist', which see.
1740 The value of this is taken from the #+LINK lines.")
1742 (defcustom org-link-parameters
1743 '(("doi" :follow org--open-doi-link)
1744 ("elisp" :follow org--open-elisp-link)
1745 ("file" :complete org-file-complete-link)
1746 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1747 ("help" :follow org--open-help-link)
1748 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1749 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1750 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1751 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1752 ("shell" :follow org--open-shell-link))
1753 "An alist of properties that defines all the links in Org mode.
1754 The key in each association is a string of the link type.
1755 Subsequent optional elements make up a p-list of link properties.
1757 :follow - A function that takes the link path as an argument.
1759 :export - A function that takes the link path, description and
1760 export-backend as arguments.
1762 :store - A function responsible for storing the link. See the
1763 function `org-store-link-functions'.
1765 :complete - A function that inserts a link with completion. The
1766 function takes one optional prefix arg.
1768 :face - A face for the link, or a function that returns a face.
1769 The function takes one argument which is the link path. The
1770 default face is `org-link'.
1772 :mouse-face - The mouse-face. The default is `highlight'.
1774 :display - `full' will not fold the link in descriptive
1775 display. Default is `org-link'.
1777 :help-echo - A string or function that takes (window object position)
1778 as arguments and returns a string.
1780 :keymap - A keymap that is active on the link. The default is
1781 `org-mouse-map'.
1783 :htmlize-link - A function for the htmlize-link. Defaults
1784 to (list :uri \"type:path\")
1786 :activate-func - A function to run at the end of font-lock
1787 activation. The function must accept (link-start link-end path bracketp)
1788 as arguments."
1789 :group 'org-link
1790 :type '(alist :tag "Link display parameters"
1791 :value-type plist)
1792 :version "26.1"
1793 :package-version '(Org . "9.1"))
1795 (defun org-link-get-parameter (type key)
1796 "Get TYPE link property for KEY.
1797 TYPE is a string and KEY is a plist keyword."
1798 (plist-get
1799 (cdr (assoc type org-link-parameters))
1800 key))
1802 (defun org-link-set-parameters (type &rest parameters)
1803 "Set link TYPE properties to PARAMETERS.
1804 PARAMETERS should be :key val pairs."
1805 (let ((data (assoc type org-link-parameters)))
1806 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1807 (push (cons type parameters) org-link-parameters)
1808 (org-make-link-regexps)
1809 (org-element-update-syntax))))
1811 (defun org-link-types ()
1812 "Return a list of known link types."
1813 (mapcar #'car org-link-parameters))
1815 (defcustom org-link-abbrev-alist nil
1816 "Alist of link abbreviations.
1817 The car of each element is a string, to be replaced at the start of a link.
1818 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1819 links in Org buffers can have an optional tag after a double colon, e.g.,
1821 [[linkkey:tag][description]]
1823 The `linkkey' must be a single word, starting with a letter, followed
1824 by letters, numbers, `-' or `_'.
1826 If REPLACE is a string, the tag will simply be appended to create the link.
1827 If the string contains \"%s\", the tag will be inserted there. If the string
1828 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1829 at that point (see the function `url-hexify-string'). If the string contains
1830 the specifier \"%(my-function)\", then the custom function `my-function' will
1831 be invoked: this function takes the tag as its only argument and must return
1832 a string.
1834 REPLACE may also be a function that will be called with the tag as the
1835 only argument to create the link, which should be returned as a string.
1837 See the manual for examples."
1838 :group 'org-link
1839 :type '(repeat
1840 (cons
1841 (string :tag "Protocol")
1842 (choice
1843 (string :tag "Format")
1844 (function)))))
1846 (defcustom org-descriptive-links t
1847 "Non-nil means Org will display descriptive links.
1848 E.g. [[https://orgmode.org][Org website]] will be displayed as
1849 \"Org Website\", hiding the link itself and just displaying its
1850 description. When set to nil, Org will display the full links
1851 literally.
1853 You can interactively set the value of this variable by calling
1854 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1855 :group 'org-link
1856 :type 'boolean)
1858 (defcustom org-link-file-path-type 'adaptive
1859 "How the path name in file links should be stored.
1860 Valid values are:
1862 relative Relative to the current directory, i.e. the directory of the file
1863 into which the link is being inserted.
1864 absolute Absolute path, if possible with ~ for home directory.
1865 noabbrev Absolute path, no abbreviation of home directory.
1866 adaptive Use relative path for files in the current directory and sub-
1867 directories of it. For other files, use an absolute path."
1868 :group 'org-link
1869 :type '(choice
1870 (const relative)
1871 (const absolute)
1872 (const noabbrev)
1873 (const adaptive)))
1875 (defvaralias 'org-activate-links 'org-highlight-links)
1876 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1877 "Types of links that should be highlighted in Org files.
1879 This is a list of symbols, each one of them leading to the
1880 highlighting of a certain link type.
1882 You can still open links that are not highlighted.
1884 In principle, it does not hurt to turn on highlighting for all
1885 link types. There may be a small gain when turning off unused
1886 link types. The types are:
1888 bracket The recommended [[link][description]] or [[link]] links with hiding.
1889 angle Links in angular brackets that may contain whitespace like
1890 <bbdb:Carsten Dominik>.
1891 plain Plain links in normal text, no whitespace, like http://google.com.
1892 radio Text that is matched by a radio target, see manual for details.
1893 tag Tag settings in a headline (link to tag search).
1894 date Time stamps (link to calendar).
1895 footnote Footnote labels.
1897 If you set this variable during an Emacs session, use `org-mode-restart'
1898 in the Org buffer so that the change takes effect."
1899 :group 'org-link
1900 :group 'org-appearance
1901 :type '(set :greedy t
1902 (const :tag "Double bracket links" bracket)
1903 (const :tag "Angular bracket links" angle)
1904 (const :tag "Plain text links" plain)
1905 (const :tag "Radio target matches" radio)
1906 (const :tag "Tags" tag)
1907 (const :tag "Timestamps" date)
1908 (const :tag "Footnotes" footnote)))
1910 (defcustom org-make-link-description-function nil
1911 "Function to use for generating link descriptions from links.
1912 This function must take two parameters: the first one is the
1913 link, the second one is the description generated by
1914 `org-insert-link'. The function should return the description to
1915 use."
1916 :group 'org-link
1917 :type '(choice (const nil) (function)))
1919 (defgroup org-link-store nil
1920 "Options concerning storing links in Org mode."
1921 :tag "Org Store Link"
1922 :group 'org-link)
1924 (defcustom org-url-hexify-p t
1925 "When non-nil, hexify URL when creating a link."
1926 :type 'boolean
1927 :version "24.3"
1928 :group 'org-link-store)
1930 (defcustom org-email-link-description-format "Email %c: %.30s"
1931 "Format of the description part of a link to an email or usenet message.
1932 The following %-escapes will be replaced by corresponding information:
1934 %F full \"From\" field
1935 %f name, taken from \"From\" field, address if no name
1936 %T full \"To\" field
1937 %t first name in \"To\" field, address if no name
1938 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1939 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1940 %s subject
1941 %d date
1942 %m message-id.
1944 You may use normal field width specification between the % and the letter.
1945 This is for example useful to limit the length of the subject.
1947 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1948 :group 'org-link-store
1949 :type 'string)
1951 (defcustom org-from-is-user-regexp
1952 (let (r1 r2)
1953 (when (and user-mail-address (not (string= user-mail-address "")))
1954 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1955 (when (and user-full-name (not (string= user-full-name "")))
1956 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1957 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1958 "Regexp matched against the \"From:\" header of an email or usenet message.
1959 It should match if the message is from the user him/herself."
1960 :group 'org-link-store
1961 :type 'regexp)
1963 (defcustom org-context-in-file-links t
1964 "Non-nil means file links from `org-store-link' contain context.
1965 \\<org-mode-map>
1966 A search string will be added to the file name with :: as separator
1967 and used to find the context when the link is activated by the command
1968 `org-open-at-point'. When this option is t, the entire active region
1969 will be placed in the search string of the file link. If set to a
1970 positive integer, only the first n lines of context will be stored.
1972 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1973 \\[org-store-link]')
1974 negates this setting for the duration of the command."
1975 :group 'org-link-store
1976 :type '(choice boolean integer))
1978 (defcustom org-keep-stored-link-after-insertion nil
1979 "Non-nil means keep link in list for entire session.
1980 \\<org-mode-map>
1981 The command `org-store-link' adds a link pointing to the current
1982 location to an internal list. These links accumulate during a session.
1983 The command `org-insert-link' can be used to insert links into any
1984 Org file (offering completion for all stored links).
1986 When this option is nil, every link which has been inserted once using
1987 `\\[org-insert-link]' will be removed from the list, to make completing the \
1988 unused
1989 links more efficient."
1990 :group 'org-link-store
1991 :type 'boolean)
1993 (defgroup org-link-follow nil
1994 "Options concerning following links in Org mode."
1995 :tag "Org Follow Link"
1996 :group 'org-link)
1998 (defcustom org-link-translation-function nil
1999 "Function to translate links with different syntax to Org syntax.
2000 This can be used to translate links created for example by the Planner
2001 or emacs-wiki packages to Org syntax.
2002 The function must accept two parameters, a TYPE containing the link
2003 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2004 which is everything after the link protocol. It should return a cons
2005 with possibly modified values of type and path.
2006 Org contains a function for this, so if you set this variable to
2007 `org-translate-link-from-planner', you should be able follow many
2008 links created by planner."
2009 :group 'org-link-follow
2010 :type '(choice (const nil) (function)))
2012 (defcustom org-follow-link-hook nil
2013 "Hook that is run after a link has been followed."
2014 :group 'org-link-follow
2015 :type 'hook)
2017 (defcustom org-tab-follows-link nil
2018 "Non-nil means on links TAB will follow the link.
2019 Needs to be set before org.el is loaded.
2020 This really should not be used, it does not make sense, and the
2021 implementation is bad."
2022 :group 'org-link-follow
2023 :type 'boolean)
2025 (defcustom org-return-follows-link nil
2026 "Non-nil means on links RET will follow the link.
2027 In tables, the special behavior of RET has precedence."
2028 :group 'org-link-follow
2029 :type 'boolean)
2031 (defcustom org-mouse-1-follows-link
2032 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2033 "Non-nil means mouse-1 on a link will follow the link.
2034 A longer mouse click will still set point. Needs to be set
2035 before org.el is loaded."
2036 :group 'org-link-follow
2037 :version "26.1"
2038 :package-version '(Org . "8.3")
2039 :type '(choice
2040 (const :tag "A double click follows the link" double)
2041 (const :tag "Unconditionally follow the link with mouse-1" t)
2042 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2044 (defcustom org-mark-ring-length 4
2045 "Number of different positions to be recorded in the ring.
2046 Changing this requires a restart of Emacs to work correctly."
2047 :group 'org-link-follow
2048 :type 'integer)
2050 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2051 "Non-nil means internal fuzzy links can only match headlines.
2053 When nil, the a fuzzy link may point to a target or a named
2054 construct in the document. When set to the special value
2055 `query-to-create', offer to create a new headline when none
2056 matched.
2058 Spaces and statistics cookies are ignored during heading searches."
2059 :group 'org-link-follow
2060 :version "24.1"
2061 :type '(choice
2062 (const :tag "Use fuzzy text search" nil)
2063 (const :tag "Match only exact headline" t)
2064 (const :tag "Match exact headline or query to create it"
2065 query-to-create))
2066 :safe #'symbolp)
2068 (defcustom org-link-frame-setup
2069 '((vm . vm-visit-folder-other-frame)
2070 (vm-imap . vm-visit-imap-folder-other-frame)
2071 (gnus . org-gnus-no-new-news)
2072 (file . find-file-other-window)
2073 (wl . wl-other-frame))
2074 "Setup the frame configuration for following links.
2075 When following a link with Emacs, it may often be useful to display
2076 this link in another window or frame. This variable can be used to
2077 set this up for the different types of links.
2078 For VM, use any of
2079 `vm-visit-folder'
2080 `vm-visit-folder-other-window'
2081 `vm-visit-folder-other-frame'
2082 For Gnus, use any of
2083 `gnus'
2084 `gnus-other-frame'
2085 `org-gnus-no-new-news'
2086 For FILE, use any of
2087 `find-file'
2088 `find-file-other-window'
2089 `find-file-other-frame'
2090 For Wanderlust use any of
2091 `wl'
2092 `wl-other-frame'
2093 For the calendar, use the variable `calendar-setup'.
2094 For BBDB, it is currently only possible to display the matches in
2095 another window."
2096 :group 'org-link-follow
2097 :type '(list
2098 (cons (const vm)
2099 (choice
2100 (const vm-visit-folder)
2101 (const vm-visit-folder-other-window)
2102 (const vm-visit-folder-other-frame)))
2103 (cons (const vm-imap)
2104 (choice
2105 (const vm-visit-imap-folder)
2106 (const vm-visit-imap-folder-other-window)
2107 (const vm-visit-imap-folder-other-frame)))
2108 (cons (const gnus)
2109 (choice
2110 (const gnus)
2111 (const gnus-other-frame)
2112 (const org-gnus-no-new-news)))
2113 (cons (const file)
2114 (choice
2115 (const find-file)
2116 (const find-file-other-window)
2117 (const find-file-other-frame)))
2118 (cons (const wl)
2119 (choice
2120 (const wl)
2121 (const wl-other-frame)))))
2123 (defcustom org-display-internal-link-with-indirect-buffer nil
2124 "Non-nil means use indirect buffer to display infile links.
2125 Activating internal links (from one location in a file to another location
2126 in the same file) normally just jumps to the location. When the link is
2127 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2128 is displayed in
2129 another window. When this option is set, the other window actually displays
2130 an indirect buffer clone of the current buffer, to avoid any visibility
2131 changes to the current buffer."
2132 :group 'org-link-follow
2133 :type 'boolean)
2135 (defcustom org-open-non-existing-files nil
2136 "Non-nil means `org-open-file' will open non-existing files.
2137 When nil, an error will be generated.
2138 This variable applies only to external applications because they
2139 might choke on non-existing files. If the link is to a file that
2140 will be opened in Emacs, the variable is ignored."
2141 :group 'org-link-follow
2142 :type 'boolean)
2144 (defcustom org-open-directory-means-index-dot-org nil
2145 "Non-nil means a link to a directory really means to index.org.
2146 When nil, following a directory link will run dired or open a finder/explorer
2147 window on that directory."
2148 :group 'org-link-follow
2149 :type 'boolean)
2151 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2152 "Non-nil means ask for confirmation before executing shell links.
2153 Shell links can be dangerous: just think about a link
2155 [[shell:rm -rf ~/*][Google Search]]
2157 This link would show up in your Org document as \"Google Search\",
2158 but really it would remove your entire home directory.
2159 Therefore we advise against setting this variable to nil.
2160 Just change it to `y-or-n-p' if you want to confirm with a
2161 single keystroke rather than having to type \"yes\"."
2162 :group 'org-link-follow
2163 :type '(choice
2164 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2165 (const :tag "with y-or-n (faster)" y-or-n-p)
2166 (const :tag "no confirmation (dangerous)" nil)))
2167 (put 'org-confirm-shell-link-function
2168 'safe-local-variable
2169 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2171 (defcustom org-confirm-shell-link-not-regexp ""
2172 "A regexp to skip confirmation for shell links."
2173 :group 'org-link-follow
2174 :version "24.1"
2175 :type 'regexp)
2177 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2178 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2179 Elisp links can be dangerous: just think about a link
2181 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2183 This link would show up in your Org document as \"Google Search\",
2184 but really it would remove your entire home directory.
2185 Therefore we advise against setting this variable to nil.
2186 Just change it to `y-or-n-p' if you want to confirm with a
2187 single keystroke rather than having to type \"yes\"."
2188 :group 'org-link-follow
2189 :type '(choice
2190 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2191 (const :tag "with y-or-n (faster)" y-or-n-p)
2192 (const :tag "no confirmation (dangerous)" nil)))
2193 (put 'org-confirm-shell-link-function
2194 'safe-local-variable
2195 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2197 (defcustom org-confirm-elisp-link-not-regexp ""
2198 "A regexp to skip confirmation for Elisp links."
2199 :group 'org-link-follow
2200 :version "24.1"
2201 :type 'regexp)
2203 (defconst org-file-apps-defaults-gnu
2204 '((remote . emacs)
2205 (system . mailcap)
2206 (t . mailcap))
2207 "Default file applications on a UNIX or GNU/Linux system.
2208 See `org-file-apps'.")
2210 (defconst org-file-apps-defaults-macosx
2211 '((remote . emacs)
2212 (system . "open %s")
2213 ("ps.gz" . "gv %s")
2214 ("eps.gz" . "gv %s")
2215 ("dvi" . "xdvi %s")
2216 ("fig" . "xfig %s")
2217 (t . "open %s"))
2218 "Default file applications on a macOS system.
2219 The system \"open\" is known as a default, but we use X11 applications
2220 for some files for which the OS does not have a good default.
2221 See `org-file-apps'.")
2223 (defconst org-file-apps-defaults-windowsnt
2224 (list '(remote . emacs)
2225 (cons 'system (lambda (file _path)
2226 (with-no-warnings (w32-shell-execute "open" file))))
2227 (cons t (lambda (file _path)
2228 (with-no-warnings (w32-shell-execute "open" file)))))
2229 "Default file applications on a Windows NT system.
2230 The system \"open\" is used for most files.
2231 See `org-file-apps'.")
2233 (defcustom org-file-apps
2234 '((auto-mode . emacs)
2235 ("\\.mm\\'" . default)
2236 ("\\.x?html?\\'" . default)
2237 ("\\.pdf\\'" . default))
2238 "External applications for opening `file:path' items in a document.
2239 \\<org-mode-map>\
2241 Org mode uses system defaults for different file types, but
2242 you can use this variable to set the application for a given file
2243 extension. The entries in this list are cons cells where the car identifies
2244 files and the cdr the corresponding command.
2246 Possible values for the file identifier are:
2248 \"string\" A string as a file identifier can be interpreted in different
2249 ways, depending on its contents:
2251 - Alphanumeric characters only:
2252 Match links with this file extension.
2253 Example: (\"pdf\" . \"evince %s\")
2254 to open PDFs with evince.
2256 - Regular expression: Match links where the
2257 filename matches the regexp. If you want to
2258 use groups here, use shy groups.
2260 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2261 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2262 to open *.html and *.xhtml with firefox.
2264 - Regular expression which contains (non-shy) groups:
2265 Match links where the whole link, including \"::\", and
2266 anything after that, matches the regexp.
2267 In a custom command string, %1, %2, etc. are replaced with
2268 the parts of the link that were matched by the groups.
2269 For backwards compatibility, if a command string is given
2270 that does not use any of the group matches, this case is
2271 handled identically to the second one (i.e. match against
2272 file name only).
2273 In a custom function, you can access the group matches with
2274 (match-string n link).
2276 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2277 \"evince -p %1 %s\")
2278 to open [[file:document.pdf::5]] with evince at page 5.
2280 `directory' Matches a directory
2281 `remote' Matches a remote file, accessible through tramp or efs.
2282 Remote files most likely should be visited through Emacs
2283 because external applications cannot handle such paths.
2284 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2285 so all files Emacs knows how to handle. Using this with
2286 command `emacs' will open most files in Emacs. Beware that this
2287 will also open html files inside Emacs, unless you add
2288 (\"html\" . default) to the list as well.
2289 `system' The system command to open files, like `open' on Windows
2290 and macOS, and mailcap under GNU/Linux. This is the command
2291 that will be selected if you call `org-open-at-point' with a
2292 double prefix argument (`\\[universal-argument] \
2293 \\[universal-argument] \\[org-open-at-point]').
2294 t Default for files not matched by any of the other options.
2296 Possible values for the command are:
2298 `emacs' The file will be visited by the current Emacs process.
2299 `default' Use the default application for this file type, which is the
2300 association for t in the list, most likely in the system-specific
2301 part. This can be used to overrule an unwanted setting in the
2302 system-specific variable.
2303 `system' Use the system command for opening files, like \"open\".
2304 This command is specified by the entry whose car is `system'.
2305 Most likely, the system-specific version of this variable
2306 does define this command, but you can overrule/replace it
2307 here.
2308 `mailcap' Use command specified in the mailcaps.
2309 string A command to be executed by a shell; %s will be replaced
2310 by the path to the file.
2311 function A Lisp function, which will be called with two arguments:
2312 the file path and the original link string, without the
2313 \"file:\" prefix.
2315 For more examples, see the system specific constants
2316 `org-file-apps-defaults-macosx'
2317 `org-file-apps-defaults-windowsnt'
2318 `org-file-apps-defaults-gnu'."
2319 :group 'org-link-follow
2320 :type '(repeat
2321 (cons (choice :value ""
2322 (string :tag "Extension")
2323 (const :tag "System command to open files" system)
2324 (const :tag "Default for unrecognized files" t)
2325 (const :tag "Remote file" remote)
2326 (const :tag "Links to a directory" directory)
2327 (const :tag "Any files that have Emacs modes"
2328 auto-mode))
2329 (choice :value ""
2330 (const :tag "Visit with Emacs" emacs)
2331 (const :tag "Use default" default)
2332 (const :tag "Use the system command" system)
2333 (string :tag "Command")
2334 (function :tag "Function")))))
2336 (defcustom org-doi-server-url "http://dx.doi.org/"
2337 "The URL of the DOI server."
2338 :type 'string
2339 :version "24.3"
2340 :group 'org-link-follow)
2342 (defgroup org-refile nil
2343 "Options concerning refiling entries in Org mode."
2344 :tag "Org Refile"
2345 :group 'org)
2347 (defcustom org-directory "~/org"
2348 "Directory with Org files.
2349 This is just a default location to look for Org files. There is no need
2350 at all to put your files into this directory. It is used in the
2351 following situations:
2353 1. When a capture template specifies a target file that is not an
2354 absolute path. The path will then be interpreted relative to
2355 `org-directory'
2356 2. When the value of variable `org-agenda-files' is a single file, any
2357 relative paths in this file will be taken as relative to
2358 `org-directory'."
2359 :group 'org-refile
2360 :group 'org-capture
2361 :type 'directory)
2363 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2364 "Default target for storing notes.
2365 Used as a fall back file for org-capture.el, for templates that
2366 do not specify a target file."
2367 :group 'org-refile
2368 :group 'org-capture
2369 :type 'file)
2371 (defcustom org-reverse-note-order nil
2372 "Non-nil means store new notes at the beginning of a file or entry.
2373 When nil, new notes will be filed to the end of a file or entry.
2374 This can also be a list with cons cells of regular expressions that
2375 are matched against file names, and values."
2376 :group 'org-capture
2377 :group 'org-refile
2378 :type '(choice
2379 (const :tag "Reverse always" t)
2380 (const :tag "Reverse never" nil)
2381 (repeat :tag "By file name regexp"
2382 (cons regexp boolean))))
2384 (defcustom org-log-refile nil
2385 "Information to record when a task is refiled.
2387 Possible values are:
2389 nil Don't add anything
2390 time Add a time stamp to the task
2391 note Prompt for a note and add it with template `org-log-note-headings'
2393 This option can also be set with on a per-file-basis with
2395 #+STARTUP: nologrefile
2396 #+STARTUP: logrefile
2397 #+STARTUP: lognoterefile
2399 You can have local logging settings for a subtree by setting the LOGGING
2400 property to one or more of these keywords.
2402 When bulk-refiling from the agenda, the value `note' is forbidden and
2403 will temporarily be changed to `time'."
2404 :group 'org-refile
2405 :group 'org-progress
2406 :version "24.1"
2407 :type '(choice
2408 (const :tag "No logging" nil)
2409 (const :tag "Record timestamp" time)
2410 (const :tag "Record timestamp with note." note)))
2412 (defcustom org-refile-targets nil
2413 "Targets for refiling entries with `\\[org-refile]'.
2414 This is a list of cons cells. Each cell contains:
2415 - a specification of the files to be considered, either a list of files,
2416 or a symbol whose function or variable value will be used to retrieve
2417 a file name or a list of file names. If you use `org-agenda-files' for
2418 that, all agenda files will be scanned for targets. Nil means consider
2419 headings in the current buffer.
2420 - A specification of how to find candidate refile targets. This may be
2421 any of:
2422 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2423 This tag has to be present in all target headlines, inheritance will
2424 not be considered.
2425 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2426 todo keyword.
2427 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2428 headlines that are refiling targets.
2429 - a cons cell (:level . N). Any headline of level N is considered a target.
2430 Note that, when `org-odd-levels-only' is set, level corresponds to
2431 order in hierarchy, not to the number of stars.
2432 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2433 Note that, when `org-odd-levels-only' is set, level corresponds to
2434 order in hierarchy, not to the number of stars.
2436 Each element of this list generates a set of possible targets.
2437 The union of these sets is presented (with completion) to
2438 the user by `org-refile'.
2440 You can set the variable `org-refile-target-verify-function' to a function
2441 to verify each headline found by the simple criteria above.
2443 When this variable is nil, all top-level headlines in the current buffer
2444 are used, equivalent to the value `((nil . (:level . 1))'."
2445 :group 'org-refile
2446 :type '(repeat
2447 (cons
2448 (choice :value org-agenda-files
2449 (const :tag "All agenda files" org-agenda-files)
2450 (const :tag "Current buffer" nil)
2451 (function) (variable) (file))
2452 (choice :tag "Identify target headline by"
2453 (cons :tag "Specific tag" (const :value :tag) (string))
2454 (cons :tag "TODO keyword" (const :value :todo) (string))
2455 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2456 (cons :tag "Level number" (const :value :level) (integer))
2457 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2459 (defcustom org-refile-target-verify-function nil
2460 "Function to verify if the headline at point should be a refile target.
2461 The function will be called without arguments, with point at the
2462 beginning of the headline. It should return t and leave point
2463 where it is if the headline is a valid target for refiling.
2465 If the target should not be selected, the function must return nil.
2466 In addition to this, it may move point to a place from where the search
2467 should be continued. For example, the function may decide that the entire
2468 subtree of the current entry should be excluded and move point to the end
2469 of the subtree."
2470 :group 'org-refile
2471 :type '(choice
2472 (const nil)
2473 (function)))
2475 (defcustom org-refile-use-cache nil
2476 "Non-nil means cache refile targets to speed up the process.
2477 \\<org-mode-map>\
2478 The cache for a particular file will be updated automatically when
2479 the buffer has been killed, or when any of the marker used for flagging
2480 refile targets no longer points at a live buffer.
2481 If you have added new entries to a buffer that might themselves be targets,
2482 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2483 if you find that easier, \
2484 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2485 \\[org-refile]'."
2486 :group 'org-refile
2487 :version "24.1"
2488 :type 'boolean)
2490 (defcustom org-refile-use-outline-path nil
2491 "Non-nil means provide refile targets as paths.
2492 So a level 3 headline will be available as level1/level2/level3.
2494 When the value is `file', also include the file name (without directory)
2495 into the path. In this case, you can also stop the completion after
2496 the file name, to get entries inserted as top level in the file.
2498 When `full-file-path', include the full file path.
2500 When `buffer-name', use the buffer name."
2501 :group 'org-refile
2502 :type '(choice
2503 (const :tag "Not" nil)
2504 (const :tag "Yes" t)
2505 (const :tag "Start with file name" file)
2506 (const :tag "Start with full file path" full-file-path)
2507 (const :tag "Start with buffer name" buffer-name)))
2509 (defcustom org-outline-path-complete-in-steps t
2510 "Non-nil means complete the outline path in hierarchical steps.
2511 When Org uses the refile interface to select an outline path (see
2512 `org-refile-use-outline-path'), the completion of the path can be
2513 done in a single go, or it can be done in steps down the headline
2514 hierarchy. Going in steps is probably the best if you do not use
2515 a special completion package like `ido' or `icicles'. However,
2516 when using these packages, going in one step can be very fast,
2517 while still showing the whole path to the entry."
2518 :group 'org-refile
2519 :type 'boolean)
2521 (defcustom org-refile-allow-creating-parent-nodes nil
2522 "Non-nil means allow the creation of new nodes as refile targets.
2523 New nodes are then created by adding \"/new node name\" to the completion
2524 of an existing node. When the value of this variable is `confirm',
2525 new node creation must be confirmed by the user (recommended).
2526 When nil, the completion must match an existing entry.
2528 Note that, if the new heading is not seen by the criteria
2529 listed in `org-refile-targets', multiple instances of the same
2530 heading would be created by trying again to file under the new
2531 heading."
2532 :group 'org-refile
2533 :type '(choice
2534 (const :tag "Never" nil)
2535 (const :tag "Always" t)
2536 (const :tag "Prompt for confirmation" confirm)))
2538 (defcustom org-refile-active-region-within-subtree nil
2539 "Non-nil means also refile active region within a subtree.
2541 By default `org-refile' doesn't allow refiling regions if they
2542 don't contain a set of subtrees, but it might be convenient to
2543 do so sometimes: in that case, the first line of the region is
2544 converted to a headline before refiling."
2545 :group 'org-refile
2546 :version "24.1"
2547 :type 'boolean)
2549 (defgroup org-todo nil
2550 "Options concerning TODO items in Org mode."
2551 :tag "Org TODO"
2552 :group 'org)
2554 (defgroup org-progress nil
2555 "Options concerning Progress logging in Org mode."
2556 :tag "Org Progress"
2557 :group 'org-time)
2559 (defvar org-todo-interpretation-widgets
2560 '((:tag "Sequence (cycling hits every state)" sequence)
2561 (:tag "Type (cycling directly to DONE)" type))
2562 "The available interpretation symbols for customizing `org-todo-keywords'.
2563 Interested libraries should add to this list.")
2565 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2566 "List of TODO entry keyword sequences and their interpretation.
2567 \\<org-mode-map>This is a list of sequences.
2569 Each sequence starts with a symbol, either `sequence' or `type',
2570 indicating if the keywords should be interpreted as a sequence of
2571 action steps, or as different types of TODO items. The first
2572 keywords are states requiring action - these states will select a headline
2573 for inclusion into the global TODO list Org produces. If one of the
2574 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2575 signify that no further action is necessary. If \"|\" is not found,
2576 the last keyword is treated as the only DONE state of the sequence.
2578 The command `\\[org-todo]' cycles an entry through these states, and one
2579 additional state where no keyword is present. For details about this
2580 cycling, see the manual.
2582 TODO keywords and interpretation can also be set on a per-file basis with
2583 the special #+SEQ_TODO and #+TYP_TODO lines.
2585 Each keyword can optionally specify a character for fast state selection
2586 \(in combination with the variable `org-use-fast-todo-selection')
2587 and specifiers for state change logging, using the same syntax that
2588 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2589 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2590 indicates to record a time stamp each time this state is selected.
2592 Each keyword may also specify if a timestamp or a note should be
2593 recorded when entering or leaving the state, by adding additional
2594 characters in the parenthesis after the keyword. This looks like this:
2595 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2596 record only the time of the state change. With X and Y being either
2597 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2598 Y when leaving the state if and only if the *target* state does not
2599 define X. You may omit any of the fast-selection key or X or /Y,
2600 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2602 For backward compatibility, this variable may also be just a list
2603 of keywords. In this case the interpretation (sequence or type) will be
2604 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2605 :group 'org-todo
2606 :group 'org-keywords
2607 :type '(choice
2608 (repeat :tag "Old syntax, just keywords"
2609 (string :tag "Keyword"))
2610 (repeat :tag "New syntax"
2611 (cons
2612 (choice
2613 :tag "Interpretation"
2614 ;;Quick and dirty way to see
2615 ;;`org-todo-interpretations'. This takes the
2616 ;;place of item arguments
2617 :convert-widget
2618 (lambda (widget)
2619 (widget-put widget
2620 :args (mapcar
2621 (lambda (x)
2622 (widget-convert
2623 (cons 'const x)))
2624 org-todo-interpretation-widgets))
2625 widget))
2626 (repeat
2627 (string :tag "Keyword"))))))
2629 (defvar-local org-todo-keywords-1 nil
2630 "All TODO and DONE keywords active in a buffer.")
2631 (defvar org-todo-keywords-for-agenda nil)
2632 (defvar org-done-keywords-for-agenda nil)
2633 (defvar org-todo-keyword-alist-for-agenda nil)
2634 (defvar org-tag-alist-for-agenda nil
2635 "Alist of all tags from all agenda files.")
2636 (defvar org-tag-groups-alist-for-agenda nil
2637 "Alist of all groups tags from all current agenda files.")
2638 (defvar-local org-tag-groups-alist nil)
2639 (defvar org-agenda-contributing-files nil)
2640 (defvar-local org-current-tag-alist nil
2641 "Alist of all tag groups in current buffer.
2642 This variable takes into consideration `org-tag-alist',
2643 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2644 (defvar-local org-not-done-keywords nil)
2645 (defvar-local org-done-keywords nil)
2646 (defvar-local org-todo-heads nil)
2647 (defvar-local org-todo-sets nil)
2648 (defvar-local org-todo-log-states nil)
2649 (defvar-local org-todo-kwd-alist nil)
2650 (defvar-local org-todo-key-alist nil)
2651 (defvar-local org-todo-key-trigger nil)
2653 (defcustom org-todo-interpretation 'sequence
2654 "Controls how TODO keywords are interpreted.
2655 This variable is in principle obsolete and is only used for
2656 backward compatibility, if the interpretation of todo keywords is
2657 not given already in `org-todo-keywords'. See that variable for
2658 more information."
2659 :group 'org-todo
2660 :group 'org-keywords
2661 :type '(choice (const sequence)
2662 (const type)))
2664 (defcustom org-use-fast-todo-selection t
2665 "\\<org-mode-map>\
2666 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2667 This variable describes if and under what circumstances the cycling
2668 mechanism for TODO keywords will be replaced by a single-key, direct
2669 selection scheme.
2671 When nil, fast selection is never used.
2673 When the symbol `prefix', it will be used when `org-todo' is called
2674 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2675 in an Org buffer, and
2676 `\\[universal-argument] t' in an agenda buffer.
2678 When t, fast selection is used by default. In this case, the prefix
2679 argument forces cycling instead.
2681 In all cases, the special interface is only used if access keys have
2682 actually been assigned by the user, i.e. if keywords in the configuration
2683 are followed by a letter in parenthesis, like TODO(t)."
2684 :group 'org-todo
2685 :type '(choice
2686 (const :tag "Never" nil)
2687 (const :tag "By default" t)
2688 (const :tag "Only with C-u C-c C-t" prefix)))
2690 (defcustom org-provide-todo-statistics t
2691 "Non-nil means update todo statistics after insert and toggle.
2692 ALL-HEADLINES means update todo statistics by including headlines
2693 with no TODO keyword as well, counting them as not done.
2694 A list of TODO keywords means the same, but skip keywords that are
2695 not in this list.
2696 When set to a list of two lists, the first list contains keywords
2697 to consider as TODO keywords, the second list contains keywords
2698 to consider as DONE keywords.
2700 When this is set, todo statistics is updated in the parent of the
2701 current entry each time a todo state is changed."
2702 :group 'org-todo
2703 :type '(choice
2704 (const :tag "Yes, only for TODO entries" t)
2705 (const :tag "Yes, including all entries" all-headlines)
2706 (repeat :tag "Yes, for TODOs in this list"
2707 (string :tag "TODO keyword"))
2708 (list :tag "Yes, for TODOs and DONEs in these lists"
2709 (repeat (string :tag "TODO keyword"))
2710 (repeat (string :tag "DONE keyword")))
2711 (other :tag "No TODO statistics" nil)))
2713 (defcustom org-hierarchical-todo-statistics t
2714 "Non-nil means TODO statistics covers just direct children.
2715 When nil, all entries in the subtree are considered.
2716 This has only an effect if `org-provide-todo-statistics' is set.
2717 To set this to nil for only a single subtree, use a COOKIE_DATA
2718 property and include the word \"recursive\" into the value."
2719 :group 'org-todo
2720 :type 'boolean)
2722 (defcustom org-after-todo-state-change-hook nil
2723 "Hook which is run after the state of a TODO item was changed.
2724 The new state (a string with a TODO keyword, or nil) is available in the
2725 Lisp variable `org-state'."
2726 :group 'org-todo
2727 :type 'hook)
2729 (defvar org-blocker-hook nil
2730 "Hook for functions that are allowed to block a state change.
2732 Functions in this hook should not modify the buffer.
2733 Each function gets as its single argument a property list,
2734 see `org-trigger-hook' for more information about this list.
2736 If any of the functions in this hook returns nil, the state change
2737 is blocked.")
2739 (defvar org-trigger-hook nil
2740 "Hook for functions that are triggered by a state change.
2742 Each function gets as its single argument a property list with at
2743 least the following elements:
2745 (:type type-of-change :position pos-at-entry-start
2746 :from old-state :to new-state)
2748 Depending on the type, more properties may be present.
2750 This mechanism is currently implemented for:
2752 TODO state changes
2753 ------------------
2754 :type todo-state-change
2755 :from previous state (keyword as a string), or nil, or a symbol
2756 `todo' or `done', to indicate the general type of state.
2757 :to new state, like in :from")
2759 (defcustom org-enforce-todo-dependencies nil
2760 "Non-nil means undone TODO entries will block switching the parent to DONE.
2761 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2762 be blocked if any prior sibling is not yet done.
2763 Finally, if the parent is blocked because of ordered siblings of its own,
2764 the child will also be blocked."
2765 :set (lambda (var val)
2766 (set var val)
2767 (if val
2768 (add-hook 'org-blocker-hook
2769 'org-block-todo-from-children-or-siblings-or-parent)
2770 (remove-hook 'org-blocker-hook
2771 'org-block-todo-from-children-or-siblings-or-parent)))
2772 :group 'org-todo
2773 :type 'boolean)
2775 (defcustom org-enforce-todo-checkbox-dependencies nil
2776 "Non-nil means unchecked boxes will block switching the parent to DONE.
2777 When this is nil, checkboxes have no influence on switching TODO states.
2778 When non-nil, you first need to check off all check boxes before the TODO
2779 entry can be switched to DONE.
2780 This variable needs to be set before org.el is loaded, and you need to
2781 restart Emacs after a change to make the change effective. The only way
2782 to change is while Emacs is running is through the customize interface."
2783 :set (lambda (var val)
2784 (set var val)
2785 (if val
2786 (add-hook 'org-blocker-hook
2787 'org-block-todo-from-checkboxes)
2788 (remove-hook 'org-blocker-hook
2789 'org-block-todo-from-checkboxes)))
2790 :group 'org-todo
2791 :type 'boolean)
2793 (defcustom org-treat-insert-todo-heading-as-state-change nil
2794 "Non-nil means inserting a TODO heading is treated as state change.
2795 So when the command `\\[org-insert-todo-heading]' is used, state change
2796 logging will apply if appropriate. When nil, the new TODO item will
2797 be inserted directly, and no logging will take place."
2798 :group 'org-todo
2799 :type 'boolean)
2801 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2802 "Non-nil means switching TODO states with S-cursor counts as state change.
2803 This is the default behavior. However, setting this to nil allows a
2804 convenient way to select a TODO state and bypass any logging associated
2805 with that."
2806 :group 'org-todo
2807 :type 'boolean)
2809 (defcustom org-todo-state-tags-triggers nil
2810 "Tag changes that should be triggered by TODO state changes.
2811 This is a list. Each entry is
2813 (state-change (tag . flag) .......)
2815 State-change can be a string with a state, and empty string to indicate the
2816 state that has no TODO keyword, or it can be one of the symbols `todo'
2817 or `done', meaning any not-done or done state, respectively."
2818 :group 'org-todo
2819 :group 'org-tags
2820 :type '(repeat
2821 (cons (choice :tag "When changing to"
2822 (const :tag "Not-done state" todo)
2823 (const :tag "Done state" done)
2824 (string :tag "State"))
2825 (repeat
2826 (cons :tag "Tag action"
2827 (string :tag "Tag")
2828 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2830 (defcustom org-log-done nil
2831 "Information to record when a task moves to the DONE state.
2833 Possible values are:
2835 nil Don't add anything, just change the keyword
2836 time Add a time stamp to the task
2837 note Prompt for a note and add it with template `org-log-note-headings'
2839 This option can also be set with on a per-file-basis with
2841 #+STARTUP: nologdone
2842 #+STARTUP: logdone
2843 #+STARTUP: lognotedone
2845 You can have local logging settings for a subtree by setting the LOGGING
2846 property to one or more of these keywords."
2847 :group 'org-todo
2848 :group 'org-progress
2849 :type '(choice
2850 (const :tag "No logging" nil)
2851 (const :tag "Record CLOSED timestamp" time)
2852 (const :tag "Record CLOSED timestamp with note." note)))
2854 ;; Normalize old uses of org-log-done.
2855 (cond
2856 ((eq org-log-done t) (setq org-log-done 'time))
2857 ((and (listp org-log-done) (memq 'done org-log-done))
2858 (setq org-log-done 'note)))
2860 (defcustom org-log-reschedule nil
2861 "Information to record when the scheduling date of a tasks is modified.
2863 Possible values are:
2865 nil Don't add anything, just change the date
2866 time Add a time stamp to the task
2867 note Prompt for a note and add it with template `org-log-note-headings'
2869 This option can also be set with on a per-file-basis with
2871 #+STARTUP: nologreschedule
2872 #+STARTUP: logreschedule
2873 #+STARTUP: lognotereschedule"
2874 :group 'org-todo
2875 :group 'org-progress
2876 :type '(choice
2877 (const :tag "No logging" nil)
2878 (const :tag "Record timestamp" time)
2879 (const :tag "Record timestamp with note." note)))
2881 (defcustom org-log-redeadline nil
2882 "Information to record when the deadline date of a tasks is modified.
2884 Possible values are:
2886 nil Don't add anything, just change the date
2887 time Add a time stamp to the task
2888 note Prompt for a note and add it with template `org-log-note-headings'
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: nologredeadline
2893 #+STARTUP: logredeadline
2894 #+STARTUP: lognoteredeadline
2896 You can have local logging settings for a subtree by setting the LOGGING
2897 property to one or more of these keywords."
2898 :group 'org-todo
2899 :group 'org-progress
2900 :type '(choice
2901 (const :tag "No logging" nil)
2902 (const :tag "Record timestamp" time)
2903 (const :tag "Record timestamp with note." note)))
2905 (defcustom org-log-note-clock-out nil
2906 "Non-nil means record a note when clocking out of an item.
2907 This can also be configured on a per-file basis by adding one of
2908 the following lines anywhere in the buffer:
2910 #+STARTUP: lognoteclock-out
2911 #+STARTUP: nolognoteclock-out"
2912 :group 'org-todo
2913 :group 'org-progress
2914 :type 'boolean)
2916 (defcustom org-log-done-with-time t
2917 "Non-nil means the CLOSED time stamp will contain date and time.
2918 When nil, only the date will be recorded."
2919 :group 'org-progress
2920 :type 'boolean)
2922 (defcustom org-log-note-headings
2923 '((done . "CLOSING NOTE %t")
2924 (state . "State %-12s from %-12S %t")
2925 (note . "Note taken on %t")
2926 (reschedule . "Rescheduled from %S on %t")
2927 (delschedule . "Not scheduled, was %S on %t")
2928 (redeadline . "New deadline from %S on %t")
2929 (deldeadline . "Removed deadline, was %S on %t")
2930 (refile . "Refiled on %t")
2931 (clock-out . ""))
2932 "Headings for notes added to entries.
2934 The value is an alist, with the car being a symbol indicating the
2935 note context, and the cdr is the heading to be used. The heading
2936 may also be the empty string. The following placeholders can be
2937 used:
2939 %t a time stamp.
2940 %T an active time stamp instead the default inactive one
2941 %d a short-format time stamp.
2942 %D an active short-format time stamp.
2943 %s the new TODO state or time stamp (inactive), in double quotes.
2944 %S the old TODO state or time stamp (inactive), in double quotes.
2945 %u the user name.
2946 %U full user name.
2948 In fact, it is not a good idea to change the `state' entry,
2949 because Agenda Log mode depends on the format of these entries."
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type '(list :greedy t
2953 (cons (const :tag "Heading when closing an item" done) string)
2954 (cons (const :tag
2955 "Heading when changing todo state (todo sequence only)"
2956 state) string)
2957 (cons (const :tag "Heading when just taking a note" note) string)
2958 (cons (const :tag "Heading when rescheduling" reschedule) string)
2959 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2960 (cons (const :tag "Heading when changing deadline" redeadline) string)
2961 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2962 (cons (const :tag "Heading when refiling" refile) string)
2963 (cons (const :tag "Heading when clocking out" clock-out) string)))
2965 (unless (assq 'note org-log-note-headings)
2966 (push '(note . "%t") org-log-note-headings))
2968 (defcustom org-log-into-drawer nil
2969 "Non-nil means insert state change notes and time stamps into a drawer.
2970 When nil, state changes notes will be inserted after the headline and
2971 any scheduling and clock lines, but not inside a drawer.
2973 The value of this variable should be the name of the drawer to use.
2974 LOGBOOK is proposed as the default drawer for this purpose, you can
2975 also set this to a string to define the drawer of your choice.
2977 A value of t is also allowed, representing \"LOGBOOK\".
2979 A value of t or nil can also be set with on a per-file-basis with
2981 #+STARTUP: logdrawer
2982 #+STARTUP: nologdrawer
2984 If this variable is set, `org-log-state-notes-insert-after-drawers'
2985 will be ignored.
2987 You can set the property LOG_INTO_DRAWER to overrule this setting for
2988 a subtree.
2990 Do not check directly this variable in a Lisp program. Call
2991 function `org-log-into-drawer' instead."
2992 :group 'org-todo
2993 :group 'org-progress
2994 :type '(choice
2995 (const :tag "Not into a drawer" nil)
2996 (const :tag "LOGBOOK" t)
2997 (string :tag "Other")))
2999 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3001 (defun org-log-into-drawer ()
3002 "Name of the log drawer, as a string, or nil.
3003 This is the value of `org-log-into-drawer'. However, if the
3004 current entry has or inherits a LOG_INTO_DRAWER property, it will
3005 be used instead of the default value."
3006 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3007 (cond ((equal p "nil") nil)
3008 ((equal p "t") "LOGBOOK")
3009 ((stringp p) p)
3010 (p "LOGBOOK")
3011 ((stringp org-log-into-drawer) org-log-into-drawer)
3012 (org-log-into-drawer "LOGBOOK"))))
3014 (defcustom org-log-state-notes-insert-after-drawers nil
3015 "Non-nil means insert state change notes after any drawers in entry.
3016 Only the drawers that *immediately* follow the headline and the
3017 deadline/scheduled line are skipped.
3018 When nil, insert notes right after the heading and perhaps the line
3019 with deadline/scheduling if present.
3021 This variable will have no effect if `org-log-into-drawer' is
3022 set."
3023 :group 'org-todo
3024 :group 'org-progress
3025 :type 'boolean)
3027 (defcustom org-log-states-order-reversed t
3028 "Non-nil means the latest state note will be directly after heading.
3029 When nil, the state change notes will be ordered according to time.
3031 This option can also be set with on a per-file-basis with
3033 #+STARTUP: logstatesreversed
3034 #+STARTUP: nologstatesreversed"
3035 :group 'org-todo
3036 :group 'org-progress
3037 :type 'boolean)
3039 (defcustom org-todo-repeat-to-state nil
3040 "The TODO state to which a repeater should return the repeating task.
3041 By default this is the first task of a TODO sequence or the
3042 previous state of a TYPE_TODO set. But you can specify to use
3043 the previous state in a TODO sequence or a string.
3045 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3046 entry, which has precedence over this option."
3047 :group 'org-todo
3048 :version "24.1"
3049 :type '(choice (const :tag "Use the previous TODO state" t)
3050 (const :tag "Use the head of the TODO sequence" nil)
3051 (string :tag "Use a specific TODO state")))
3053 (defcustom org-log-repeat 'time
3054 "Non-nil means record moving through the DONE state when triggering repeat.
3055 An auto-repeating task is immediately switched back to TODO when
3056 marked DONE. If you are not logging state changes (by adding \"@\"
3057 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3058 record a closing note, there will be no record of the task moving
3059 through DONE. This variable forces taking a note anyway.
3061 nil Don't force a record
3062 time Record a time stamp
3063 note Prompt for a note and add it with template `org-log-note-headings'
3065 This option can also be set with on a per-file-basis with
3067 #+STARTUP: nologrepeat
3068 #+STARTUP: logrepeat
3069 #+STARTUP: lognoterepeat
3071 You can have local logging settings for a subtree by setting the LOGGING
3072 property to one or more of these keywords."
3073 :group 'org-todo
3074 :group 'org-progress
3075 :type '(choice
3076 (const :tag "Don't force a record" nil)
3077 (const :tag "Force recording the DONE state" time)
3078 (const :tag "Force recording a note with the DONE state" note)))
3081 (defgroup org-priorities nil
3082 "Priorities in Org mode."
3083 :tag "Org Priorities"
3084 :group 'org-todo)
3086 (defcustom org-enable-priority-commands t
3087 "Non-nil means priority commands are active.
3088 When nil, these commands will be disabled, so that you never accidentally
3089 set a priority."
3090 :group 'org-priorities
3091 :type 'boolean)
3093 (defcustom org-highest-priority ?A
3094 "The highest priority of TODO items. A character like ?A, ?B etc.
3095 Must have a smaller ASCII number than `org-lowest-priority'."
3096 :group 'org-priorities
3097 :type 'character)
3099 (defcustom org-lowest-priority ?C
3100 "The lowest priority of TODO items. A character like ?A, ?B etc.
3101 Must have a larger ASCII number than `org-highest-priority'."
3102 :group 'org-priorities
3103 :type 'character)
3105 (defcustom org-default-priority ?B
3106 "The default priority of TODO items.
3107 This is the priority an item gets if no explicit priority is given.
3108 When starting to cycle on an empty priority the first step in the cycle
3109 depends on `org-priority-start-cycle-with-default'. The resulting first
3110 step priority must not exceed the range from `org-highest-priority' to
3111 `org-lowest-priority' which means that `org-default-priority' has to be
3112 in this range exclusive or inclusive the range boundaries. Else the
3113 first step refuses to set the default and the second will fall back
3114 to (depending on the command used) the highest or lowest priority."
3115 :group 'org-priorities
3116 :type 'character)
3118 (defcustom org-priority-start-cycle-with-default t
3119 "Non-nil means start with default priority when starting to cycle.
3120 When this is nil, the first step in the cycle will be (depending on the
3121 command used) one higher or lower than the default priority.
3122 See also `org-default-priority'."
3123 :group 'org-priorities
3124 :type 'boolean)
3126 (defcustom org-get-priority-function nil
3127 "Function to extract the priority from a string.
3128 The string is normally the headline. If this is nil Org computes the
3129 priority from the priority cookie like [#A] in the headline. It returns
3130 an integer, increasing by 1000 for each priority level.
3131 The user can set a different function here, which should take a string
3132 as an argument and return the numeric priority."
3133 :group 'org-priorities
3134 :version "24.1"
3135 :type '(choice
3136 (const nil)
3137 (function)))
3139 (defgroup org-time nil
3140 "Options concerning time stamps and deadlines in Org mode."
3141 :tag "Org Time"
3142 :group 'org)
3144 (defcustom org-time-stamp-rounding-minutes '(0 5)
3145 "Number of minutes to round time stamps to.
3146 \\<org-mode-map>\
3147 These are two values, the first applies when first creating a time stamp.
3148 The second applies when changing it with the commands `S-up' and `S-down'.
3149 When changing the time stamp, this means that it will change in steps
3150 of N minutes, as given by the second value.
3152 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3153 numbers should be factors of 60, so for example 5, 10, 15.
3155 When this is larger than 1, you can still force an exact time stamp by using
3156 a double prefix argument to a time stamp command like \
3157 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3158 and by using a prefix arg to `S-up/down' to specify the exact number
3159 of minutes to shift."
3160 :group 'org-time
3161 :get (lambda (var) ; Make sure both elements are there
3162 (if (integerp (default-value var))
3163 (list (default-value var) 5)
3164 (default-value var)))
3165 :type '(list
3166 (integer :tag "when inserting times")
3167 (integer :tag "when modifying times")))
3169 ;; Normalize old customizations of this variable.
3170 (when (integerp org-time-stamp-rounding-minutes)
3171 (setq org-time-stamp-rounding-minutes
3172 (list org-time-stamp-rounding-minutes
3173 org-time-stamp-rounding-minutes)))
3175 (defcustom org-display-custom-times nil
3176 "Non-nil means overlay custom formats over all time stamps.
3177 The formats are defined through the variable `org-time-stamp-custom-formats'.
3178 To turn this on on a per-file basis, insert anywhere in the file:
3179 #+STARTUP: customtime"
3180 :group 'org-time
3181 :set 'set-default
3182 :type 'sexp)
3183 (make-variable-buffer-local 'org-display-custom-times)
3185 (defcustom org-time-stamp-custom-formats
3186 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3187 "Custom formats for time stamps. See `format-time-string' for the syntax.
3188 These are overlaid over the default ISO format if the variable
3189 `org-display-custom-times' is set. Time like %H:%M should be at the
3190 end of the second format. The custom formats are also honored by export
3191 commands, if custom time display is turned on at the time of export."
3192 :group 'org-time
3193 :type 'sexp)
3195 (defun org-time-stamp-format (&optional long inactive)
3196 "Get the right format for a time string."
3197 (let ((f (if long (cdr org-time-stamp-formats)
3198 (car org-time-stamp-formats))))
3199 (if inactive
3200 (concat "[" (substring f 1 -1) "]")
3201 f)))
3203 (defcustom org-deadline-warning-days 14
3204 "Number of days before expiration during which a deadline becomes active.
3205 This variable governs the display in sparse trees and in the agenda.
3206 When 0 or negative, it means use this number (the absolute value of it)
3207 even if a deadline has a different individual lead time specified.
3209 Custom commands can set this variable in the options section."
3210 :group 'org-time
3211 :group 'org-agenda-daily/weekly
3212 :type 'integer)
3214 (defcustom org-scheduled-delay-days 0
3215 "Number of days before a scheduled item becomes active.
3216 This variable governs the display in sparse trees and in the agenda.
3217 The default value (i.e. 0) means: don't delay scheduled item.
3218 When negative, it means use this number (the absolute value of it)
3219 even if a scheduled item has a different individual delay time
3220 specified.
3222 Custom commands can set this variable in the options section."
3223 :group 'org-time
3224 :group 'org-agenda-daily/weekly
3225 :version "24.4"
3226 :package-version '(Org . "8.0")
3227 :type 'integer)
3229 (defcustom org-read-date-prefer-future t
3230 "Non-nil means assume future for incomplete date input from user.
3231 This affects the following situations:
3232 1. The user gives a month but not a year.
3233 For example, if it is April and you enter \"feb 2\", this will be read
3234 as Feb 2, *next* year. \"May 5\", however, will be this year.
3235 2. The user gives a day, but no month.
3236 For example, if today is the 15th, and you enter \"3\", Org will read
3237 this as the third of *next* month. However, if you enter \"17\",
3238 it will be considered as *this* month.
3240 If you set this variable to the symbol `time', then also the following
3241 will work:
3243 3. If the user gives a time.
3244 If the time is before now, it will be interpreted as tomorrow.
3246 Currently none of this works for ISO week specifications.
3248 When this option is nil, the current day, month and year will always be
3249 used as defaults.
3251 See also `org-agenda-jump-prefer-future'."
3252 :group 'org-time
3253 :type '(choice
3254 (const :tag "Never" nil)
3255 (const :tag "Check month and day" t)
3256 (const :tag "Check month, day, and time" time)))
3258 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3259 "Should the agenda jump command prefer the future for incomplete dates?
3260 The default is to do the same as configured in `org-read-date-prefer-future'.
3261 But you can also set a deviating value here.
3262 This may t or nil, or the symbol `org-read-date-prefer-future'."
3263 :group 'org-agenda
3264 :group 'org-time
3265 :version "24.1"
3266 :type '(choice
3267 (const :tag "Use org-read-date-prefer-future"
3268 org-read-date-prefer-future)
3269 (const :tag "Never" nil)
3270 (const :tag "Always" t)))
3272 (defcustom org-read-date-force-compatible-dates t
3273 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3275 Depending on the system Emacs is running on, certain dates cannot
3276 be represented with the type used internally to represent time.
3277 Dates between 1970-1-1 and 2038-1-1 can always be represented
3278 correctly. Some systems allow for earlier dates, some for later,
3279 some for both. One way to find out it to insert any date into an
3280 Org buffer, putting the cursor on the year and hitting S-up and
3281 S-down to test the range.
3283 When this variable is set to t, the date/time prompt will not let
3284 you specify dates outside the 1970-2037 range, so it is certain that
3285 these dates will work in whatever version of Emacs you are
3286 running, and also that you can move a file from one Emacs implementation
3287 to another. WHenever Org is forcing the year for you, it will display
3288 a message and beep.
3290 When this variable is nil, Org will check if the date is
3291 representable in the specific Emacs implementation you are using.
3292 If not, it will force a year, usually the current year, and beep
3293 to remind you. Currently this setting is not recommended because
3294 the likelihood that you will open your Org files in an Emacs that
3295 has limited date range is not negligible.
3297 A workaround for this problem is to use diary sexp dates for time
3298 stamps outside of this range."
3299 :group 'org-time
3300 :version "24.1"
3301 :type 'boolean)
3303 (defcustom org-read-date-display-live t
3304 "Non-nil means display current interpretation of date prompt live.
3305 This display will be in an overlay, in the minibuffer."
3306 :group 'org-time
3307 :type 'boolean)
3309 (defcustom org-read-date-popup-calendar t
3310 "Non-nil means pop up a calendar when prompting for a date.
3311 In the calendar, the date can be selected with mouse-1. However, the
3312 minibuffer will also be active, and you can simply enter the date as well.
3313 When nil, only the minibuffer will be available."
3314 :group 'org-time
3315 :type 'boolean)
3316 (defvaralias 'org-popup-calendar-for-date-prompt
3317 'org-read-date-popup-calendar)
3319 (defcustom org-extend-today-until 0
3320 "The hour when your day really ends. Must be an integer.
3321 This has influence for the following applications:
3322 - When switching the agenda to \"today\". It it is still earlier than
3323 the time given here, the day recognized as TODAY is actually yesterday.
3324 - When a date is read from the user and it is still before the time given
3325 here, the current date and time will be assumed to be yesterday, 23:59.
3326 Also, timestamps inserted in capture templates follow this rule.
3328 IMPORTANT: This is a feature whose implementation is and likely will
3329 remain incomplete. Really, it is only here because past midnight seems to
3330 be the favorite working time of John Wiegley :-)"
3331 :group 'org-time
3332 :type 'integer)
3334 (defcustom org-use-effective-time nil
3335 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3336 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3337 \"effective time\" of any timestamps between midnight and 8am will be
3338 23:59 of the previous day."
3339 :group 'org-time
3340 :version "24.1"
3341 :type 'boolean)
3343 (defcustom org-use-last-clock-out-time-as-effective-time nil
3344 "When non-nil, use the last clock out time for `org-todo'.
3345 Note that this option has precedence over the combined use of
3346 `org-use-effective-time' and `org-extend-today-until'."
3347 :group 'org-time
3348 :version "24.4"
3349 :package-version '(Org . "8.0")
3350 :type 'boolean)
3352 (defcustom org-edit-timestamp-down-means-later nil
3353 "Non-nil means S-down will increase the time in a time stamp.
3354 When nil, S-up will increase."
3355 :group 'org-time
3356 :type 'boolean)
3358 (defcustom org-calendar-follow-timestamp-change t
3359 "Non-nil means make the calendar window follow timestamp changes.
3360 When a timestamp is modified and the calendar window is visible, it will be
3361 moved to the new date."
3362 :group 'org-time
3363 :type 'boolean)
3365 (defgroup org-tags nil
3366 "Options concerning tags in Org mode."
3367 :tag "Org Tags"
3368 :group 'org)
3370 (defcustom org-tag-alist nil
3371 "Default tags available in Org files.
3373 The value of this variable is an alist. Associations either:
3375 (TAG)
3376 (TAG . SELECT)
3377 (SPECIAL)
3379 where TAG is a tag as a string, SELECT is character, used to
3380 select that tag through the fast tag selection interface, and
3381 SPECIAL is one of the following keywords: `:startgroup',
3382 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3383 `:newline'. These keywords are used to define a hierarchy of
3384 tags. See manual for details.
3386 When this variable is nil, Org mode bases tag input on what is
3387 already in the buffer. The value can be overridden locally by
3388 using a TAGS keyword, e.g.,
3390 #+TAGS: tag1 tag2
3392 See also `org-tag-persistent-alist' to sidestep this behavior."
3393 :group 'org-tags
3394 :type '(repeat
3395 (choice
3396 (cons :tag "Tag with key"
3397 (string :tag "Tag name")
3398 (character :tag "Access char"))
3399 (list :tag "Tag" (string :tag "Tag name"))
3400 (const :tag "Start radio group" (:startgroup))
3401 (const :tag "Start tag group, non distinct" (:startgrouptag))
3402 (const :tag "Group tags delimiter" (:grouptags))
3403 (const :tag "End radio group" (:endgroup))
3404 (const :tag "End tag group, non distinct" (:endgrouptag))
3405 (const :tag "New line" (:newline)))))
3407 (defcustom org-tag-persistent-alist nil
3408 "Tags always available in Org files.
3410 The value of this variable is an alist. Associations either:
3412 (TAG)
3413 (TAG . SELECT)
3414 (SPECIAL)
3416 where TAG is a tag as a string, SELECT is a character, used to
3417 select that tag through the fast tag selection interface, and
3418 SPECIAL is one of the following keywords: `:startgroup',
3419 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3420 `:newline'. These keywords are used to define a hierarchy of
3421 tags. See manual for details.
3423 Unlike to `org-tag-alist', tags defined in this variable do not
3424 depend on a local TAGS keyword. Instead, to disable these tags
3425 on a per-file basis, insert anywhere in the file:
3427 #+STARTUP: noptag"
3428 :group 'org-tags
3429 :type '(repeat
3430 (choice
3431 (cons :tag "Tag with key"
3432 (string :tag "Tag name")
3433 (character :tag "Access char"))
3434 (list :tag "Tag" (string :tag "Tag name"))
3435 (const :tag "Start radio group" (:startgroup))
3436 (const :tag "Start tag group, non distinct" (:startgrouptag))
3437 (const :tag "Group tags delimiter" (:grouptags))
3438 (const :tag "End radio group" (:endgroup))
3439 (const :tag "End tag group, non distinct" (:endgrouptag))
3440 (const :tag "New line" (:newline)))))
3442 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3443 "If non-nil, always offer completion for all tags of all agenda files.
3444 Instead of customizing this variable directly, you might want to
3445 set it locally for capture buffers, because there no list of
3446 tags in that file can be created dynamically (there are none).
3448 (add-hook \\='org-capture-mode-hook
3449 (lambda ()
3450 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3451 :group 'org-tags
3452 :version "24.1"
3453 :type 'boolean)
3455 (defvar org-file-tags nil
3456 "List of tags that can be inherited by all entries in the file.
3457 The tags will be inherited if the variable `org-use-tag-inheritance'
3458 says they should be.
3459 This variable is populated from #+FILETAGS lines.")
3461 (defcustom org-use-fast-tag-selection 'auto
3462 "Non-nil means use fast tag selection scheme.
3463 This is a special interface to select and deselect tags with single keys.
3464 When nil, fast selection is never used.
3465 When the symbol `auto', fast selection is used if and only if selection
3466 characters for tags have been configured, either through the variable
3467 `org-tag-alist' or through a #+TAGS line in the buffer.
3468 When t, fast selection is always used and selection keys are assigned
3469 automatically if necessary."
3470 :group 'org-tags
3471 :type '(choice
3472 (const :tag "Always" t)
3473 (const :tag "Never" nil)
3474 (const :tag "When selection characters are configured" auto)))
3476 (defcustom org-fast-tag-selection-single-key nil
3477 "Non-nil means fast tag selection exits after first change.
3478 When nil, you have to press RET to exit it.
3479 During fast tag selection, you can toggle this flag with `C-c'.
3480 This variable can also have the value `expert'. In this case, the window
3481 displaying the tags menu is not even shown, until you press C-c again."
3482 :group 'org-tags
3483 :type '(choice
3484 (const :tag "No" nil)
3485 (const :tag "Yes" t)
3486 (const :tag "Expert" expert)))
3488 (defvar org-fast-tag-selection-include-todo nil
3489 "Non-nil means fast tags selection interface will also offer TODO states.
3490 This is an undocumented feature, you should not rely on it.")
3492 (defcustom org-tags-column -77
3493 "The column to which tags should be indented in a headline.
3494 If this number is positive, it specifies the column. If it is negative,
3495 it means that the tags should be flushright to that column. For example,
3496 -80 works well for a normal 80 character screen.
3497 When 0, place tags directly after headline text, with only one space in
3498 between."
3499 :group 'org-tags
3500 :type 'integer)
3502 (defcustom org-auto-align-tags t
3503 "Non-nil keeps tags aligned when modifying headlines.
3504 Some operations (i.e. demoting) change the length of a headline and
3505 therefore shift the tags around. With this option turned on, after
3506 each such operation the tags are again aligned to `org-tags-column'."
3507 :group 'org-tags
3508 :type 'boolean)
3510 (defcustom org-use-tag-inheritance t
3511 "Non-nil means tags in levels apply also for sublevels.
3512 When nil, only the tags directly given in a specific line apply there.
3513 This may also be a list of tags that should be inherited, or a regexp that
3514 matches tags that should be inherited. Additional control is possible
3515 with the variable `org-tags-exclude-from-inheritance' which gives an
3516 explicit list of tags to be excluded from inheritance, even if the value of
3517 `org-use-tag-inheritance' would select it for inheritance.
3519 If this option is t, a match early-on in a tree can lead to a large
3520 number of matches in the subtree when constructing the agenda or creating
3521 a sparse tree. If you only want to see the first match in a tree during
3522 a search, check out the variable `org-tags-match-list-sublevels'."
3523 :group 'org-tags
3524 :type '(choice
3525 (const :tag "Not" nil)
3526 (const :tag "Always" t)
3527 (repeat :tag "Specific tags" (string :tag "Tag"))
3528 (regexp :tag "Tags matched by regexp")))
3530 (defcustom org-tags-exclude-from-inheritance nil
3531 "List of tags that should never be inherited.
3532 This is a way to exclude a few tags from inheritance. For way to do
3533 the opposite, to actively allow inheritance for selected tags,
3534 see the variable `org-use-tag-inheritance'."
3535 :group 'org-tags
3536 :type '(repeat (string :tag "Tag")))
3538 (defun org-tag-inherit-p (tag)
3539 "Check if TAG is one that should be inherited."
3540 (cond
3541 ((member tag org-tags-exclude-from-inheritance) nil)
3542 ((eq org-use-tag-inheritance t) t)
3543 ((not org-use-tag-inheritance) nil)
3544 ((stringp org-use-tag-inheritance)
3545 (string-match org-use-tag-inheritance tag))
3546 ((listp org-use-tag-inheritance)
3547 (member tag org-use-tag-inheritance))
3548 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3550 (defcustom org-tags-match-list-sublevels t
3551 "Non-nil means list also sublevels of headlines matching a search.
3552 This variable applies to tags/property searches, and also to stuck
3553 projects because this search is based on a tags match as well.
3555 When set to the symbol `indented', sublevels are indented with
3556 leading dots.
3558 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3559 the sublevels of a headline matching a tag search often also match
3560 the same search. Listing all of them can create very long lists.
3561 Setting this variable to nil causes subtrees of a match to be skipped.
3563 This variable is semi-obsolete and probably should always be true. It
3564 is better to limit inheritance to certain tags using the variables
3565 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3566 :group 'org-tags
3567 :type '(choice
3568 (const :tag "No, don't list them" nil)
3569 (const :tag "Yes, do list them" t)
3570 (const :tag "List them, indented with leading dots" indented)))
3572 (defcustom org-tags-sort-function nil
3573 "When set, tags are sorted using this function as a comparator."
3574 :group 'org-tags
3575 :type '(choice
3576 (const :tag "No sorting" nil)
3577 (const :tag "Alphabetical" org-string-collate-lessp)
3578 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3579 (function :tag "Custom function" nil)))
3581 (defvar org-tags-history nil
3582 "History of minibuffer reads for tags.")
3583 (defvar org-last-tags-completion-table nil
3584 "The last used completion table for tags.")
3585 (defvar org-after-tags-change-hook nil
3586 "Hook that is run after the tags in a line have changed.")
3588 (defgroup org-properties nil
3589 "Options concerning properties in Org mode."
3590 :tag "Org Properties"
3591 :group 'org)
3593 (defcustom org-property-format "%-10s %s"
3594 "How property key/value pairs should be formatted by `indent-line'.
3595 When `indent-line' hits a property definition, it will format the line
3596 according to this format, mainly to make sure that the values are
3597 lined-up with respect to each other."
3598 :group 'org-properties
3599 :type 'string)
3601 (defcustom org-properties-postprocess-alist nil
3602 "Alist of properties and functions to adjust inserted values.
3603 Elements of this alist must be of the form
3605 ([string] [function])
3607 where [string] must be a property name and [function] must be a
3608 lambda expression: this lambda expression must take one argument,
3609 the value to adjust, and return the new value as a string.
3611 For example, this element will allow the property \"Remaining\"
3612 to be updated wrt the relation between the \"Effort\" property
3613 and the clock summary:
3615 ((\"Remaining\" (lambda(value)
3616 (let ((clocksum (org-clock-sum-current-item))
3617 (effort (org-duration-to-minutes
3618 (org-entry-get (point) \"Effort\"))))
3619 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3620 :group 'org-properties
3621 :version "24.1"
3622 :type '(alist :key-type (string :tag "Property")
3623 :value-type (function :tag "Function")))
3625 (defcustom org-use-property-inheritance nil
3626 "Non-nil means properties apply also for sublevels.
3628 This setting is chiefly used during property searches. Turning it on can
3629 cause significant overhead when doing a search, which is why it is not
3630 on by default.
3632 When nil, only the properties directly given in the current entry count.
3633 When t, every property is inherited. The value may also be a list of
3634 properties that should have inheritance, or a regular expression matching
3635 properties that should be inherited.
3637 However, note that some special properties use inheritance under special
3638 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3639 and the properties ending in \"_ALL\" when they are used as descriptor
3640 for valid values of a property.
3642 Note for programmers:
3643 When querying an entry with `org-entry-get', you can control if inheritance
3644 should be used. By default, `org-entry-get' looks only at the local
3645 properties. You can request inheritance by setting the inherit argument
3646 to t (to force inheritance) or to `selective' (to respect the setting
3647 in this variable)."
3648 :group 'org-properties
3649 :type '(choice
3650 (const :tag "Not" nil)
3651 (const :tag "Always" t)
3652 (repeat :tag "Specific properties" (string :tag "Property"))
3653 (regexp :tag "Properties matched by regexp")))
3655 (defun org-property-inherit-p (property)
3656 "Return a non-nil value if PROPERTY should be inherited."
3657 (cond
3658 ((eq org-use-property-inheritance t) t)
3659 ((not org-use-property-inheritance) nil)
3660 ((stringp org-use-property-inheritance)
3661 (string-match org-use-property-inheritance property))
3662 ((listp org-use-property-inheritance)
3663 (member-ignore-case property org-use-property-inheritance))
3664 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3666 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3667 "The default column format, if no other format has been defined.
3668 This variable can be set on the per-file basis by inserting a line
3670 #+COLUMNS: %25ITEM ....."
3671 :group 'org-properties
3672 :type 'string)
3674 (defcustom org-columns-ellipses ".."
3675 "The ellipses to be used when a field in column view is truncated.
3676 When this is the empty string, as many characters as possible are shown,
3677 but then there will be no visual indication that the field has been truncated.
3678 When this is a string of length N, the last N characters of a truncated
3679 field are replaced by this string. If the column is narrower than the
3680 ellipses string, only part of the ellipses string will be shown."
3681 :group 'org-properties
3682 :type 'string)
3684 (defconst org-global-properties-fixed
3685 '(("VISIBILITY_ALL" . "folded children content all")
3686 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3687 "List of property/value pairs that can be inherited by any entry.
3689 These are fixed values, for the preset properties. The user variable
3690 that can be used to add to this list is `org-global-properties'.
3692 The entries in this list are cons cells where the car is a property
3693 name and cdr is a string with the value. If the value represents
3694 multiple items like an \"_ALL\" property, separate the items by
3695 spaces.")
3697 (defcustom org-global-properties nil
3698 "List of property/value pairs that can be inherited by any entry.
3700 This list will be combined with the constant `org-global-properties-fixed'.
3702 The entries in this list are cons cells where the car is a property
3703 name and cdr is a string with the value.
3705 You can set buffer-local values for the same purpose in the variable
3706 `org-file-properties' this by adding lines like
3708 #+PROPERTY: NAME VALUE"
3709 :group 'org-properties
3710 :type '(repeat
3711 (cons (string :tag "Property")
3712 (string :tag "Value"))))
3714 (defvar-local org-file-properties nil
3715 "List of property/value pairs that can be inherited by any entry.
3716 Valid for the current buffer.
3717 This variable is populated from #+PROPERTY lines.")
3719 (defgroup org-agenda nil
3720 "Options concerning agenda views in Org mode."
3721 :tag "Org Agenda"
3722 :group 'org)
3724 (defvar-local org-category nil
3725 "Variable used by Org files to set a category for agenda display.
3726 Such files should use a file variable to set it, for example
3728 # -*- mode: org; org-category: \"ELisp\"
3730 or contain a special line
3732 #+CATEGORY: ELisp
3734 If the file does not specify a category, then file's base name
3735 is used instead.")
3736 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3738 (defcustom org-agenda-files nil
3739 "The files to be used for agenda display.
3741 If an entry is a directory, all files in that directory that are matched
3742 by `org-agenda-file-regexp' will be part of the file list.
3744 If the value of the variable is not a list but a single file name, then
3745 the list of agenda files is actually stored and maintained in that file,
3746 one agenda file per line. In this file paths can be given relative to
3747 `org-directory'. Tilde expansion and environment variable substitution
3748 are also made.
3750 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3751 and removed with `\\[org-remove-file]'."
3752 :group 'org-agenda
3753 :type '(choice
3754 (repeat :tag "List of files and directories" file)
3755 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3757 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3758 "Regular expression to match files for `org-agenda-files'.
3759 If any element in the list in that variable contains a directory instead
3760 of a normal file, all files in that directory that are matched by this
3761 regular expression will be included."
3762 :group 'org-agenda
3763 :type 'regexp)
3765 (defcustom org-agenda-text-search-extra-files nil
3766 "List of extra files to be searched by text search commands.
3767 These files will be searched in addition to the agenda files by the
3768 commands `org-search-view' (`\\[org-agenda] s') \
3769 and `org-occur-in-agenda-files'.
3770 Note that these files will only be searched for text search commands,
3771 not for the other agenda views like todo lists, tag searches or the weekly
3772 agenda. This variable is intended to list notes and possibly archive files
3773 that should also be searched by these two commands.
3774 In fact, if the first element in the list is the symbol `agenda-archives',
3775 then all archive files of all agenda files will be added to the search
3776 scope."
3777 :group 'org-agenda
3778 :type '(set :greedy t
3779 (const :tag "Agenda Archives" agenda-archives)
3780 (repeat :inline t (file))))
3782 (defvaralias 'org-agenda-multi-occur-extra-files
3783 'org-agenda-text-search-extra-files)
3785 (defcustom org-agenda-skip-unavailable-files nil
3786 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3787 A nil value means to remove them, after a query, from the list."
3788 :group 'org-agenda
3789 :type 'boolean)
3791 (defcustom org-agenda-diary-file 'diary-file
3792 "File to which to add new entries with the `i' key in agenda and calendar.
3793 When this is the symbol `diary-file', the functionality in the Emacs
3794 calendar will be used to add entries to the `diary-file'. But when this
3795 points to a file, `org-agenda-diary-entry' will be used instead."
3796 :group 'org-agenda
3797 :type '(choice
3798 (const :tag "The standard Emacs diary file" diary-file)
3799 (file :tag "Special Org file diary entries")))
3801 (defgroup org-latex nil
3802 "Options for embedding LaTeX code into Org mode."
3803 :tag "Org LaTeX"
3804 :group 'org)
3806 (defcustom org-format-latex-options
3807 '(:foreground default :background default :scale 1.0
3808 :html-foreground "Black" :html-background "Transparent"
3809 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3810 "Options for creating images from LaTeX fragments.
3811 This is a property list with the following properties:
3812 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3813 `default' means use the foreground of the default face.
3814 `auto' means use the foreground from the text face.
3815 :background the background color, or \"Transparent\".
3816 `default' means use the background of the default face.
3817 `auto' means use the background from the text face.
3818 :scale a scaling factor for the size of the images, to get more pixels
3819 :html-foreground, :html-background, :html-scale
3820 the same numbers for HTML export.
3821 :matchers a list indicating which matchers should be used to
3822 find LaTeX fragments. Valid members of this list are:
3823 \"begin\" find environments
3824 \"$1\" find single characters surrounded by $.$
3825 \"$\" find math expressions surrounded by $...$
3826 \"$$\" find math expressions surrounded by $$....$$
3827 \"\\(\" find math expressions surrounded by \\(...\\)
3828 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3829 :group 'org-latex
3830 :type 'plist)
3832 (defcustom org-format-latex-signal-error t
3833 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3834 When nil, just push out a message."
3835 :group 'org-latex
3836 :version "24.1"
3837 :type 'boolean)
3839 (defcustom org-latex-to-mathml-jar-file nil
3840 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3841 Use this to specify additional executable file say a jar file.
3843 When using MathToWeb as the converter, specify the full-path to
3844 your mathtoweb.jar file."
3845 :group 'org-latex
3846 :version "24.1"
3847 :type '(choice
3848 (const :tag "None" nil)
3849 (file :tag "JAR file" :must-match t)))
3851 (defcustom org-latex-to-mathml-convert-command nil
3852 "Command to convert LaTeX fragments to MathML.
3853 Replace format-specifiers in the command as noted below and use
3854 `shell-command' to convert LaTeX to MathML.
3855 %j: Executable file in fully expanded form as specified by
3856 `org-latex-to-mathml-jar-file'.
3857 %I: Input LaTeX file in fully expanded form.
3858 %i: The latex fragment to be converted.
3859 %o: Output MathML file.
3861 This command is used by `org-create-math-formula'.
3863 When using MathToWeb as the converter, set this option to
3864 \"java -jar %j -unicode -force -df %o %I\".
3866 When using LaTeXML set this option to
3867 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3868 :group 'org-latex
3869 :version "24.1"
3870 :type '(choice
3871 (const :tag "None" nil)
3872 (string :tag "\nShell command")))
3874 (defcustom org-preview-latex-default-process 'dvipng
3875 "The default process to convert LaTeX fragments to image files.
3876 All available processes and theirs documents can be found in
3877 `org-preview-latex-process-alist', which see."
3878 :group 'org-latex
3879 :version "26.1"
3880 :package-version '(Org . "9.0")
3881 :type 'symbol)
3883 (defcustom org-preview-latex-process-alist
3884 '((dvipng
3885 :programs ("latex" "dvipng")
3886 :description "dvi > png"
3887 :message "you need to install the programs: latex and dvipng."
3888 :image-input-type "dvi"
3889 :image-output-type "png"
3890 :image-size-adjust (1.0 . 1.0)
3891 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3892 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3893 (dvisvgm
3894 :programs ("latex" "dvisvgm")
3895 :description "dvi > svg"
3896 :message "you need to install the programs: latex and dvisvgm."
3897 :use-xcolor t
3898 :image-input-type "dvi"
3899 :image-output-type "svg"
3900 :image-size-adjust (1.7 . 1.5)
3901 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3902 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3903 (imagemagick
3904 :programs ("latex" "convert")
3905 :description "pdf > png"
3906 :message "you need to install the programs: latex and imagemagick."
3907 :use-xcolor t
3908 :image-input-type "pdf"
3909 :image-output-type "png"
3910 :image-size-adjust (1.0 . 1.0)
3911 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3912 :image-converter
3913 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3914 "Definitions of external processes for LaTeX previewing.
3915 Org mode can use some external commands to generate TeX snippet's images for
3916 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3917 `org-create-formula-image' how to call them.
3919 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3920 PROPERTIES accepts the following attributes:
3922 :programs list of strings, required programs.
3923 :description string, describe the process.
3924 :message string, message it when required programs cannot be found.
3925 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3926 :image-output-type string, output file type of image converter (e.g., \"png\").
3927 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3928 deal with background and foreground color of image.
3929 Otherwise, dvipng style background and foreground color
3930 format are generated. You may then refer to them in
3931 command options with \"%F\" and \"%B\".
3932 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3933 image size showed in buffer and the cdr element is for
3934 HTML file. This option is only useful for process
3935 developers, users should use variable
3936 `org-format-latex-options' instead.
3937 :post-clean list of strings, files matched are to be cleaned up once
3938 the image is generated. When nil, the files with \".dvi\",
3939 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3940 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3941 be cleaned up.
3942 :latex-header list of strings, the LaTeX header of the snippet file.
3943 When nil, the fallback value is used instead, which is
3944 controlled by `org-format-latex-header',
3945 `org-latex-default-packages-alist' and
3946 `org-latex-packages-alist', which see.
3947 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3948 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3949 replaced with values defined below.
3950 :image-converter list of image converter commands strings. Each of them is
3951 given to the shell and supports any of the following
3952 place-holders defined below.
3954 Place-holders used by `:image-converter' and `:latex-compiler':
3956 %f input file name
3957 %b base name of input file
3958 %o base directory of input file
3959 %O absolute output file name
3961 Place-holders only used by `:image-converter':
3963 %F foreground of image
3964 %B background of image
3965 %D dpi, which is used to adjust image size by some processing commands.
3966 %S the image size scale ratio, which is used to adjust image size by some
3967 processing commands."
3968 :group 'org-latex
3969 :version "26.1"
3970 :package-version '(Org . "9.0")
3971 :type '(alist :tag "LaTeX to image backends"
3972 :value-type (plist)))
3974 (defcustom org-preview-latex-image-directory "ltximg/"
3975 "Path to store latex preview images.
3976 A relative path here creates many directories relative to the
3977 processed Org files paths. An absolute path puts all preview
3978 images at the same place."
3979 :group 'org-latex
3980 :version "26.1"
3981 :package-version '(Org . "9.0")
3982 :type 'string)
3984 (defun org-format-latex-mathml-available-p ()
3985 "Return t if `org-latex-to-mathml-convert-command' is usable."
3986 (save-match-data
3987 (when (and (boundp 'org-latex-to-mathml-convert-command)
3988 org-latex-to-mathml-convert-command)
3989 (let ((executable (car (split-string
3990 org-latex-to-mathml-convert-command))))
3991 (when (executable-find executable)
3992 (if (string-match
3993 "%j" org-latex-to-mathml-convert-command)
3994 (file-readable-p org-latex-to-mathml-jar-file)
3995 t))))))
3997 (defcustom org-format-latex-header "\\documentclass{article}
3998 \\usepackage[usenames]{color}
3999 \[PACKAGES]
4000 \[DEFAULT-PACKAGES]
4001 \\pagestyle{empty} % do not remove
4002 % The settings below are copied from fullpage.sty
4003 \\setlength{\\textwidth}{\\paperwidth}
4004 \\addtolength{\\textwidth}{-3cm}
4005 \\setlength{\\oddsidemargin}{1.5cm}
4006 \\addtolength{\\oddsidemargin}{-2.54cm}
4007 \\setlength{\\evensidemargin}{\\oddsidemargin}
4008 \\setlength{\\textheight}{\\paperheight}
4009 \\addtolength{\\textheight}{-\\headheight}
4010 \\addtolength{\\textheight}{-\\headsep}
4011 \\addtolength{\\textheight}{-\\footskip}
4012 \\addtolength{\\textheight}{-3cm}
4013 \\setlength{\\topmargin}{1.5cm}
4014 \\addtolength{\\topmargin}{-2.54cm}"
4015 "The document header used for processing LaTeX fragments.
4016 It is imperative that this header make sure that no page number
4017 appears on the page. The package defined in the variables
4018 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4019 will either replace the placeholder \"[PACKAGES]\" in this
4020 header, or they will be appended."
4021 :group 'org-latex
4022 :type 'string)
4024 (defun org-set-packages-alist (var val)
4025 "Set the packages alist and make sure it has 3 elements per entry."
4026 (set var (mapcar (lambda (x)
4027 (if (and (consp x) (= (length x) 2))
4028 (list (car x) (nth 1 x) t)
4030 val)))
4032 (defun org-get-packages-alist (var)
4033 "Get the packages alist and make sure it has 3 elements per entry."
4034 (mapcar (lambda (x)
4035 (if (and (consp x) (= (length x) 2))
4036 (list (car x) (nth 1 x) t)
4038 (default-value var)))
4040 (defcustom org-latex-default-packages-alist
4041 '(("AUTO" "inputenc" t ("pdflatex"))
4042 ("T1" "fontenc" t ("pdflatex"))
4043 ("" "graphicx" t)
4044 ("" "grffile" t)
4045 ("" "longtable" nil)
4046 ("" "wrapfig" nil)
4047 ("" "rotating" nil)
4048 ("normalem" "ulem" t)
4049 ("" "amsmath" t)
4050 ("" "textcomp" t)
4051 ("" "amssymb" t)
4052 ("" "capt-of" nil)
4053 ("" "hyperref" nil))
4054 "Alist of default packages to be inserted in the header.
4056 Change this only if one of the packages here causes an
4057 incompatibility with another package you are using.
4059 The packages in this list are needed by one part or another of
4060 Org mode to function properly:
4062 - inputenc, fontenc: for basic font and character selection
4063 - graphicx: for including images
4064 - grffile: allow periods and spaces in graphics file names
4065 - longtable: For multipage tables
4066 - wrapfig: for figure placement
4067 - rotating: for sideways figures and tables
4068 - ulem: for underline and strike-through
4069 - amsmath: for subscript and superscript and math environments
4070 - textcomp, amssymb: for various symbols used
4071 for interpreting the entities in `org-entities'. You can skip
4072 some of these packages if you don't use any of their symbols.
4073 - capt-of: for captions outside of floats
4074 - hyperref: for cross references
4076 Therefore you should not modify this variable unless you know
4077 what you are doing. The one reason to change it anyway is that
4078 you might be loading some other package that conflicts with one
4079 of the default packages. Each element is either a cell or
4080 a string.
4082 A cell is of the format
4084 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4086 If SNIPPET-FLAG is non-nil, the package also needs to be included
4087 when compiling LaTeX snippets into images for inclusion into
4088 non-LaTeX output. COMPILERS is a list of compilers that should
4089 include the package, see `org-latex-compiler'. If the document
4090 compiler is not in the list, and the list is non-nil, the package
4091 will not be inserted in the final document.
4093 A string will be inserted as-is in the header of the document."
4094 :group 'org-latex
4095 :group 'org-export-latex
4096 :set 'org-set-packages-alist
4097 :get 'org-get-packages-alist
4098 :version "26.1"
4099 :package-version '(Org . "8.3")
4100 :type '(repeat
4101 (choice
4102 (list :tag "options/package pair"
4103 (string :tag "options")
4104 (string :tag "package")
4105 (boolean :tag "Snippet")
4106 (choice
4107 (const :tag "For all compilers" nil)
4108 (repeat :tag "Allowed compiler" string)))
4109 (string :tag "A line of LaTeX"))))
4111 (defcustom org-latex-packages-alist nil
4112 "Alist of packages to be inserted in every LaTeX header.
4114 These will be inserted after `org-latex-default-packages-alist'.
4115 Each element is either a cell or a string.
4117 A cell is of the format:
4119 (\"options\" \"package\" SNIPPET-FLAG)
4121 SNIPPET-FLAG, when non-nil, indicates that this package is also
4122 needed when turning LaTeX snippets into images for inclusion into
4123 non-LaTeX output.
4125 A string will be inserted as-is in the header of the document.
4127 Make sure that you only list packages here which:
4129 - you want in every file;
4130 - do not conflict with the setup in `org-format-latex-header';
4131 - do not conflict with the default packages in
4132 `org-latex-default-packages-alist'."
4133 :group 'org-latex
4134 :group 'org-export-latex
4135 :set 'org-set-packages-alist
4136 :get 'org-get-packages-alist
4137 :type '(repeat
4138 (choice
4139 (list :tag "options/package pair"
4140 (string :tag "options")
4141 (string :tag "package")
4142 (boolean :tag "Snippet"))
4143 (string :tag "A line of LaTeX"))))
4145 (defgroup org-appearance nil
4146 "Settings for Org mode appearance."
4147 :tag "Org Appearance"
4148 :group 'org)
4150 (defcustom org-level-color-stars-only nil
4151 "Non-nil means fontify only the stars in each headline.
4152 When nil, the entire headline is fontified.
4153 Changing it requires restart of `font-lock-mode' to become effective
4154 also in regions already fontified."
4155 :group 'org-appearance
4156 :type 'boolean)
4158 (defcustom org-hide-leading-stars nil
4159 "Non-nil means hide the first N-1 stars in a headline.
4160 This works by using the face `org-hide' for these stars. This
4161 face is white for a light background, and black for a dark
4162 background. You may have to customize the face `org-hide' to
4163 make this work.
4164 Changing it requires restart of `font-lock-mode' to become effective
4165 also in regions already fontified.
4166 You may also set this on a per-file basis by adding one of the following
4167 lines to the buffer:
4169 #+STARTUP: hidestars
4170 #+STARTUP: showstars"
4171 :group 'org-appearance
4172 :type 'boolean)
4174 (defcustom org-hidden-keywords nil
4175 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4176 For example, a value \\='(title) for this list makes the document's title
4177 appear in the buffer without the initial \"#+TITLE:\" part."
4178 :group 'org-appearance
4179 :version "24.1"
4180 :type '(set (const :tag "#+AUTHOR" author)
4181 (const :tag "#+DATE" date)
4182 (const :tag "#+EMAIL" email)
4183 (const :tag "#+TITLE" title)))
4185 (defcustom org-custom-properties nil
4186 "List of properties (as strings) with a special meaning.
4187 The default use of these custom properties is to let the user
4188 hide them with `org-toggle-custom-properties-visibility'."
4189 :group 'org-properties
4190 :group 'org-appearance
4191 :version "24.3"
4192 :type '(repeat (string :tag "Property Name")))
4194 (defcustom org-fontify-done-headline nil
4195 "Non-nil means change the face of a headline if it is marked DONE.
4196 Normally, only the TODO/DONE keyword indicates the state of a headline.
4197 When this is non-nil, the headline after the keyword is set to the
4198 `org-headline-done' as an additional indication."
4199 :group 'org-appearance
4200 :type 'boolean)
4202 (defcustom org-fontify-emphasized-text t
4203 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4204 Changing this variable requires a restart of Emacs to take effect."
4205 :group 'org-appearance
4206 :type 'boolean)
4208 (defcustom org-fontify-whole-heading-line nil
4209 "Non-nil means fontify the whole line for headings.
4210 This is useful when setting a background color for the
4211 org-level-* faces."
4212 :group 'org-appearance
4213 :type 'boolean)
4215 (defcustom org-highlight-latex-and-related nil
4216 "Non-nil means highlight LaTeX related syntax in the buffer.
4217 When non nil, the value should be a list containing any of the
4218 following symbols:
4219 `latex' Highlight LaTeX snippets and environments.
4220 `script' Highlight subscript and superscript.
4221 `entities' Highlight entities."
4222 :group 'org-appearance
4223 :version "24.4"
4224 :package-version '(Org . "8.0")
4225 :type '(choice
4226 (const :tag "No highlighting" nil)
4227 (set :greedy t :tag "Highlight"
4228 (const :tag "LaTeX snippets and environments" latex)
4229 (const :tag "Subscript and superscript" script)
4230 (const :tag "Entities" entities))))
4232 (defcustom org-hide-emphasis-markers nil
4233 "Non-nil mean font-lock should hide the emphasis marker characters."
4234 :group 'org-appearance
4235 :type 'boolean)
4237 (defcustom org-hide-macro-markers nil
4238 "Non-nil mean font-lock should hide the brackets marking macro calls."
4239 :group 'org-appearance
4240 :type 'boolean)
4242 (defcustom org-pretty-entities nil
4243 "Non-nil means show entities as UTF8 characters.
4244 When nil, the \\name form remains in the buffer."
4245 :group 'org-appearance
4246 :version "24.1"
4247 :type 'boolean)
4249 (defcustom org-pretty-entities-include-sub-superscripts t
4250 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4251 :group 'org-appearance
4252 :version "24.1"
4253 :type 'boolean)
4255 (defvar org-emph-re nil
4256 "Regular expression for matching emphasis.
4257 After a match, the match groups contain these elements:
4258 0 The match of the full regular expression, including the characters
4259 before and after the proper match
4260 1 The character before the proper match, or empty at beginning of line
4261 2 The proper match, including the leading and trailing markers
4262 3 The leading marker like * or /, indicating the type of highlighting
4263 4 The text between the emphasis markers, not including the markers
4264 5 The character after the match, empty at the end of a line")
4266 (defvar org-verbatim-re nil
4267 "Regular expression for matching verbatim text.")
4269 (defvar org-emphasis-regexp-components) ; defined just below
4270 (defvar org-emphasis-alist) ; defined just below
4271 (defun org-set-emph-re (var val)
4272 "Set variable and compute the emphasis regular expression."
4273 (set var val)
4274 (when (and (boundp 'org-emphasis-alist)
4275 (boundp 'org-emphasis-regexp-components)
4276 org-emphasis-alist org-emphasis-regexp-components)
4277 (pcase-let*
4278 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4279 (body (if (<= nl 0) body
4280 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4281 (template
4282 (format (concat "\\([%s]\\|^\\)" ;before markers
4283 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4284 "\\([%s]\\|$\\)") ;after markers
4285 pre border border body border post)))
4286 (setq org-emph-re (format template "*/_+"))
4287 (setq org-verbatim-re (format template "=~")))))
4289 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4290 ;; set this option proved cumbersome. See this message/thread:
4291 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4292 (defvar org-emphasis-regexp-components
4293 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4294 "Components used to build the regular expression for emphasis.
4295 This is a list with five entries. Terminology: In an emphasis string
4296 like \" *strong word* \", we call the initial space PREMATCH, the final
4297 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4298 and \"trong wor\" is the body. The different components in this variable
4299 specify what is allowed/forbidden in each part:
4301 pre Chars allowed as prematch. Beginning of line will be allowed too.
4302 post Chars allowed as postmatch. End of line will be allowed too.
4303 border The chars *forbidden* as border characters.
4304 body-regexp A regexp like \".\" to match a body character. Don't use
4305 non-shy groups here, and don't allow newline here.
4306 newline The maximum number of newlines allowed in an emphasis exp.
4308 You need to reload Org or to restart Emacs after setting this.")
4310 (defcustom org-emphasis-alist
4311 '(("*" bold)
4312 ("/" italic)
4313 ("_" underline)
4314 ("=" org-verbatim verbatim)
4315 ("~" org-code verbatim)
4316 ("+" (:strike-through t)))
4317 "Alist of characters and faces to emphasize text.
4318 Text starting and ending with a special character will be emphasized,
4319 for example *bold*, _underlined_ and /italic/. This variable sets the
4320 marker characters and the face to be used by font-lock for highlighting
4321 in Org buffers.
4323 You need to reload Org or to restart Emacs after customizing this."
4324 :group 'org-appearance
4325 :set 'org-set-emph-re
4326 :version "24.4"
4327 :package-version '(Org . "8.0")
4328 :type '(repeat
4329 (list
4330 (string :tag "Marker character")
4331 (choice
4332 (face :tag "Font-lock-face")
4333 (plist :tag "Face property list"))
4334 (option (const verbatim)))))
4336 (defvar org-protecting-blocks '("src" "example" "export")
4337 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4338 This is needed for font-lock setup.")
4340 ;;; Functions and variables from their packages
4341 ;; Declared here to avoid compiler warnings
4342 (defvar mark-active)
4344 ;; Various packages
4345 (declare-function calc-eval "calc" (str &optional separator &rest args))
4346 (declare-function calendar-forward-day "cal-move" (arg))
4347 (declare-function calendar-goto-date "cal-move" (date))
4348 (declare-function calendar-goto-today "cal-move" ())
4349 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4350 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4351 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4352 (declare-function cdlatex-tab "ext:cdlatex" ())
4353 (declare-function dired-get-filename
4354 "dired"
4355 (&optional localp no-error-if-not-filep))
4356 (declare-function iswitchb-read-buffer
4357 "iswitchb"
4358 (prompt &optional
4359 default require-match _predicate start matches-set))
4360 (declare-function org-agenda-change-all-lines
4361 "org-agenda"
4362 (newhead hdmarker &optional fixface just-this))
4363 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4364 "org-agenda"
4365 (&optional end))
4366 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4367 (declare-function org-agenda-format-item
4368 "org-agenda"
4369 (extra txt &optional level category tags dotime
4370 remove-re habitp))
4371 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4372 (declare-function org-agenda-save-markers-for-cut-and-paste
4373 "org-agenda"
4374 (beg end))
4375 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4376 (declare-function org-agenda-skip "org-agenda" ())
4377 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4378 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4379 (declare-function org-indent-mode "org-indent" (&optional arg))
4380 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4381 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4382 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4383 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4384 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4385 (declare-function parse-time-string "parse-time" (string))
4387 (defvar align-mode-rules-list)
4388 (defvar calc-embedded-close-formula)
4389 (defvar calc-embedded-open-formula)
4390 (defvar calc-embedded-open-mode)
4391 (defvar font-lock-unfontify-region-function)
4392 (defvar iswitchb-temp-buflist)
4393 (defvar org-agenda-tags-todo-honor-ignore-options)
4394 (defvar remember-data-file)
4395 (defvar texmathp-why)
4397 ;;;###autoload
4398 (defun turn-on-orgtbl ()
4399 "Unconditionally turn on `orgtbl-mode'."
4400 (require 'org-table)
4401 (orgtbl-mode 1))
4403 (defun org-at-table-p (&optional table-type)
4404 "Non-nil if the cursor is inside an Org table.
4405 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4406 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4407 (or (not (derived-mode-p 'org-mode))
4408 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4409 (and e (or table-type
4410 (eq 'org (org-element-property :type e))))))))
4412 (defun org-at-table.el-p ()
4413 "Non-nil when point is at a table.el table."
4414 (and (org-match-line "[ \t]*[|+]")
4415 (let ((element (org-element-at-point)))
4416 (and (eq (org-element-type element) 'table)
4417 (eq (org-element-property :type element) 'table.el)))))
4419 (defun org-at-table-hline-p ()
4420 "Non-nil when point is inside a hline in a table.
4421 Assume point is already in a table."
4422 (org-match-line org-table-hline-regexp))
4424 (defun org-table-map-tables (function &optional quietly)
4425 "Apply FUNCTION to the start of all tables in the buffer."
4426 (org-with-wide-buffer
4427 (goto-char (point-min))
4428 (while (re-search-forward org-table-any-line-regexp nil t)
4429 (unless quietly
4430 (message "Mapping tables: %d%%"
4431 (floor (* 100.0 (point)) (buffer-size))))
4432 (beginning-of-line 1)
4433 (when (and (looking-at org-table-line-regexp)
4434 ;; Exclude tables in src/example/verbatim/clocktable blocks
4435 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4436 (save-excursion (funcall function))
4437 (or (looking-at org-table-line-regexp)
4438 (forward-char 1)))
4439 (re-search-forward org-table-any-border-regexp nil 1)))
4440 (unless quietly (message "Mapping tables: done")))
4442 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4443 (declare-function org-clock-update-mode-line "org-clock" ())
4444 (declare-function org-resolve-clocks "org-clock"
4445 (&optional also-non-dangling-p prompt last-valid))
4447 (defun org-at-TBLFM-p (&optional pos)
4448 "Non-nil when point (or POS) is in #+TBLFM line."
4449 (save-excursion
4450 (goto-char (or pos (point)))
4451 (beginning-of-line)
4452 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4453 (eq (org-element-type (org-element-at-point)) 'table))))
4455 (defvar org-clock-start-time)
4456 (defvar org-clock-marker (make-marker)
4457 "Marker recording the last clock-in.")
4458 (defvar org-clock-hd-marker (make-marker)
4459 "Marker recording the last clock-in, but the headline position.")
4460 (defvar org-clock-heading ""
4461 "The heading of the current clock entry.")
4462 (defun org-clock-is-active ()
4463 "Return the buffer where the clock is currently running.
4464 Return nil if no clock is running."
4465 (marker-buffer org-clock-marker))
4467 (defun org-check-running-clock ()
4468 "Check if the current buffer contains the running clock.
4469 If yes, offer to stop it and to save the buffer with the changes."
4470 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4471 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4472 (buffer-name))))
4473 (org-clock-out)
4474 (when (y-or-n-p "Save changed buffer?")
4475 (save-buffer))))
4477 (defun org-clocktable-try-shift (dir n)
4478 "Check if this line starts a clock table, if yes, shift the time block."
4479 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4480 (org-clocktable-shift dir n)))
4482 ;;;###autoload
4483 (defun org-clock-persistence-insinuate ()
4484 "Set up hooks for clock persistence."
4485 (require 'org-clock)
4486 (add-hook 'org-mode-hook 'org-clock-load)
4487 (add-hook 'kill-emacs-hook 'org-clock-save))
4489 (defgroup org-archive nil
4490 "Options concerning archiving in Org mode."
4491 :tag "Org Archive"
4492 :group 'org-structure)
4494 (defcustom org-archive-location "%s_archive::"
4495 "The location where subtrees should be archived.
4497 The value of this variable is a string, consisting of two parts,
4498 separated by a double-colon. The first part is a filename and
4499 the second part is a headline.
4501 When the filename is omitted, archiving happens in the same file.
4502 %s in the filename will be replaced by the current file
4503 name (without the directory part). Archiving to a different file
4504 is useful to keep archived entries from contributing to the
4505 Org Agenda.
4507 The archived entries will be filed as subtrees of the specified
4508 headline. When the headline is omitted, the subtrees are simply
4509 filed away at the end of the file, as top-level entries. Also in
4510 the heading you can use %s to represent the file name, this can be
4511 useful when using the same archive for a number of different files.
4513 Here are a few examples:
4514 \"%s_archive::\"
4515 If the current file is Projects.org, archive in file
4516 Projects.org_archive, as top-level trees. This is the default.
4518 \"::* Archived Tasks\"
4519 Archive in the current file, under the top-level headline
4520 \"* Archived Tasks\".
4522 \"~/org/archive.org::\"
4523 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4525 \"~/org/archive.org::* From %s\"
4526 Archive in file ~/org/archive.org (absolute path), under headlines
4527 \"From FILENAME\" where file name is the current file name.
4529 \"~/org/datetree.org::datetree/* Finished Tasks\"
4530 The \"datetree/\" string is special, signifying to archive
4531 items to the datetree. Items are placed in either the CLOSED
4532 date of the item, or the current date if there is no CLOSED date.
4533 The heading will be a subentry to the current date. There doesn't
4534 need to be a heading, but there always needs to be a slash after
4535 datetree. For example, to store archived items directly in the
4536 datetree, use \"~/org/datetree.org::datetree/\".
4538 \"basement::** Finished Tasks\"
4539 Archive in file ./basement (relative path), as level 3 trees
4540 below the level 2 heading \"** Finished Tasks\".
4542 You may set this option on a per-file basis by adding to the buffer a
4543 line like
4545 #+ARCHIVE: basement::** Finished Tasks
4547 You may also define it locally for a subtree by setting an ARCHIVE property
4548 in the entry. If such a property is found in an entry, or anywhere up
4549 the hierarchy, it will be used."
4550 :group 'org-archive
4551 :type 'string)
4553 (defcustom org-agenda-skip-archived-trees t
4554 "Non-nil means the agenda will skip any items located in archived trees.
4555 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4556 variable is no longer recommended, you should leave it at the value t.
4557 Instead, use the key `v' to cycle the archives-mode in the agenda."
4558 :group 'org-archive
4559 :group 'org-agenda-skip
4560 :type 'boolean)
4562 (defcustom org-columns-skip-archived-trees t
4563 "Non-nil means ignore archived trees when creating column view."
4564 :group 'org-archive
4565 :group 'org-properties
4566 :type 'boolean)
4568 (defcustom org-cycle-open-archived-trees nil
4569 "Non-nil means `org-cycle' will open archived trees.
4570 An archived tree is a tree marked with the tag ARCHIVE.
4571 When nil, archived trees will stay folded. You can still open them with
4572 normal outline commands like `show-all', but not with the cycling commands."
4573 :group 'org-archive
4574 :group 'org-cycle
4575 :type 'boolean)
4577 (defcustom org-sparse-tree-open-archived-trees nil
4578 "Non-nil means sparse tree construction shows matches in archived trees.
4579 When nil, matches in these trees are highlighted, but the trees are kept in
4580 collapsed state."
4581 :group 'org-archive
4582 :group 'org-sparse-trees
4583 :type 'boolean)
4585 (defcustom org-sparse-tree-default-date-type nil
4586 "The default date type when building a sparse tree.
4587 When this is nil, a date is a scheduled or a deadline timestamp.
4588 Otherwise, these types are allowed:
4590 all: all timestamps
4591 active: only active timestamps (<...>)
4592 inactive: only inactive timestamps ([...])
4593 scheduled: only scheduled timestamps
4594 deadline: only deadline timestamps"
4595 :type '(choice (const :tag "Scheduled or deadline" nil)
4596 (const :tag "All timestamps" all)
4597 (const :tag "Only active timestamps" active)
4598 (const :tag "Only inactive timestamps" inactive)
4599 (const :tag "Only scheduled timestamps" scheduled)
4600 (const :tag "Only deadline timestamps" deadline)
4601 (const :tag "Only closed timestamps" closed))
4602 :version "26.1"
4603 :package-version '(Org . "8.3")
4604 :group 'org-sparse-trees)
4606 (defun org-cycle-hide-archived-subtrees (state)
4607 "Re-hide all archived subtrees after a visibility state change.
4608 STATE should be one of the symbols listed in the docstring of
4609 `org-cycle-hook'."
4610 (when (and (not org-cycle-open-archived-trees)
4611 (not (memq state '(overview folded))))
4612 (save-excursion
4613 (let* ((globalp (memq state '(contents all)))
4614 (beg (if globalp (point-min) (point)))
4615 (end (if globalp (point-max) (org-end-of-subtree t))))
4616 (org-hide-archived-subtrees beg end)
4617 (goto-char beg)
4618 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4619 (message "%s" (substitute-command-keys
4620 "Subtree is archived and stays closed. Use \
4621 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4623 (defun org-force-cycle-archived ()
4624 "Cycle subtree even if it is archived."
4625 (interactive)
4626 (setq this-command 'org-cycle)
4627 (let ((org-cycle-open-archived-trees t))
4628 (call-interactively 'org-cycle)))
4630 (defun org-hide-archived-subtrees (beg end)
4631 "Re-hide all archived subtrees after a visibility state change."
4632 (org-with-wide-buffer
4633 (let ((case-fold-search nil)
4634 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4635 (goto-char beg)
4636 ;; Include headline point is currently on.
4637 (beginning-of-line)
4638 (while (and (< (point) end) (re-search-forward re end t))
4639 (when (member org-archive-tag (org-get-tags nil t))
4640 (org-flag-subtree t)
4641 (org-end-of-subtree t))))))
4643 (defun org-flag-subtree (flag)
4644 (save-excursion
4645 (org-back-to-heading t)
4646 (org-flag-region (line-end-position)
4647 (progn (org-end-of-subtree t) (point))
4648 flag
4649 'outline)))
4651 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4653 ;; Declare Column View Code
4655 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4656 (declare-function org-columns-compute "org-colview" (property))
4658 ;; Declare ID code
4660 (declare-function org-id-store-link "org-id")
4661 (declare-function org-id-locations-load "org-id")
4662 (declare-function org-id-locations-save "org-id")
4663 (defvar org-id-track-globally)
4665 ;;; Variables for pre-computed regular expressions, all buffer local
4667 (defvar-local org-todo-regexp nil
4668 "Matches any of the TODO state keywords.
4669 Since TODO keywords are case-sensitive, `case-fold-search' is
4670 expected to be bound to nil when matching against this regexp.")
4672 (defvar-local org-not-done-regexp nil
4673 "Matches any of the TODO state keywords except the last one.
4674 Since TODO keywords are case-sensitive, `case-fold-search' is
4675 expected to be bound to nil when matching against this regexp.")
4677 (defvar-local org-not-done-heading-regexp nil
4678 "Matches a TODO headline that is not done.
4679 Since TODO keywords are case-sensitive, `case-fold-search' is
4680 expected to be bound to nil when matching against this regexp.")
4682 (defvar-local org-todo-line-regexp nil
4683 "Matches a headline and puts TODO state into group 2 if present.
4684 Since TODO keywords are case-sensitive, `case-fold-search' is
4685 expected to be bound to nil when matching against this regexp.")
4687 (defvar-local org-complex-heading-regexp nil
4688 "Matches a headline and puts everything into groups:
4690 group 1: Stars
4691 group 2: The TODO keyword, maybe
4692 group 3: Priority cookie
4693 group 4: True headline
4694 group 5: Tags
4696 Since TODO keywords are case-sensitive, `case-fold-search' is
4697 expected to be bound to nil when matching against this regexp.")
4699 (defvar-local org-complex-heading-regexp-format nil
4700 "Printf format to make regexp to match an exact headline.
4701 This regexp will match the headline of any node which has the
4702 exact headline text that is put into the format, but may have any
4703 TODO state, priority and tags.")
4705 (defvar-local org-todo-line-tags-regexp nil
4706 "Matches a headline and puts TODO state into group 2 if present.
4707 Also put tags into group 4 if tags are present.")
4709 (defconst org-plain-time-of-day-regexp
4710 (concat
4711 "\\(\\<[012]?[0-9]"
4712 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4713 "\\(--?"
4714 "\\(\\<[012]?[0-9]"
4715 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4716 "\\)?")
4717 "Regular expression to match a plain time or time range.
4718 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4719 groups carry important information:
4720 0 the full match
4721 1 the first time, range or not
4722 8 the second time, if it is a range.")
4724 (defconst org-plain-time-extension-regexp
4725 (concat
4726 "\\(\\<[012]?[0-9]"
4727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4728 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4729 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4730 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4731 groups carry important information:
4732 0 the full match
4733 7 hours of duration
4734 9 minutes of duration")
4736 (defconst org-stamp-time-of-day-regexp
4737 (concat
4738 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4739 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4740 "\\(--?"
4741 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4742 "Regular expression to match a timestamp time or time range.
4743 After a match, the following groups carry important information:
4744 0 the full match
4745 1 date plus weekday, for back referencing to make sure both times are on the same day
4746 2 the first time, range or not
4747 4 the second time, if it is a range.")
4749 (defconst org-startup-options
4750 '(("fold" org-startup-folded t)
4751 ("overview" org-startup-folded t)
4752 ("nofold" org-startup-folded nil)
4753 ("showall" org-startup-folded nil)
4754 ("showeverything" org-startup-folded showeverything)
4755 ("content" org-startup-folded content)
4756 ("indent" org-startup-indented t)
4757 ("noindent" org-startup-indented nil)
4758 ("hidestars" org-hide-leading-stars t)
4759 ("showstars" org-hide-leading-stars nil)
4760 ("odd" org-odd-levels-only t)
4761 ("oddeven" org-odd-levels-only nil)
4762 ("align" org-startup-align-all-tables t)
4763 ("noalign" org-startup-align-all-tables nil)
4764 ("shrink" org-startup-shrink-all-tables t)
4765 ("inlineimages" org-startup-with-inline-images t)
4766 ("noinlineimages" org-startup-with-inline-images nil)
4767 ("latexpreview" org-startup-with-latex-preview t)
4768 ("nolatexpreview" org-startup-with-latex-preview nil)
4769 ("customtime" org-display-custom-times t)
4770 ("logdone" org-log-done time)
4771 ("lognotedone" org-log-done note)
4772 ("nologdone" org-log-done nil)
4773 ("lognoteclock-out" org-log-note-clock-out t)
4774 ("nolognoteclock-out" org-log-note-clock-out nil)
4775 ("logrepeat" org-log-repeat state)
4776 ("lognoterepeat" org-log-repeat note)
4777 ("logdrawer" org-log-into-drawer t)
4778 ("nologdrawer" org-log-into-drawer nil)
4779 ("logstatesreversed" org-log-states-order-reversed t)
4780 ("nologstatesreversed" org-log-states-order-reversed nil)
4781 ("nologrepeat" org-log-repeat nil)
4782 ("logreschedule" org-log-reschedule time)
4783 ("lognotereschedule" org-log-reschedule note)
4784 ("nologreschedule" org-log-reschedule nil)
4785 ("logredeadline" org-log-redeadline time)
4786 ("lognoteredeadline" org-log-redeadline note)
4787 ("nologredeadline" org-log-redeadline nil)
4788 ("logrefile" org-log-refile time)
4789 ("lognoterefile" org-log-refile note)
4790 ("nologrefile" org-log-refile nil)
4791 ("fninline" org-footnote-define-inline t)
4792 ("nofninline" org-footnote-define-inline nil)
4793 ("fnlocal" org-footnote-section nil)
4794 ("fnauto" org-footnote-auto-label t)
4795 ("fnprompt" org-footnote-auto-label nil)
4796 ("fnconfirm" org-footnote-auto-label confirm)
4797 ("fnplain" org-footnote-auto-label plain)
4798 ("fnadjust" org-footnote-auto-adjust t)
4799 ("nofnadjust" org-footnote-auto-adjust nil)
4800 ("constcgs" constants-unit-system cgs)
4801 ("constSI" constants-unit-system SI)
4802 ("noptag" org-tag-persistent-alist nil)
4803 ("hideblocks" org-hide-block-startup t)
4804 ("nohideblocks" org-hide-block-startup nil)
4805 ("beamer" org-startup-with-beamer-mode t)
4806 ("entitiespretty" org-pretty-entities t)
4807 ("entitiesplain" org-pretty-entities nil))
4808 "Variable associated with STARTUP options for Org.
4809 Each element is a list of three items: the startup options (as written
4810 in the #+STARTUP line), the corresponding variable, and the value to set
4811 this variable to if the option is found. An optional forth element PUSH
4812 means to push this value onto the list in the variable.")
4814 (defcustom org-group-tags t
4815 "When non-nil (the default), use group tags.
4816 This can be turned on/off through `org-toggle-tags-groups'."
4817 :group 'org-tags
4818 :group 'org-startup
4819 :type 'boolean)
4821 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4823 (defun org-toggle-tags-groups ()
4824 "Toggle support for group tags.
4825 Support for group tags is controlled by the option
4826 `org-group-tags', which is non-nil by default."
4827 (interactive)
4828 (setq org-group-tags (not org-group-tags))
4829 (cond ((and (derived-mode-p 'org-agenda-mode)
4830 org-group-tags)
4831 (org-agenda-redo))
4832 ((derived-mode-p 'org-mode)
4833 (let ((org-inhibit-startup t)) (org-mode))))
4834 (message "Groups tags support has been turned %s"
4835 (if org-group-tags "on" "off")))
4837 (defun org--tag-add-to-alist (alist1 alist2)
4838 "Merge tags from ALIST1 into ALIST2.
4840 Duplicates tags outside a group are removed. Keywords and order
4841 are preserved.
4843 The function assumes ALIST1 and ALIST2 are proper tag alists.
4844 See `org-tag-alist' for their structure."
4845 (cond
4846 ((null alist2) alist1)
4847 ((null alist1) alist2)
4849 (let ((to-add nil)
4850 (group-flag nil))
4851 (dolist (tag-pair alist1)
4852 (pcase tag-pair
4853 (`(,(or :startgrouptag :startgroup))
4854 (setq group-flag t)
4855 (push tag-pair to-add))
4856 (`(,(or :endgrouptag :endgroup))
4857 (setq group-flag nil)
4858 (push tag-pair to-add))
4859 (`(,(or :grouptags :newline))
4860 (push tag-pair to-add))
4861 (`(,tag . ,_)
4862 ;; Remove duplicates from ALIST1, unless they are in
4863 ;; a group. Indeed, it makes sense to have a tag appear in
4864 ;; multiple groups.
4865 (when (or group-flag (not (assoc tag alist2)))
4866 (push tag-pair to-add)))
4867 (_ (error "Invalid association in tag alist: %S" tag-pair))))
4868 ;; Preserve order of ALIST1.
4869 (append (nreverse to-add) alist2)))))
4871 (defun org-set-regexps-and-options (&optional tags-only)
4872 "Precompute regular expressions used in the current buffer.
4873 When optional argument TAGS-ONLY is non-nil, only compute tags
4874 related expressions."
4875 (when (derived-mode-p 'org-mode)
4876 (let ((alist (org--setup-collect-keywords
4877 (org-make-options-regexp
4878 (append '("FILETAGS" "TAGS" "SETUPFILE")
4879 (and (not tags-only)
4880 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4881 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4882 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4883 ;; Startup options. Get this early since it does change
4884 ;; behavior for other options (e.g., tags).
4885 (let ((startup (cdr (assq 'startup alist))))
4886 (dolist (option startup)
4887 (let ((entry (assoc-string option org-startup-options t)))
4888 (when entry
4889 (let ((var (nth 1 entry))
4890 (val (nth 2 entry)))
4891 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4892 (unless (listp (symbol-value var))
4893 (set (make-local-variable var) nil))
4894 (add-to-list var val)))))))
4895 (setq-local org-file-tags
4896 (mapcar #'org-add-prop-inherited
4897 (cdr (assq 'filetags alist))))
4898 (setq org-current-tag-alist
4899 (org--tag-add-to-alist
4900 org-tag-persistent-alist
4901 (let ((tags (cdr (assq 'tags alist))))
4902 (if tags (org-tag-string-to-alist tags)
4903 org-tag-alist))))
4904 (setq org-tag-groups-alist
4905 (org-tag-alist-to-groups org-current-tag-alist))
4906 (unless tags-only
4907 ;; File properties.
4908 (setq-local org-file-properties (cdr (assq 'property alist)))
4909 ;; Archive location.
4910 (let ((archive (cdr (assq 'archive alist))))
4911 (when archive (setq-local org-archive-location archive)))
4912 ;; Category.
4913 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4914 (when cat
4915 (setq-local org-category (intern cat))
4916 (setq-local org-file-properties
4917 (org--update-property-plist
4918 "CATEGORY" cat org-file-properties))))
4919 ;; Columns.
4920 (let ((column (cdr (assq 'columns alist))))
4921 (when column (setq-local org-columns-default-format column)))
4922 ;; Constants.
4923 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4924 ;; Link abbreviations.
4925 (let ((links (cdr (assq 'link alist))))
4926 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4927 ;; Priorities.
4928 (let ((priorities (cdr (assq 'priorities alist))))
4929 (when priorities
4930 (setq-local org-highest-priority (nth 0 priorities))
4931 (setq-local org-lowest-priority (nth 1 priorities))
4932 (setq-local org-default-priority (nth 2 priorities))))
4933 ;; Scripts.
4934 (let ((scripts (assq 'scripts alist)))
4935 (when scripts
4936 (setq-local org-use-sub-superscripts (cdr scripts))))
4937 ;; TODO keywords.
4938 (setq-local org-todo-kwd-alist nil)
4939 (setq-local org-todo-key-alist nil)
4940 (setq-local org-todo-key-trigger nil)
4941 (setq-local org-todo-keywords-1 nil)
4942 (setq-local org-done-keywords nil)
4943 (setq-local org-todo-heads nil)
4944 (setq-local org-todo-sets nil)
4945 (setq-local org-todo-log-states nil)
4946 (let ((todo-sequences
4947 (or (nreverse (cdr (assq 'todo alist)))
4948 (let ((d (default-value 'org-todo-keywords)))
4949 (if (not (stringp (car d))) d
4950 ;; XXX: Backward compatibility code.
4951 (list (cons org-todo-interpretation d)))))))
4952 (dolist (sequence todo-sequences)
4953 (let* ((sequence (or (run-hook-with-args-until-success
4954 'org-todo-setup-filter-hook sequence)
4955 sequence))
4956 (sequence-type (car sequence))
4957 (keywords (cdr sequence))
4958 (sep (member "|" keywords))
4959 names alist)
4960 (dolist (k (remove "|" keywords))
4961 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4963 (error "Invalid TODO keyword %s" k))
4964 (let ((name (match-string 1 k))
4965 (key (match-string 2 k))
4966 (log (org-extract-log-state-settings k)))
4967 (push name names)
4968 (push (cons name (and key (string-to-char key))) alist)
4969 (when log (push log org-todo-log-states))))
4970 (let* ((names (nreverse names))
4971 (done (if sep (org-remove-keyword-keys (cdr sep))
4972 (last names)))
4973 (head (car names))
4974 (tail (list sequence-type head (car done) (org-last done))))
4975 (add-to-list 'org-todo-heads head 'append)
4976 (push names org-todo-sets)
4977 (setq org-done-keywords (append org-done-keywords done nil))
4978 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4979 (setq org-todo-key-alist
4980 (append org-todo-key-alist
4981 (and alist
4982 (append '((:startgroup))
4983 (nreverse alist)
4984 '((:endgroup))))))
4985 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4986 (setq org-todo-sets (nreverse org-todo-sets)
4987 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4988 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4989 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4990 ;; Compute the regular expressions and other local variables.
4991 ;; Using `org-outline-regexp-bol' would complicate them much,
4992 ;; because of the fixed white space at the end of that string.
4993 (unless org-done-keywords
4994 (setq org-done-keywords
4995 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4996 (setq org-not-done-keywords
4997 (org-delete-all org-done-keywords
4998 (copy-sequence org-todo-keywords-1))
4999 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5000 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5001 org-not-done-heading-regexp
5002 (format org-heading-keyword-regexp-format org-not-done-regexp)
5003 org-todo-line-regexp
5004 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5005 org-complex-heading-regexp
5006 (concat "^\\(\\*+\\)"
5007 "\\(?: +" org-todo-regexp "\\)?"
5008 "\\(?: +\\(\\[#.\\]\\)\\)?"
5009 "\\(?: +\\(.*?\\)\\)??"
5010 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5011 "[ \t]*$")
5012 org-complex-heading-regexp-format
5013 (concat "^\\(\\*+\\)"
5014 "\\(?: +" org-todo-regexp "\\)?"
5015 "\\(?: +\\(\\[#.\\]\\)\\)?"
5016 "\\(?: +"
5017 ;; Stats cookies can be stuck to body.
5018 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5019 "\\(%s\\)"
5020 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5021 "\\)"
5022 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5023 "[ \t]*$")
5024 org-todo-line-tags-regexp
5025 (concat "^\\(\\*+\\)"
5026 "\\(?: +" org-todo-regexp "\\)?"
5027 "\\(?: +\\(.*?\\)\\)??"
5028 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5029 "[ \t]*$"))
5030 (org-compute-latex-and-related-regexp)))))
5032 (defun org--setup-collect-keywords (regexp &optional files alist)
5033 "Return setup keywords values as an alist.
5035 REGEXP matches a subset of setup keywords. FILES is a list of
5036 file names already visited. It is used to avoid circular setup
5037 files. ALIST, when non-nil, is the alist computed so far.
5039 Return value contains the following keys: `archive', `category',
5040 `columns', `constants', `filetags', `link', `priorities',
5041 `property', `scripts', `startup', `tags' and `todo'."
5042 (org-with-wide-buffer
5043 (goto-char (point-min))
5044 (let ((case-fold-search t))
5045 (while (re-search-forward regexp nil t)
5046 (let ((element (org-element-at-point)))
5047 (when (eq (org-element-type element) 'keyword)
5048 (let ((key (org-element-property :key element))
5049 (value (org-element-property :value element)))
5050 (cond
5051 ((equal key "ARCHIVE")
5052 (when (org-string-nw-p value)
5053 (push (cons 'archive value) alist)))
5054 ((equal key "CATEGORY") (push (cons 'category value) alist))
5055 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5056 ((equal key "CONSTANTS")
5057 (let* ((constants (assq 'constants alist))
5058 (store (cdr constants)))
5059 (dolist (pair (split-string value))
5060 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5061 pair)
5062 (let* ((name (match-string 1 pair))
5063 (value (match-string 2 pair))
5064 (old (assoc name store)))
5065 (if old (setcdr old value)
5066 (push (cons name value) store)))))
5067 (if constants (setcdr constants store)
5068 (push (cons 'constants store) alist))))
5069 ((equal key "FILETAGS")
5070 (when (org-string-nw-p value)
5071 (let ((old (assq 'filetags alist))
5072 (new (apply #'nconc
5073 (mapcar (lambda (x) (org-split-string x ":"))
5074 (split-string value)))))
5075 (if old (setcdr old (append new (cdr old)))
5076 (push (cons 'filetags new) alist)))))
5077 ((equal key "LINK")
5078 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5079 (let ((links (assq 'link alist))
5080 (pair (cons (match-string-no-properties 1 value)
5081 (match-string-no-properties 2 value))))
5082 (if links (push pair (cdr links))
5083 (push (list 'link pair) alist)))))
5084 ((equal key "OPTIONS")
5085 (when (and (org-string-nw-p value)
5086 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5087 (push (cons 'scripts (read (match-string 1 value))) alist)))
5088 ((equal key "PRIORITIES")
5089 (push (cons 'priorities
5090 (let ((prio (split-string value)))
5091 (if (< (length prio) 3) '(?A ?C ?B)
5092 (mapcar #'string-to-char prio))))
5093 alist))
5094 ((equal key "PROPERTY")
5095 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5096 (let* ((property (assq 'property alist))
5097 (value (org--update-property-plist
5098 (match-string-no-properties 1 value)
5099 (match-string-no-properties 2 value)
5100 (cdr property))))
5101 (if property (setcdr property value)
5102 (push (cons 'property value) alist)))))
5103 ((equal key "STARTUP")
5104 (let ((startup (assq 'startup alist)))
5105 (if startup
5106 (setcdr startup
5107 (append (cdr startup) (split-string value)))
5108 (push (cons 'startup (split-string value)) alist))))
5109 ((equal key "TAGS")
5110 (let ((tag-cell (assq 'tags alist)))
5111 (if tag-cell
5112 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5113 (push (cons 'tags value) alist))))
5114 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5115 (let ((todo (assq 'todo alist))
5116 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5117 (split-string value))))
5118 (if todo (push value (cdr todo))
5119 (push (list 'todo value) alist))))
5120 ((equal key "SETUPFILE")
5121 (unless buffer-read-only ; Do not check in Gnus messages.
5122 (let ((f (and (org-string-nw-p value)
5123 (expand-file-name
5124 (org-unbracket-string "\"" "\"" value)))))
5125 (when (and f (file-readable-p f) (not (member f files)))
5126 (with-temp-buffer
5127 (setq default-directory (file-name-directory f))
5128 (insert-file-contents f)
5129 (setq alist
5130 ;; Fake Org mode to benefit from cache
5131 ;; without recurring needlessly.
5132 (let ((major-mode 'org-mode))
5133 (org--setup-collect-keywords
5134 regexp (cons f files) alist)))))))))))))))
5135 alist)
5137 (defun org-tag-string-to-alist (s)
5138 "Return tag alist associated to string S.
5139 S is a value for TAGS keyword or produced with
5140 `org-tag-alist-to-string'. Return value is an alist suitable for
5141 `org-tag-alist' or `org-tag-persistent-alist'."
5142 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5143 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5144 "\\(?:(\\(.\\))\\)?\\'"))
5145 alist group-flag)
5146 (dolist (tokens lines (cdr (nreverse alist)))
5147 (push '(:newline) alist)
5148 (while tokens
5149 (let ((token (pop tokens)))
5150 (pcase token
5151 ("{"
5152 (push '(:startgroup) alist)
5153 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5154 ("}"
5155 (push '(:endgroup) alist)
5156 (setq group-flag nil))
5157 ("["
5158 (push '(:startgrouptag) alist)
5159 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5160 ("]"
5161 (push '(:endgrouptag) alist)
5162 (setq group-flag nil))
5163 (":"
5164 (push '(:grouptags) alist))
5165 ((guard (string-match tag-re token))
5166 (let ((tag (match-string 1 token))
5167 (key (and (match-beginning 2)
5168 (string-to-char (match-string 2 token)))))
5169 ;; Push all tags in groups, no matter if they already
5170 ;; appear somewhere else in the list.
5171 (when (or group-flag (not (assoc tag alist)))
5172 (push (cons tag key) alist))))))))))
5174 (defun org-tag-alist-to-string (alist &optional skip-key)
5175 "Return tag string associated to ALIST.
5177 ALIST is an alist, as defined in `org-tag-alist' or
5178 `org-tag-persistent-alist', or produced with
5179 `org-tag-string-to-alist'.
5181 Return value is a string suitable as a value for \"TAGS\"
5182 keyword.
5184 When optional argument SKIP-KEY is non-nil, skip selection keys
5185 next to tags."
5186 (mapconcat (lambda (token)
5187 (pcase token
5188 (`(:startgroup) "{")
5189 (`(:endgroup) "}")
5190 (`(:startgrouptag) "[")
5191 (`(:endgrouptag) "]")
5192 (`(:grouptags) ":")
5193 (`(:newline) "\\n")
5194 ((and
5195 (guard (not skip-key))
5196 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5197 (format "%s(%c)" tag key))
5198 (`(,(and tag (pred stringp)) . ,_) tag)
5199 (_ (user-error "Invalid tag token: %S" token))))
5200 alist
5201 " "))
5203 (defun org-tag-alist-to-groups (alist)
5204 "Return group alist from tag ALIST.
5205 ALIST is an alist, as defined in `org-tag-alist' or
5206 `org-tag-persistent-alist', or produced with
5207 `org-tag-string-to-alist'. Return value is an alist following
5208 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5209 a string, summarizing TAGS, as a list of strings."
5210 (let (groups group-status current-group)
5211 (dolist (token alist (nreverse groups))
5212 (pcase token
5213 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5214 (`(,(or :endgroup :endgrouptag))
5215 (when (eq group-status 'append)
5216 (push (nreverse current-group) groups))
5217 (setq group-status nil current-group nil))
5218 (`(:grouptags) (setq group-status 'append))
5219 ((and `(,tag . ,_) (guard group-status))
5220 (if (eq group-status 'append) (push tag current-group)
5221 (setq current-group (list tag))))
5222 (_ nil)))))
5224 (defvar org--file-cache (make-hash-table :test #'equal)
5225 "Hash table to store contents of files referenced via a URL.
5226 This is the cache of file URLs read using `org-file-contents'.")
5228 (defun org-reset-file-cache ()
5229 "Reset the cache of files downloaded by `org-file-contents'."
5230 (clrhash org--file-cache))
5232 (defun org-file-url-p (file)
5233 "Non-nil if FILE is a URL."
5234 (require 'ffap)
5235 (string-match-p ffap-url-regexp file))
5237 (defun org-file-contents (file &optional noerror nocache)
5238 "Return the contents of FILE, as a string.
5240 FILE can be a file name or URL.
5242 If FILE is a URL, download the contents. If the URL contents are
5243 already cached in the `org--file-cache' hash table, the download step
5244 is skipped.
5246 If NOERROR is non-nil, ignore the error when unable to read the FILE
5247 from file or URL.
5249 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5250 is available. This option applies only if FILE is a URL."
5251 (let* ((is-url (org-file-url-p file))
5252 (cache (and is-url
5253 (not nocache)
5254 (gethash file org--file-cache))))
5255 (cond
5256 (cache)
5257 (is-url
5258 (with-current-buffer (url-retrieve-synchronously file)
5259 (goto-char (point-min))
5260 ;; Move point to after the url-retrieve header.
5261 (search-forward "\n\n" nil :move)
5262 ;; Search for the success code only in the url-retrieve header.
5263 (if (save-excursion
5264 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5265 ;; Update the cache `org--file-cache' and return contents.
5266 (puthash file
5267 (buffer-substring-no-properties (point) (point-max))
5268 org--file-cache)
5269 (funcall (if noerror #'message #'user-error)
5270 "Unable to fetch file from %S"
5271 file))))
5273 (with-temp-buffer
5274 (condition-case nil
5275 (progn
5276 (insert-file-contents file)
5277 (buffer-string))
5278 (file-error
5279 (funcall (if noerror #'message #'user-error)
5280 "Unable to read file %S"
5281 file))))))))
5283 (defun org-extract-log-state-settings (x)
5284 "Extract the log state setting from a TODO keyword string.
5285 This will extract info from a string like \"WAIT(w@/!)\"."
5286 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5287 (let ((kw (match-string 1 x))
5288 (log1 (and (match-end 3) (match-string 3 x)))
5289 (log2 (and (match-end 4) (match-string 4 x))))
5290 (and (or log1 log2)
5291 (list kw
5292 (and log1 (if (equal log1 "!") 'time 'note))
5293 (and log2 (if (equal log2 "!") 'time 'note)))))))
5295 (defun org-remove-keyword-keys (list)
5296 "Remove a pair of parenthesis at the end of each string in LIST."
5297 (mapcar (lambda (x)
5298 (if (string-match "(.*)$" x)
5299 (substring x 0 (match-beginning 0))
5301 list))
5303 (defun org-assign-fast-keys (alist)
5304 "Assign fast keys to a keyword-key alist.
5305 Respect keys that are already there."
5306 (let (new e (alt ?0))
5307 (while (setq e (pop alist))
5308 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5309 (cdr e)) ;; Key already assigned.
5310 (push e new)
5311 (let ((clist (string-to-list (downcase (car e))))
5312 (used (append new alist)))
5313 (when (= (car clist) ?@)
5314 (pop clist))
5315 (while (and clist (rassoc (car clist) used))
5316 (pop clist))
5317 (unless clist
5318 (while (rassoc alt used)
5319 (cl-incf alt)))
5320 (push (cons (car e) (or (car clist) alt)) new))))
5321 (nreverse new)))
5323 ;;; Some variables used in various places
5325 (defvar org-window-configuration nil
5326 "Used in various places to store a window configuration.")
5327 (defvar org-selected-window nil
5328 "Used in various places to store a window configuration.")
5329 (defvar org-finish-function nil
5330 "Function to be called when `C-c C-c' is used.
5331 This is for getting out of special buffers like capture.")
5332 (defvar org-last-state)
5334 ;; Defined somewhere in this file, but used before definition.
5335 (defvar org-entities) ;; defined in org-entities.el
5336 (defvar org-struct-menu)
5337 (defvar org-org-menu)
5338 (defvar org-tbl-menu)
5340 ;;;; Define the Org mode
5342 ;; We use a before-change function to check if a table might need
5343 ;; an update.
5344 (defvar org-table-may-need-update t
5345 "Indicates that a table might need an update.
5346 This variable is set by `org-before-change-function'.
5347 `org-table-align' sets it back to nil.")
5348 (defun org-before-change-function (_beg _end)
5349 "Every change indicates that a table might need an update."
5350 (setq org-table-may-need-update t))
5351 (defvar org-mode-map)
5352 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5353 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5354 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5355 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5356 (defvar org-table-buffer-is-an nil)
5358 (defvar bidi-paragraph-direction)
5359 (defvar buffer-face-mode-face)
5361 (require 'outline)
5363 ;; Other stuff we need.
5364 (require 'time-date)
5365 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5366 (require 'easymenu)
5367 (autoload 'easy-menu-add "easymenu")
5368 (require 'overlay)
5370 ;; (require 'org-macs) moved higher up in the file before it is first used
5371 (require 'org-entities)
5372 ;; (require 'org-compat) moved higher up in the file before it is first used
5373 (require 'org-faces)
5374 (require 'org-list)
5375 (require 'org-pcomplete)
5376 (require 'org-src)
5377 (require 'org-footnote)
5378 (require 'org-macro)
5380 ;; babel
5381 (require 'ob)
5383 ;;;###autoload
5384 (define-derived-mode org-mode outline-mode "Org"
5385 "Outline-based notes management and organizer, alias
5386 \"Carsten's outline-mode for keeping track of everything.\"
5388 Org mode develops organizational tasks around a NOTES file which
5389 contains information about projects as plain text. Org mode is
5390 implemented on top of Outline mode, which is ideal to keep the content
5391 of large files well structured. It supports ToDo items, deadlines and
5392 time stamps, which magically appear in the diary listing of the Emacs
5393 calendar. Tables are easily created with a built-in table editor.
5394 Plain text URL-like links connect to websites, emails (VM), Usenet
5395 messages (Gnus), BBDB entries, and any files related to the project.
5396 For printing and sharing of notes, an Org file (or a part of it)
5397 can be exported as a structured ASCII or HTML file.
5399 The following commands are available:
5401 \\{org-mode-map}"
5403 ;; Get rid of Outline menus, they are not needed
5404 ;; Need to do this here because define-derived-mode sets up
5405 ;; the keymap so late. Still, it is a waste to call this each time
5406 ;; we switch another buffer into Org mode.
5407 (define-key org-mode-map [menu-bar headings] 'undefined)
5408 (define-key org-mode-map [menu-bar hide] 'undefined)
5409 (define-key org-mode-map [menu-bar show] 'undefined)
5411 (org-load-modules-maybe)
5412 (org-install-agenda-files-menu)
5413 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5414 (add-to-invisibility-spec '(org-hide-block . t))
5415 (add-to-invisibility-spec '(org-hide-drawer . t))
5416 (setq-local outline-regexp org-outline-regexp)
5417 (setq-local outline-level 'org-outline-level)
5418 (setq bidi-paragraph-direction 'left-to-right)
5419 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5420 (unless org-display-table
5421 (setq org-display-table (make-display-table)))
5422 (set-display-table-slot
5423 org-display-table 4
5424 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5425 org-ellipsis)))
5426 (setq buffer-display-table org-display-table))
5427 (org-set-regexps-and-options)
5428 (org-set-font-lock-defaults)
5429 (when (and org-tag-faces (not org-tags-special-faces-re))
5430 ;; tag faces set outside customize.... force initialization.
5431 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5432 ;; Calc embedded
5433 (setq-local calc-embedded-open-mode "# ")
5434 ;; Modify a few syntax entries
5435 (modify-syntax-entry ?\" "\"")
5436 (modify-syntax-entry ?\\ "_")
5437 (modify-syntax-entry ?~ "_")
5438 (modify-syntax-entry ?< "(>")
5439 (modify-syntax-entry ?> ")<")
5440 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5441 ;; Activate before-change-function
5442 (setq-local org-table-may-need-update t)
5443 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5444 ;; Check for running clock before killing a buffer
5445 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5446 ;; Initialize macros templates.
5447 (org-macro-initialize-templates)
5448 ;; Initialize radio targets.
5449 (org-update-radio-target-regexp)
5450 ;; Indentation.
5451 (setq-local indent-line-function 'org-indent-line)
5452 (setq-local indent-region-function 'org-indent-region)
5453 ;; Filling and auto-filling.
5454 (org-setup-filling)
5455 ;; Comments.
5456 (org-setup-comments-handling)
5457 ;; Initialize cache.
5458 (org-element-cache-reset)
5459 ;; Beginning/end of defun
5460 (setq-local beginning-of-defun-function 'org-backward-element)
5461 (setq-local end-of-defun-function
5462 (lambda ()
5463 (if (not (org-at-heading-p))
5464 (org-forward-element)
5465 (org-forward-element)
5466 (forward-char -1))))
5467 ;; Next error for sparse trees
5468 (setq-local next-error-function 'org-occur-next-match)
5469 ;; Make sure dependence stuff works reliably, even for users who set it
5470 ;; too late :-(
5471 (if org-enforce-todo-dependencies
5472 (add-hook 'org-blocker-hook
5473 'org-block-todo-from-children-or-siblings-or-parent)
5474 (remove-hook 'org-blocker-hook
5475 'org-block-todo-from-children-or-siblings-or-parent))
5476 (if org-enforce-todo-checkbox-dependencies
5477 (add-hook 'org-blocker-hook
5478 'org-block-todo-from-checkboxes)
5479 (remove-hook 'org-blocker-hook
5480 'org-block-todo-from-checkboxes))
5482 ;; Align options lines
5483 (setq-local
5484 align-mode-rules-list
5485 '((org-in-buffer-settings
5486 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5487 (modes . '(org-mode)))))
5489 ;; Imenu
5490 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5492 ;; Make isearch reveal context
5493 (setq-local outline-isearch-open-invisible-function
5494 (lambda (&rest _) (org-show-context 'isearch)))
5496 ;; Setup the pcomplete hooks
5497 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5498 (setq-local pcomplete-command-name-function 'org-command-at-point)
5499 (setq-local pcomplete-default-completion-function 'ignore)
5500 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5501 (setq-local pcomplete-termination-string "")
5502 (setq-local buffer-face-mode-face 'org-default)
5504 ;; If empty file that did not turn on Org mode automatically, make
5505 ;; it to.
5506 (when (and org-insert-mode-line-in-empty-file
5507 (called-interactively-p 'any)
5508 (= (point-min) (point-max)))
5509 (insert "# -*- mode: org -*-\n\n"))
5510 (unless org-inhibit-startup
5511 (org-unmodified
5512 (when org-startup-with-beamer-mode (org-beamer-mode))
5513 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5514 (org-table-map-tables
5515 (cond ((and org-startup-align-all-tables
5516 org-startup-shrink-all-tables)
5517 (lambda () (org-table-align) (org-table-shrink)))
5518 (org-startup-align-all-tables #'org-table-align)
5519 (t #'org-table-shrink))
5521 (when org-startup-with-inline-images (org-display-inline-images))
5522 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5523 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5524 (when org-startup-truncated (setq truncate-lines t))
5525 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5526 (org-refresh-effort-properties)))
5527 ;; Try to set `org-hide' face correctly.
5528 (let ((foreground (org-find-invisible-foreground)))
5529 (when foreground
5530 (set-face-foreground 'org-hide foreground))))
5532 ;; Update `customize-package-emacs-version-alist'
5533 (add-to-list 'customize-package-emacs-version-alist
5534 '(Org ("8.0" . "24.4")
5535 ("8.1" . "24.4")
5536 ("8.2" . "24.4")
5537 ("8.2.7" . "24.4")
5538 ("8.3" . "26.1")
5539 ("9.0" . "26.1")
5540 ("9.1" . "26.1")
5541 ("9.2" . "27.1")))
5543 (defvar org-mode-transpose-word-syntax-table
5544 (let ((st (make-syntax-table text-mode-syntax-table)))
5545 (dolist (c org-emphasis-alist st)
5546 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5548 (when (fboundp 'abbrev-table-put)
5549 (abbrev-table-put org-mode-abbrev-table
5550 :parents (list text-mode-abbrev-table)))
5552 (defun org-find-invisible-foreground ()
5553 (let ((candidates (remove
5554 "unspecified-bg"
5555 (nconc
5556 (list (face-background 'default)
5557 (face-background 'org-default))
5558 (mapcar
5559 (lambda (alist)
5560 (when (boundp alist)
5561 (cdr (assq 'background-color (symbol-value alist)))))
5562 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5563 (list (face-foreground 'org-hide))))))
5564 (car (remove nil candidates))))
5566 (defun org-current-time (&optional rounding-minutes past)
5567 "Current time, possibly rounded to ROUNDING-MINUTES.
5568 When ROUNDING-MINUTES is not an integer, fall back on the car of
5569 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5570 the rounding returns a past time."
5571 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5572 (car org-time-stamp-rounding-minutes)))
5573 (time (decode-time)) res)
5574 (if (< r 1)
5575 (current-time)
5576 (setq res
5577 (apply 'encode-time
5578 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5579 (nthcdr 2 time))))
5580 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5581 (seconds-to-time (- (float-time res) (* r 60)))
5582 res))))
5584 (defun org-today ()
5585 "Return today date, considering `org-extend-today-until'."
5586 (time-to-days
5587 (time-subtract (current-time)
5588 (list 0 (* 3600 org-extend-today-until) 0))))
5590 ;;;; Font-Lock stuff, including the activators
5592 (defvar org-mouse-map (make-sparse-keymap))
5593 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5594 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5595 (when org-mouse-1-follows-link
5596 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5597 (when org-tab-follows-link
5598 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5599 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5601 (require 'font-lock)
5603 (defconst org-non-link-chars "]\t\n\r<>")
5604 (defvar org-link-types-re nil
5605 "Matches a link that has a url-like prefix like \"http:\"")
5606 (defvar org-link-re-with-space nil
5607 "Matches a link with spaces, optional angular brackets around it.")
5608 (defvar org-link-re-with-space2 nil
5609 "Matches a link with spaces, optional angular brackets around it.")
5610 (defvar org-link-re-with-space3 nil
5611 "Matches a link with spaces, only for internal part in bracket links.")
5612 (defvar org-angle-link-re nil
5613 "Matches link with angular brackets, spaces are allowed.")
5614 (defvar org-plain-link-re nil
5615 "Matches plain link, without spaces.")
5616 (defvar org-bracket-link-regexp nil
5617 "Matches a link in double brackets.")
5618 (defvar org-bracket-link-analytic-regexp nil
5619 "Regular expression used to analyze links.
5620 Here is what the match groups contain after a match:
5621 1: http:
5622 2: http
5623 3: path
5624 4: [desc]
5625 5: desc")
5626 (defvar org-bracket-link-analytic-regexp++ nil
5627 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5628 (defvar org-any-link-re nil
5629 "Regular expression matching any link.")
5631 (defconst org-match-sexp-depth 3
5632 "Number of stacked braces for sub/superscript matching.")
5634 (defun org-create-multibrace-regexp (left right n)
5635 "Create a regular expression which will match a balanced sexp.
5636 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5637 as single character strings.
5638 The regexp returned will match the entire expression including the
5639 delimiters. It will also define a single group which contains the
5640 match except for the outermost delimiters. The maximum depth of
5641 stacked delimiters is N. Escaping delimiters is not possible."
5642 (let* ((nothing (concat "[^" left right "]*?"))
5643 (or "\\|")
5644 (re nothing)
5645 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5646 (while (> n 1)
5647 (setq n (1- n)
5648 re (concat re or next)
5649 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5650 (concat left "\\(" re "\\)" right)))
5652 (defconst org-match-substring-regexp
5653 (concat
5654 "\\(\\S-\\)\\([_^]\\)\\("
5655 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5656 "\\|"
5657 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5658 "\\|"
5659 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5660 "The regular expression matching a sub- or superscript.")
5662 (defconst org-match-substring-with-braces-regexp
5663 (concat
5664 "\\(\\S-\\)\\([_^]\\)"
5665 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5666 "The regular expression matching a sub- or superscript, forcing braces.")
5668 (defun org-make-link-regexps ()
5669 "Update the link regular expressions.
5670 This should be called after the variable `org-link-parameters' has changed."
5671 (let ((types-re (regexp-opt (org-link-types) t)))
5672 (setq org-link-types-re
5673 (concat "\\`" types-re ":")
5674 org-link-re-with-space
5675 (concat "<?" types-re ":"
5676 "\\([^" org-non-link-chars " ]"
5677 "[^" org-non-link-chars "]*"
5678 "[^" org-non-link-chars " ]\\)>?")
5679 org-link-re-with-space2
5680 (concat "<?" types-re ":"
5681 "\\([^" org-non-link-chars " ]"
5682 "[^\t\n\r]*"
5683 "[^" org-non-link-chars " ]\\)>?")
5684 org-link-re-with-space3
5685 (concat "<?" types-re ":"
5686 "\\([^" org-non-link-chars " ]"
5687 "[^\t\n\r]*\\)")
5688 org-angle-link-re
5689 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5690 types-re)
5691 org-plain-link-re
5692 (concat
5693 "\\<" types-re ":"
5694 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5695 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5696 org-bracket-link-regexp
5697 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5698 org-bracket-link-analytic-regexp
5699 (concat
5700 "\\[\\["
5701 "\\(" types-re ":\\)?"
5702 "\\([^]]+\\)"
5703 "\\]"
5704 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5705 "\\]")
5706 org-bracket-link-analytic-regexp++
5707 (concat
5708 "\\[\\["
5709 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5710 "\\([^]]+\\)"
5711 "\\]"
5712 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5713 "\\]")
5714 org-any-link-re
5715 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5716 org-angle-link-re "\\)\\|\\("
5717 org-plain-link-re "\\)"))))
5719 (org-make-link-regexps)
5721 (defvar org-emph-face nil)
5723 (defun org-do-emphasis-faces (limit)
5724 "Run through the buffer and emphasize strings."
5725 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5726 (car org-emphasis-regexp-components))))
5727 (catch :exit
5728 (while (re-search-forward quick-re limit t)
5729 (let* ((marker (match-string 2))
5730 (verbatim? (member marker '("~" "="))))
5731 (when (save-excursion
5732 (goto-char (match-beginning 0))
5733 (and
5734 ;; Do not match table hlines.
5735 (not (and (equal marker "+")
5736 (org-match-line
5737 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5738 ;; Do not match headline stars. Do not consider
5739 ;; stars of a headline as closing marker for bold
5740 ;; markup either.
5741 (not (and (equal marker "*")
5742 (save-excursion
5743 (forward-char)
5744 (skip-chars-backward "*")
5745 (looking-at-p org-outline-regexp-bol))))
5746 ;; Match full emphasis markup regexp.
5747 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5748 ;; Do not span over paragraph boundaries.
5749 (not (string-match-p org-element-paragraph-separate
5750 (match-string 2)))
5751 ;; Do not span over cells in table rows.
5752 (not (and (save-match-data (org-match-line "[ \t]*|"))
5753 (string-match-p "|" (match-string 4))))))
5754 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5755 (font-lock-prepend-text-property
5756 (match-beginning 2) (match-end 2) 'face face)
5757 (when verbatim?
5758 (org-remove-flyspell-overlays-in
5759 (match-beginning 0) (match-end 0)))
5760 (add-text-properties (match-beginning 2) (match-end 2)
5761 '(font-lock-multiline t org-emphasis t))
5762 (when org-hide-emphasis-markers
5763 (add-text-properties (match-end 4) (match-beginning 5)
5764 '(invisible org-link))
5765 (add-text-properties (match-beginning 3) (match-end 3)
5766 '(invisible org-link)))
5767 (throw :exit t))))))))
5769 (defun org-emphasize (&optional char)
5770 "Insert or change an emphasis, i.e. a font like bold or italic.
5771 If there is an active region, change that region to a new emphasis.
5772 If there is no region, just insert the marker characters and position
5773 the cursor between them.
5774 CHAR should be the marker character. If it is a space, it means to
5775 remove the emphasis of the selected region.
5776 If CHAR is not given (for example in an interactive call) it will be
5777 prompted for."
5778 (interactive)
5779 (let ((erc org-emphasis-regexp-components)
5780 (string "") beg end move s)
5781 (if (org-region-active-p)
5782 (setq beg (region-beginning)
5783 end (region-end)
5784 string (buffer-substring beg end))
5785 (setq move t))
5787 (unless char
5788 (message "Emphasis marker or tag: [%s]"
5789 (mapconcat #'car org-emphasis-alist ""))
5790 (setq char (read-char-exclusive)))
5791 (if (equal char ?\s)
5792 (setq s ""
5793 move nil)
5794 (unless (assoc (char-to-string char) org-emphasis-alist)
5795 (user-error "No such emphasis marker: \"%c\"" char))
5796 (setq s (char-to-string char)))
5797 (while (and (> (length string) 1)
5798 (equal (substring string 0 1) (substring string -1))
5799 (assoc (substring string 0 1) org-emphasis-alist))
5800 (setq string (substring string 1 -1)))
5801 (setq string (concat s string s))
5802 (when beg (delete-region beg end))
5803 (unless (or (bolp)
5804 (string-match (concat "[" (nth 0 erc) "\n]")
5805 (char-to-string (char-before (point)))))
5806 (insert " "))
5807 (unless (or (eobp)
5808 (string-match (concat "[" (nth 1 erc) "\n]")
5809 (char-to-string (char-after (point)))))
5810 (insert " ") (backward-char 1))
5811 (insert string)
5812 (and move (backward-char 1))))
5814 (defconst org-nonsticky-props
5815 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5817 (defsubst org-rear-nonsticky-at (pos)
5818 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5820 (defun org-activate-links (limit)
5821 "Add link properties to links.
5822 This includes angle, plain, and bracket links."
5823 (catch :exit
5824 (while (re-search-forward org-any-link-re limit t)
5825 (let* ((start (match-beginning 0))
5826 (end (match-end 0))
5827 (style (cond ((eq ?< (char-after start)) 'angle)
5828 ((eq ?\[ (char-after (1+ start))) 'bracket)
5829 (t 'plain))))
5830 (when (and (memq style org-highlight-links)
5831 ;; Do not confuse plain links with tags.
5832 (not (and (eq style 'plain)
5833 (let ((face (get-text-property
5834 (max (1- start) (point-min)) 'face)))
5835 (if (consp face) (memq 'org-tag face)
5836 (eq 'org-tag face))))))
5837 (let* ((link-object (save-excursion
5838 (goto-char start)
5839 (save-match-data (org-element-link-parser))))
5840 (link (org-element-property :raw-link link-object))
5841 (type (org-element-property :type link-object))
5842 (path (org-element-property :path link-object))
5843 (properties ;for link's visible part
5844 (list
5845 'face (pcase (org-link-get-parameter type :face)
5846 ((and (pred functionp) face) (funcall face path))
5847 ((and (pred facep) face) face)
5848 ((and (pred consp) face) face) ;anonymous
5849 (_ 'org-link))
5850 'mouse-face (or (org-link-get-parameter type :mouse-face)
5851 'highlight)
5852 'keymap (or (org-link-get-parameter type :keymap)
5853 org-mouse-map)
5854 'help-echo (pcase (org-link-get-parameter type :help-echo)
5855 ((and (pred stringp) echo) echo)
5856 ((and (pred functionp) echo) echo)
5857 (_ (concat "LINK: " link)))
5858 'htmlize-link (pcase (org-link-get-parameter type
5859 :htmlize-link)
5860 ((and (pred functionp) f) (funcall f))
5861 (_ `(:uri ,link)))
5862 'font-lock-multiline t)))
5863 (org-remove-flyspell-overlays-in start end)
5864 (org-rear-nonsticky-at end)
5865 (if (not (eq 'bracket style))
5866 (add-text-properties start end properties)
5867 ;; Handle invisible parts in bracket links.
5868 (remove-text-properties start end '(invisible nil))
5869 (let ((hidden
5870 (append `(invisible
5871 ,(or (org-link-get-parameter type :display)
5872 'org-link))
5873 properties))
5874 (visible-start (or (match-beginning 4) (match-beginning 2)))
5875 (visible-end (or (match-end 4) (match-end 2))))
5876 (add-text-properties start visible-start hidden)
5877 (add-text-properties visible-start visible-end properties)
5878 (add-text-properties visible-end end hidden)
5879 (org-rear-nonsticky-at visible-start)
5880 (org-rear-nonsticky-at visible-end)))
5881 (let ((f (org-link-get-parameter type :activate-func)))
5882 (when (functionp f)
5883 (funcall f start end path (eq style 'bracket))))
5884 (throw :exit t))))) ;signal success
5885 nil))
5887 (defun org-activate-code (limit)
5888 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5889 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5890 (remove-text-properties (match-beginning 0) (match-end 0)
5891 '(display t invisible t intangible t))
5894 (defcustom org-src-fontify-natively t
5895 "When non-nil, fontify code in code blocks.
5896 See also the `org-block' face."
5897 :type 'boolean
5898 :version "26.1"
5899 :package-version '(Org . "8.3")
5900 :group 'org-appearance
5901 :group 'org-babel)
5903 (defcustom org-allow-promoting-top-level-subtree nil
5904 "When non-nil, allow promoting a top level subtree.
5905 The leading star of the top level headline will be replaced
5906 by a #."
5907 :type 'boolean
5908 :version "24.1"
5909 :group 'org-appearance)
5911 (defun org-fontify-meta-lines-and-blocks (limit)
5912 (condition-case nil
5913 (org-fontify-meta-lines-and-blocks-1 limit)
5914 (error (message "Org mode fontification error in %S at %d"
5915 (current-buffer)
5916 (line-number-at-pos)))))
5918 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5919 "Fontify #+ lines and blocks."
5920 (let ((case-fold-search t))
5921 (when (re-search-forward
5922 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5923 limit t)
5924 (let ((beg (match-beginning 0))
5925 (block-start (match-end 0))
5926 (block-end nil)
5927 (lang (match-string 7))
5928 (beg1 (line-beginning-position 2))
5929 (dc1 (downcase (match-string 2)))
5930 (dc3 (downcase (match-string 3)))
5931 end end1 quoting block-type)
5932 (cond
5933 ((and (match-end 4) (equal dc3 "+begin"))
5934 ;; Truly a block
5935 (setq block-type (downcase (match-string 5))
5936 quoting (member block-type org-protecting-blocks))
5937 (when (re-search-forward
5938 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5939 nil t) ;; on purpose, we look further than LIMIT
5940 (setq end (min (point-max) (match-end 0))
5941 end1 (min (point-max) (1- (match-beginning 0))))
5942 (setq block-end (match-beginning 0))
5943 (when quoting
5944 (org-remove-flyspell-overlays-in beg1 end1)
5945 (remove-text-properties beg end
5946 '(display t invisible t intangible t)))
5947 (add-text-properties
5948 beg end '(font-lock-fontified t font-lock-multiline t))
5949 (add-text-properties beg beg1 '(face org-meta-line))
5950 (org-remove-flyspell-overlays-in beg beg1)
5951 (add-text-properties ; For end_src
5952 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5953 (org-remove-flyspell-overlays-in end1 end)
5954 (cond
5955 ((and lang (not (string= lang "")) org-src-fontify-natively)
5956 (org-src-font-lock-fontify-block lang block-start block-end)
5957 (add-text-properties beg1 block-end '(src-block t)))
5958 (quoting
5959 (add-text-properties beg1 (min (point-max) (1+ end1))
5960 (list 'face
5961 (list :inherit
5962 (let ((face-name
5963 (intern (format "org-block-%s" lang))))
5964 (append (and (facep face-name) (list face-name))
5965 '(org-block))))))) ; end of source block
5966 ((not org-fontify-quote-and-verse-blocks))
5967 ((string= block-type "quote")
5968 (add-face-text-property
5969 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5970 ((string= block-type "verse")
5971 (add-face-text-property
5972 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5973 (add-text-properties beg beg1 '(face org-block-begin-line))
5974 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5975 '(face org-block-end-line))
5977 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5978 (org-remove-flyspell-overlays-in
5979 (match-beginning 0)
5980 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5981 (add-text-properties
5982 beg (match-end 3)
5983 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5984 '(font-lock-fontified t invisible t)
5985 '(font-lock-fontified t face org-document-info-keyword)))
5986 (add-text-properties
5987 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5988 (if (string-equal dc1 "+title:")
5989 '(font-lock-fontified t face org-document-title)
5990 '(font-lock-fontified t face org-document-info))))
5991 ((string-prefix-p "+caption" dc1)
5992 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5993 (remove-text-properties (match-beginning 0) (match-end 0)
5994 '(display t invisible t intangible t))
5995 ;; Handle short captions.
5996 (save-excursion
5997 (beginning-of-line)
5998 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5999 (add-text-properties (line-beginning-position) (match-end 1)
6000 '(font-lock-fontified t face org-meta-line))
6001 (add-text-properties (match-end 0) (line-end-position)
6002 '(font-lock-fontified t face org-block))
6004 ((member dc3 '(" " ""))
6005 (org-remove-flyspell-overlays-in beg (match-end 0))
6006 (add-text-properties
6007 beg (match-end 0)
6008 '(font-lock-fontified t face font-lock-comment-face)))
6009 (t ;; just any other in-buffer setting, but not indented
6010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6011 (remove-text-properties (match-beginning 0) (match-end 0)
6012 '(display t invisible t intangible t))
6013 (add-text-properties beg (match-end 0)
6014 '(font-lock-fontified t face org-meta-line))
6015 t))))))
6017 (defun org-fontify-drawers (limit)
6018 "Fontify drawers."
6019 (when (re-search-forward org-drawer-regexp limit t)
6020 (add-text-properties
6021 (match-beginning 0) (match-end 0)
6022 '(font-lock-fontified t face org-special-keyword))
6023 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6026 (defun org-fontify-macros (limit)
6027 "Fontify macros."
6028 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6029 (let ((begin (match-beginning 0))
6030 (opening-end (match-beginning 1)))
6031 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6032 (match-string 1))
6033 (let ((end (match-end 1))
6034 (closing-start (match-beginning 1)))
6035 (add-text-properties
6036 begin end
6037 '(font-lock-multiline t font-lock-fontified t face org-macro))
6038 (org-remove-flyspell-overlays-in begin end)
6039 (when org-hide-macro-markers
6040 (add-text-properties begin opening-end '(invisible t))
6041 (add-text-properties closing-start end '(invisible t)))
6042 t)))))
6044 (defun org-activate-footnote-links (limit)
6045 "Add text properties for footnotes."
6046 (let ((fn (org-footnote-next-reference-or-definition limit)))
6047 (when fn
6048 (let* ((beg (nth 1 fn))
6049 (end (nth 2 fn))
6050 (label (car fn))
6051 (referencep (/= (line-beginning-position) beg)))
6052 (when (and referencep (nth 3 fn))
6053 (save-excursion
6054 (goto-char beg)
6055 (search-forward (or label "fn:"))
6056 (org-remove-flyspell-overlays-in beg (match-end 0))))
6057 (add-text-properties beg end
6058 (list 'mouse-face 'highlight
6059 'keymap org-mouse-map
6060 'help-echo
6061 (if referencep "Footnote reference"
6062 "Footnote definition")
6063 'font-lock-fontified t
6064 'font-lock-multiline t
6065 'face 'org-footnote))))))
6067 (defun org-activate-dates (limit)
6068 "Add text properties for dates."
6069 (when (and (re-search-forward org-tsr-regexp-both limit t)
6070 (not (equal (char-before (match-beginning 0)) 91)))
6071 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6072 (add-text-properties (match-beginning 0) (match-end 0)
6073 (list 'mouse-face 'highlight
6074 'keymap org-mouse-map))
6075 (org-rear-nonsticky-at (match-end 0))
6076 (when org-display-custom-times
6077 ;; If it's a date range, activate custom time for second date.
6078 (when (match-end 3)
6079 (org-display-custom-time (match-beginning 3) (match-end 3)))
6080 (org-display-custom-time (match-beginning 1) (match-end 1)))
6083 (defvar-local org-target-link-regexp nil
6084 "Regular expression matching radio targets in plain text.")
6086 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6087 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6088 border border border))
6089 "Regular expression matching a link target.")
6091 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6092 "Regular expression matching a radio target.")
6094 (defconst org-any-target-regexp
6095 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6096 "Regular expression matching any target.")
6098 (defun org-activate-target-links (limit)
6099 "Add text properties for target matches."
6100 (when org-target-link-regexp
6101 (let ((case-fold-search t))
6102 (when (re-search-forward org-target-link-regexp limit t)
6103 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6104 (add-text-properties (match-beginning 1) (match-end 1)
6105 (list 'mouse-face 'highlight
6106 'keymap org-mouse-map
6107 'help-echo "Radio target link"
6108 'org-linked-text t))
6109 (org-rear-nonsticky-at (match-end 1))
6110 t))))
6112 (defun org-update-radio-target-regexp ()
6113 "Find all radio targets in this file and update the regular expression.
6114 Also refresh fontification if needed."
6115 (interactive)
6116 (let ((old-regexp org-target-link-regexp)
6117 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6118 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6119 (targets
6120 (org-with-wide-buffer
6121 (goto-char (point-min))
6122 (let (rtn)
6123 (while (re-search-forward org-radio-target-regexp nil t)
6124 ;; Make sure point is really within the object.
6125 (backward-char)
6126 (let ((obj (org-element-context)))
6127 (when (eq (org-element-type obj) 'radio-target)
6128 (cl-pushnew (org-element-property :value obj) rtn
6129 :test #'equal))))
6130 rtn))))
6131 (setq org-target-link-regexp
6132 (and targets
6133 (concat before-re
6134 (mapconcat
6135 (lambda (x)
6136 (replace-regexp-in-string
6137 " +" "\\s-+" (regexp-quote x) t t))
6138 targets
6139 "\\|")
6140 after-re)))
6141 (unless (equal old-regexp org-target-link-regexp)
6142 ;; Clean-up cache.
6143 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6144 ((not org-target-link-regexp) old-regexp)
6146 (concat before-re
6147 (mapconcat
6148 (lambda (re)
6149 (substring re (length before-re)
6150 (- (length after-re))))
6151 (list old-regexp org-target-link-regexp)
6152 "\\|")
6153 after-re)))))
6154 (org-with-wide-buffer
6155 (goto-char (point-min))
6156 (while (re-search-forward regexp nil t)
6157 (org-element-cache-refresh (match-beginning 1)))))
6158 ;; Re fontify buffer.
6159 (when (memq 'radio org-highlight-links)
6160 (org-restart-font-lock)))))
6162 (defvar org-latex-and-related-regexp nil
6163 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6165 (defun org-compute-latex-and-related-regexp ()
6166 "Compute regular expression for LaTeX, entities and sub/superscript.
6167 Result depends on variable `org-highlight-latex-and-related'."
6168 (setq-local
6169 org-latex-and-related-regexp
6170 (let* ((re-sub
6171 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6172 ((eq org-use-sub-superscripts '{})
6173 (list org-match-substring-with-braces-regexp))
6174 (org-use-sub-superscripts (list org-match-substring-regexp))))
6175 (re-latex
6176 (when (memq 'latex org-highlight-latex-and-related)
6177 (let ((matchers (plist-get org-format-latex-options :matchers)))
6178 (delq nil
6179 (mapcar (lambda (x)
6180 (and (member (car x) matchers) (nth 1 x)))
6181 org-latex-regexps)))))
6182 (re-entities
6183 (when (memq 'entities org-highlight-latex-and-related)
6184 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6185 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6187 (defun org-do-latex-and-related (limit)
6188 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6189 LIMIT bounds the search for syntax to highlight. Stop at first
6190 highlighted object, if any. Return t if some highlighting was
6191 done, nil otherwise."
6192 (when (org-string-nw-p org-latex-and-related-regexp)
6193 (catch 'found
6194 (while (re-search-forward org-latex-and-related-regexp limit t)
6195 (unless
6196 (cl-some
6197 (lambda (f)
6198 (memq f '(org-code org-verbatim underline org-special-keyword)))
6199 (save-excursion
6200 (goto-char (1+ (match-beginning 0)))
6201 (face-at-point nil t)))
6202 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6203 '(?_ ?^))
6205 0)))
6206 (font-lock-prepend-text-property
6207 (+ offset (match-beginning 0)) (match-end 0)
6208 'face 'org-latex-and-related)
6209 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6210 '(font-lock-multiline t)))
6211 (throw 'found t)))
6212 nil)))
6214 (defun org-restart-font-lock ()
6215 "Restart `font-lock-mode', to force refontification."
6216 (when (and (boundp 'font-lock-mode) font-lock-mode)
6217 (font-lock-mode -1)
6218 (font-lock-mode 1)))
6220 (defun org-activate-tags (limit)
6221 (when (re-search-forward org-tag-line-re limit t)
6222 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6223 (add-text-properties (match-beginning 1) (match-end 1)
6224 (list 'mouse-face 'highlight
6225 'keymap org-mouse-map))
6226 (org-rear-nonsticky-at (match-end 1))
6229 (defun org-outline-level ()
6230 "Compute the outline level of the heading at point.
6232 If this is called at a normal headline, the level is the number
6233 of stars. Use `org-reduced-level' to remove the effect of
6234 `org-odd-levels'. Unlike to `org-current-level', this function
6235 takes into consideration inlinetasks."
6236 (org-with-wide-buffer
6237 (end-of-line)
6238 (if (re-search-backward org-outline-regexp-bol nil t)
6239 (1- (- (match-end 0) (match-beginning 0)))
6240 0)))
6242 (defvar org-font-lock-keywords nil)
6244 (defsubst org-re-property (property &optional literal allow-null value)
6245 "Return a regexp matching a PROPERTY line.
6247 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6248 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6249 non-nil, match properties even without a value.
6251 Match group 3 is set to the value when it exists. If there is no
6252 value and ALLOW-NULL is non-nil, it is set to the empty string.
6254 With optional argument VALUE, match only property lines with
6255 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6256 unless LITERAL is non-nil."
6257 (concat
6258 "^\\(?4:[ \t]*\\)"
6259 (format "\\(?1::\\(?2:%s\\):\\)"
6260 (if literal property (regexp-quote property)))
6261 (cond (value
6262 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6263 (if literal value (regexp-quote value))))
6264 (allow-null
6265 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6267 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6269 (defconst org-property-re
6270 (org-re-property "\\S-+" 'literal t)
6271 "Regular expression matching a property line.
6272 There are four matching groups:
6273 1: :PROPKEY: including the leading and trailing colon,
6274 2: PROPKEY without the leading and trailing colon,
6275 3: PROPVAL without leading or trailing spaces,
6276 4: the indentation of the current line,
6277 5: trailing whitespace.")
6279 (defvar org-font-lock-hook nil
6280 "Functions to be called for special font lock stuff.")
6282 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6284 (defvar org-font-lock-set-keywords-hook nil
6285 "Functions that can manipulate `org-font-lock-extra-keywords'.
6286 This is called after `org-font-lock-extra-keywords' is defined, but before
6287 it is installed to be used by font lock. This can be useful if something
6288 needs to be inserted at a specific position in the font-lock sequence.")
6290 (defun org-font-lock-hook (limit)
6291 "Run `org-font-lock-hook' within LIMIT."
6292 (run-hook-with-args 'org-font-lock-hook limit))
6294 (defun org-set-font-lock-defaults ()
6295 "Set font lock defaults for the current buffer."
6296 (let* ((em org-fontify-emphasized-text)
6297 (lk org-highlight-links)
6298 (org-font-lock-extra-keywords
6299 (list
6300 ;; Call the hook
6301 '(org-font-lock-hook)
6302 ;; Headlines
6303 `(,(if org-fontify-whole-heading-line
6304 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6305 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6306 (1 (org-get-level-face 1))
6307 (2 (org-get-level-face 2))
6308 (3 (org-get-level-face 3)))
6309 ;; Table lines
6310 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6311 (1 'org-table t))
6312 ;; Table internals
6313 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6314 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6315 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6316 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6317 ;; Drawers
6318 '(org-fontify-drawers)
6319 ;; Properties
6320 (list org-property-re
6321 '(1 'org-special-keyword t)
6322 '(3 'org-property-value t))
6323 ;; Link related fontification.
6324 '(org-activate-links)
6325 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6326 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6327 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6328 (when (memq 'footnote lk) '(org-activate-footnote-links))
6329 ;; Targets.
6330 (list org-any-target-regexp '(0 'org-target t))
6331 ;; Diary sexps.
6332 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6333 ;; Macro
6334 '(org-fontify-macros)
6335 ;; TODO keyword
6336 (list (format org-heading-keyword-regexp-format
6337 org-todo-regexp)
6338 '(2 (org-get-todo-face 2) t))
6339 ;; DONE
6340 (if org-fontify-done-headline
6341 (list (format org-heading-keyword-regexp-format
6342 (concat
6343 "\\(?:"
6344 (mapconcat 'regexp-quote org-done-keywords "\\|")
6345 "\\)"))
6346 '(2 'org-headline-done t))
6347 nil)
6348 ;; Priorities
6349 '(org-font-lock-add-priority-faces)
6350 ;; Tags
6351 '(org-font-lock-add-tag-faces)
6352 ;; Tags groups
6353 (when (and org-group-tags org-tag-groups-alist)
6354 (list (concat org-outline-regexp-bol ".+\\(:"
6355 (regexp-opt (mapcar 'car org-tag-groups-alist))
6356 ":\\).*$")
6357 '(1 'org-tag-group prepend)))
6358 ;; Special keywords
6359 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6360 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6361 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6362 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6363 ;; Emphasis
6364 (when em '(org-do-emphasis-faces))
6365 ;; Checkboxes
6366 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6367 1 'org-checkbox prepend)
6368 (when (cdr (assq 'checkbox org-list-automatic-rules))
6369 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6370 (0 (org-get-checkbox-statistics-face) t)))
6371 ;; Description list items
6372 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6373 1 'org-list-dt prepend)
6374 ;; ARCHIVEd headings
6375 (list (concat
6376 org-outline-regexp-bol
6377 "\\(.*:" org-archive-tag ":.*\\)")
6378 '(1 'org-archived prepend))
6379 ;; Specials
6380 '(org-do-latex-and-related)
6381 '(org-fontify-entities)
6382 '(org-raise-scripts)
6383 ;; Code
6384 '(org-activate-code (1 'org-code t))
6385 ;; COMMENT
6386 (list (format
6387 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6388 org-todo-regexp
6389 org-comment-string)
6390 '(9 'org-special-keyword t))
6391 ;; Blocks and meta lines
6392 '(org-fontify-meta-lines-and-blocks))))
6393 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6394 (run-hooks 'org-font-lock-set-keywords-hook)
6395 ;; Now set the full font-lock-keywords
6396 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6397 (setq-local font-lock-defaults
6398 '(org-font-lock-keywords t nil nil backward-paragraph))
6399 (kill-local-variable 'font-lock-keywords)
6400 nil))
6402 (defun org-toggle-pretty-entities ()
6403 "Toggle the composition display of entities as UTF8 characters."
6404 (interactive)
6405 (setq-local org-pretty-entities (not org-pretty-entities))
6406 (org-restart-font-lock)
6407 (if org-pretty-entities
6408 (message "Entities are now displayed as UTF8 characters")
6409 (save-restriction
6410 (widen)
6411 (decompose-region (point-min) (point-max))
6412 (message "Entities are now displayed as plain text"))))
6414 (defvar-local org-custom-properties-overlays nil
6415 "List of overlays used for custom properties.")
6417 (defun org-toggle-custom-properties-visibility ()
6418 "Display or hide properties in `org-custom-properties'."
6419 (interactive)
6420 (if org-custom-properties-overlays
6421 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6422 (setq org-custom-properties-overlays nil))
6423 (when org-custom-properties
6424 (org-with-wide-buffer
6425 (goto-char (point-min))
6426 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6427 (while (re-search-forward regexp nil t)
6428 (let ((end (cdr (save-match-data (org-get-property-block)))))
6429 (when (and end (< (point) end))
6430 ;; Hide first custom property in current drawer.
6431 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6432 (overlay-put o 'invisible t)
6433 (overlay-put o 'org-custom-property t)
6434 (push o org-custom-properties-overlays))
6435 ;; Hide additional custom properties in the same drawer.
6436 (while (re-search-forward regexp end t)
6437 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6438 (overlay-put o 'invisible t)
6439 (overlay-put o 'org-custom-property t)
6440 (push o org-custom-properties-overlays)))))
6441 ;; Each entry is limited to a single property drawer.
6442 (outline-next-heading)))))))
6444 (defun org-fontify-entities (limit)
6445 "Find an entity to fontify."
6446 (let (ee)
6447 (when org-pretty-entities
6448 (catch 'match
6449 ;; "\_ "-family is left out on purpose. Only the first one,
6450 ;; i.e., "\_ ", could be fontified anyway, and it would be
6451 ;; confusing when adding a second white space character.
6452 (while (re-search-forward
6453 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6454 limit t)
6455 (when (and (not (org-at-comment-p))
6456 (setq ee (org-entity-get (match-string 1)))
6457 (= (length (nth 6 ee)) 1))
6458 (let* ((end (if (equal (match-string 2) "{}")
6459 (match-end 2)
6460 (match-end 1))))
6461 (add-text-properties
6462 (match-beginning 0) end
6463 (list 'font-lock-fontified t))
6464 (compose-region (match-beginning 0) end
6465 (nth 6 ee) nil)
6466 (backward-char 1)
6467 (throw 'match t))))
6468 nil))))
6470 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6471 "Fontify string S like in Org mode."
6472 (with-temp-buffer
6473 (insert s)
6474 (let ((org-odd-levels-only odd-levels))
6475 (org-mode)
6476 (org-font-lock-ensure)
6477 (buffer-string))))
6479 (defvar org-m nil)
6480 (defvar org-l nil)
6481 (defvar org-f nil)
6482 (defun org-get-level-face (n)
6483 "Get the right face for match N in font-lock matching of headlines."
6484 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6485 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6486 (if org-cycle-level-faces
6487 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6488 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6489 (cond
6490 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6491 ((eq n 2) org-f)
6492 (t (unless org-level-color-stars-only org-f))))
6494 (defun org-face-from-face-or-color (context inherit face-or-color)
6495 "Create a face list that inherits INHERIT, but sets the foreground color.
6496 When FACE-OR-COLOR is not a string, just return it."
6497 (if (stringp face-or-color)
6498 (list :inherit inherit
6499 (cdr (assoc context org-faces-easy-properties))
6500 face-or-color)
6501 face-or-color))
6503 (defun org-get-todo-face (kwd)
6504 "Get the right face for a TODO keyword KWD.
6505 If KWD is a number, get the corresponding match group."
6506 (when (numberp kwd) (setq kwd (match-string kwd)))
6507 (or (org-face-from-face-or-color
6508 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6509 (and (member kwd org-done-keywords) 'org-done)
6510 'org-todo))
6512 (defun org-get-priority-face (priority)
6513 "Get the right face for PRIORITY.
6514 PRIORITY is a character."
6515 (or (org-face-from-face-or-color
6516 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6517 'org-priority))
6519 (defun org-get-tag-face (tag)
6520 "Get the right face for TAG.
6521 If TAG is a number, get the corresponding match group."
6522 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6523 (or (org-face-from-face-or-color
6524 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6525 'org-tag)))
6527 (defun org-font-lock-add-priority-faces (limit)
6528 "Add the special priority faces."
6529 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6530 (add-text-properties
6531 (match-beginning 1) (match-end 1)
6532 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6533 'font-lock-fontified t))))
6535 (defun org-font-lock-add-tag-faces (limit)
6536 "Add the special tag faces."
6537 (when (and org-tag-faces org-tags-special-faces-re)
6538 (while (re-search-forward org-tags-special-faces-re limit t)
6539 (add-text-properties (match-beginning 1) (match-end 1)
6540 (list 'face (org-get-tag-face 1)
6541 'font-lock-fontified t))
6542 (backward-char 1))))
6544 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6545 "Remove fontification and activation overlays from links."
6546 (font-lock-default-unfontify-region beg end)
6547 (let* ((buffer-undo-list t)
6548 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6549 (inhibit-modification-hooks t)
6550 deactivate-mark buffer-file-name buffer-file-truename)
6551 (decompose-region beg end)
6552 (remove-text-properties beg end
6553 '(mouse-face t keymap t org-linked-text t
6554 invisible t intangible t
6555 org-emphasis t))
6556 (org-remove-font-lock-display-properties beg end)))
6558 (defconst org-script-display '(((raise -0.3) (height 0.7))
6559 ((raise 0.3) (height 0.7))
6560 ((raise -0.5))
6561 ((raise 0.5)))
6562 "Display properties for showing superscripts and subscripts.")
6564 (defun org-remove-font-lock-display-properties (beg end)
6565 "Remove specific display properties that have been added by font lock.
6566 The will remove the raise properties that are used to show superscripts
6567 and subscripts."
6568 (let (next prop)
6569 (while (< beg end)
6570 (setq next (next-single-property-change beg 'display nil end)
6571 prop (get-text-property beg 'display))
6572 (when (member prop org-script-display)
6573 (put-text-property beg next 'display nil))
6574 (setq beg next))))
6576 (defun org-raise-scripts (limit)
6577 "Add raise properties to sub/superscripts."
6578 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6579 (re-search-forward
6580 (if (eq org-use-sub-superscripts t)
6581 org-match-substring-regexp
6582 org-match-substring-with-braces-regexp)
6583 limit t))
6584 (let* ((pos (point)) table-p comment-p
6585 (mpos (match-beginning 3))
6586 (emph-p (get-text-property mpos 'org-emphasis))
6587 (link-p (get-text-property mpos 'mouse-face))
6588 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6589 (goto-char (point-at-bol))
6590 (setq table-p (looking-at-p org-table-dataline-regexp)
6591 comment-p (looking-at-p "^[ \t]*#[ +]"))
6592 (goto-char pos)
6593 ;; Handle a_b^c
6594 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6595 (unless (or comment-p emph-p link-p keyw-p)
6596 (put-text-property (match-beginning 3) (match-end 0)
6597 'display
6598 (if (equal (char-after (match-beginning 2)) ?^)
6599 (nth (if table-p 3 1) org-script-display)
6600 (nth (if table-p 2 0) org-script-display)))
6601 (add-text-properties (match-beginning 2) (match-end 2)
6602 (list 'invisible t))
6603 (when (and (eq (char-after (match-beginning 3)) ?{)
6604 (eq (char-before (match-end 3)) ?}))
6605 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6606 (list 'invisible t))
6607 (add-text-properties (1- (match-end 3)) (match-end 3)
6608 (list 'invisible t))))
6609 t)))
6611 (defun org-remove-empty-overlays-at (pos)
6612 "Remove outline overlays that do not contain non-white stuff."
6613 (dolist (o (overlays-at pos))
6614 (and (eq 'outline (overlay-get o 'invisible))
6615 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6616 (overlay-end o))))
6617 (delete-overlay o))))
6619 (defun org-show-empty-lines-in-parent ()
6620 "Move to the parent and re-show empty lines before visible headlines."
6621 (save-excursion
6622 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6623 (org-cycle-show-empty-lines context))))
6625 (defun org-files-list ()
6626 "Return `org-agenda-files' list, plus all open Org files.
6627 This is useful for operations that need to scan all of a user's
6628 open and agenda-wise Org files."
6629 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6630 (dolist (buf (buffer-list))
6631 (with-current-buffer buf
6632 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6633 (cl-pushnew (expand-file-name (buffer-file-name)) files
6634 :test #'equal))))
6635 files))
6637 (defsubst org-entry-beginning-position ()
6638 "Return the beginning position of the current entry."
6639 (save-excursion (org-back-to-heading t) (point)))
6641 (defsubst org-entry-end-position ()
6642 "Return the end position of the current entry."
6643 (save-excursion (outline-next-heading) (point)))
6645 (defun org-subtree-end-visible-p ()
6646 "Is the end of the current subtree visible?"
6647 (pos-visible-in-window-p
6648 (save-excursion (org-end-of-subtree t) (point))))
6650 (defun org-first-headline-recenter ()
6651 "Move cursor to the first headline and recenter the headline."
6652 (let ((window (get-buffer-window)))
6653 (when window
6654 (goto-char (point-min))
6655 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6656 (set-window-start window (line-beginning-position))))))
6659 ;;; Visibility (headlines, blocks, drawers)
6661 ;;;; Headlines visibility
6663 (defun org-show-entry ()
6664 "Show the body directly following this heading.
6665 Show the heading too, if it is currently invisible."
6666 (interactive)
6667 (save-excursion
6668 (ignore-errors
6669 (org-back-to-heading t)
6670 (org-flag-region
6671 (line-end-position 0)
6672 (save-excursion
6673 (if (re-search-forward
6674 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6675 (match-beginning 1)
6676 (point-max)))
6678 'outline))))
6680 (defun org-show-children (&optional level)
6681 "Show all direct subheadings of this heading.
6682 Prefix arg LEVEL is how many levels below the current level
6683 should be shown. Default is enough to cause the following
6684 heading to appear."
6685 (interactive "p")
6686 (save-excursion
6687 (org-back-to-heading t)
6688 (let* ((current-level (funcall outline-level))
6689 (max-level (org-get-valid-level
6690 current-level
6691 (if level (prefix-numeric-value level) 1)))
6692 (end (save-excursion (org-end-of-subtree t t)))
6693 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6694 (past-first-child nil)
6695 ;; Make sure to skip inlinetasks.
6696 (re (format regexp-fmt
6697 current-level
6698 (cond
6699 ((not (featurep 'org-inlinetask)) "")
6700 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6702 (t (1- org-inlinetask-min-level))))))
6703 ;; Display parent heading.
6704 (org-flag-heading nil)
6705 (forward-line)
6706 ;; Display children. First child may be deeper than expected
6707 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6708 ;; MAX-LEVEL accordingly.
6709 (while (re-search-forward re end t)
6710 (unless past-first-child
6711 (setq re (format regexp-fmt
6712 current-level
6713 (max (funcall outline-level) max-level)))
6714 (setq past-first-child t))
6715 (org-flag-heading nil)))))
6717 (defun org-show-subtree ()
6718 "Show everything after this heading at deeper levels."
6719 (interactive)
6720 (org-flag-region
6721 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6723 ;;;; Blocks visibility
6725 (defun org-hide-block-toggle-maybe ()
6726 "Toggle visibility of block at point.
6727 Unlike to `org-hide-block-toggle', this function does not throw
6728 an error. Return a non-nil value when toggling is successful."
6729 (interactive)
6730 (ignore-errors (org-hide-block-toggle)))
6732 (defun org-hide-block-toggle (&optional force)
6733 "Toggle the visibility of the current block.
6734 When optional argument FORCE is `off', make block visible. If it
6735 is non-nil, hide it unconditionally. Throw an error when not at
6736 a block. Return a non-nil value when toggling is successful."
6737 (interactive)
6738 (let ((element (org-element-at-point)))
6739 (unless (memq (org-element-type element)
6740 '(center-block comment-block dynamic-block example-block
6741 export-block quote-block special-block
6742 src-block verse-block))
6743 (user-error "Not at a block"))
6744 (let* ((post (org-element-property :post-affiliated element))
6745 (start (save-excursion
6746 (goto-char post)
6747 (line-end-position)))
6748 (end (save-excursion
6749 (goto-char (org-element-property :end element))
6750 (skip-chars-backward " \t\n")
6751 (line-end-position))))
6752 ;; Do nothing when not before or at the block opening line or at
6753 ;; the block closing line.
6754 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6755 (cond ((eq force 'off)
6756 (org-flag-region start end nil 'org-hide-block))
6757 (force
6758 (org-flag-region start end t 'org-hide-block))
6759 ((eq (get-char-property start 'invisible) 'org-hide-block)
6760 (org-flag-region start end nil 'org-hide-block))
6762 (org-flag-region start end t 'org-hide-block)))
6763 ;; When the block is hidden away, make sure point is left in
6764 ;; a visible part of the buffer.
6765 (when (invisible-p (max (1- (point)) (point-min)))
6766 (goto-char post))
6767 ;; Signal success.
6768 t))))
6770 (defun org-hide-block-toggle-all ()
6771 "Toggle the visibility of all blocks in the current buffer."
6772 (org-block-map 'org-hide-block-toggle))
6774 (defun org-hide-block-all ()
6775 "Fold all blocks in the current buffer."
6776 (interactive)
6777 (org-show-all '(blocks))
6778 (org-block-map 'org-hide-block-toggle-maybe))
6780 ;;;; Drawers visibility
6782 (defun org-cycle-hide-drawers (state &optional exceptions)
6783 "Re-hide all drawers after a visibility state change.
6784 STATE should be one of the symbols listed in the docstring of
6785 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6786 a list of strings specifying which drawers should not be hidden."
6787 (when (and (derived-mode-p 'org-mode)
6788 (not (memq state '(overview folded contents))))
6789 (save-excursion
6790 (let* ((globalp (eq state 'all))
6791 (beg (if globalp (point-min) (point)))
6792 (end (if globalp (point-max)
6793 (if (eq state 'children)
6794 (save-excursion (outline-next-heading) (point))
6795 (org-end-of-subtree t)))))
6796 (goto-char beg)
6797 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6798 (unless (member-ignore-case (match-string 1) exceptions)
6799 (let ((drawer (org-element-at-point)))
6800 (when (memq (org-element-type drawer) '(drawer property-drawer))
6801 (org-flag-drawer t drawer)
6802 ;; Make sure to skip drawer entirely or we might flag
6803 ;; it another time when matching its ending line with
6804 ;; `org-drawer-regexp'.
6805 (goto-char (org-element-property :end drawer))))))))))
6807 (defun org-flag-drawer (flag &optional element)
6808 "When FLAG is non-nil, hide the drawer we are at.
6809 Otherwise make it visible. When optional argument ELEMENT is
6810 a parsed drawer, as returned by `org-element-at-point', hide or
6811 show that drawer instead."
6812 (let ((drawer (or element
6813 (and (save-excursion
6814 (beginning-of-line)
6815 (looking-at-p org-drawer-regexp))
6816 (org-element-at-point)))))
6817 (when (memq (org-element-type drawer) '(drawer property-drawer))
6818 (let ((post (org-element-property :post-affiliated drawer)))
6819 (org-flag-region
6820 (save-excursion (goto-char post) (line-end-position))
6821 (save-excursion (goto-char (org-element-property :end drawer))
6822 (skip-chars-backward " \t\n")
6823 (line-end-position))
6824 flag 'org-hide-drawer)
6825 ;; When the drawer is hidden away, make sure point lies in
6826 ;; a visible part of the buffer.
6827 (when (invisible-p (max (1- (point)) (point-min)))
6828 (goto-char post))))))
6830 ;;;; Visibility cycling
6832 (defvar-local org-cycle-global-status nil)
6833 (put 'org-cycle-global-status 'org-state t)
6834 (defvar-local org-cycle-subtree-status nil)
6835 (put 'org-cycle-subtree-status 'org-state t)
6837 (defun org-show-all (&optional types)
6838 "Show all contents in the visible part of the buffer.
6839 By default, the function expands headings, blocks and drawers.
6840 When optional argument TYPE is a list of symbols among `blocks',
6841 `drawers' and `headings', to only expand one specific type."
6842 (dolist (type (or types '(blocks drawers headings)))
6843 (org-flag-region (point-min) (point-max) nil
6844 (pcase type
6845 (`blocks 'org-hide-block)
6846 (`drawers 'org-hide-drawer)
6847 (`headings 'outline)
6848 (_ (error "Invalid type: %S" type))))))
6850 ;;;###autoload
6851 (defun org-cycle (&optional arg)
6852 "TAB-action and visibility cycling for Org mode.
6854 This is the command invoked in Org mode by the `TAB' key. Its main
6855 purpose is outline visibility cycling, but it also invokes other actions
6856 in special contexts.
6858 When this function is called with a `\\[universal-argument]' prefix, rotate \
6859 the entire
6860 buffer through 3 states (global cycling)
6861 1. OVERVIEW: Show only top-level headlines.
6862 2. CONTENTS: Show all headlines of all levels, but no body text.
6863 3. SHOW ALL: Show everything.
6865 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6866 switch to the startup visibility,
6867 determined by the variable `org-startup-folded', and by any VISIBILITY
6868 properties in the buffer.
6870 With a `\\[universal-argument] \\[universal-argument] \
6871 \\[universal-argument]' prefix argument, show the entire buffer, including
6872 any drawers.
6874 When inside a table, re-align the table and move to the next field.
6876 When point is at the beginning of a headline, rotate the subtree started
6877 by this line through 3 different states (local cycling)
6878 1. FOLDED: Only the main headline is shown.
6879 2. CHILDREN: The main headline and the direct children are shown.
6880 From this state, you can move to one of the children
6881 and zoom in further.
6882 3. SUBTREE: Show the entire subtree, including body text.
6883 If there is no subtree, switch directly from CHILDREN to FOLDED.
6885 When point is at the beginning of an empty headline and the variable
6886 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6887 of the headline by demoting and promoting it to likely levels. This
6888 speeds up creation document structure by pressing `TAB' once or several
6889 times right after creating a new headline.
6891 When there is a numeric prefix, go up to a heading with level ARG, do
6892 a `show-subtree' and return to the previous cursor position. If ARG
6893 is negative, go up that many levels.
6895 When point is not at the beginning of a headline, execute the global
6896 binding for `TAB', which is re-indenting the line. See the option
6897 `org-cycle-emulate-tab' for details.
6899 As a special case, if point is at the beginning of the buffer and there is
6900 no headline in line 1, this function will act as if called with prefix arg
6901 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6902 prefix arg, but only
6903 if the variable `org-cycle-global-at-bob' is t."
6904 (interactive "P")
6905 (org-load-modules-maybe)
6906 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6907 (and org-cycle-level-after-item/entry-creation
6908 (or (org-cycle-level)
6909 (org-cycle-item-indentation))))
6910 (let* ((limit-level
6911 (or org-cycle-max-level
6912 (and (boundp 'org-inlinetask-min-level)
6913 org-inlinetask-min-level
6914 (1- org-inlinetask-min-level))))
6915 (nstars (and limit-level
6916 (if org-odd-levels-only
6917 (and limit-level (1- (* limit-level 2)))
6918 limit-level)))
6919 (org-outline-regexp
6920 (if (not (derived-mode-p 'org-mode))
6921 outline-regexp
6922 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6923 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6924 (not (looking-at org-outline-regexp))))
6925 (org-cycle-hook
6926 (if bob-special
6927 (delq 'org-optimize-window-after-visibility-change
6928 (copy-sequence org-cycle-hook))
6929 org-cycle-hook))
6930 (pos (point)))
6932 (cond
6934 ((equal arg '(16))
6935 (setq last-command 'dummy)
6936 (org-set-startup-visibility)
6937 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6939 ((equal arg '(64))
6940 (org-show-all)
6941 (org-unlogged-message "Entire buffer visible, including drawers"))
6943 ((equal arg '(4)) (org-cycle-internal-global))
6945 ;; Try hiding block at point.
6946 ((org-hide-block-toggle-maybe))
6948 ;; Try cdlatex TAB completion
6949 ((org-try-cdlatex-tab))
6951 ;; Table: enter it or move to the next field.
6952 ((org-at-table-p 'any)
6953 (if (org-at-table.el-p)
6954 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6955 Use `\\[org-edit-special]' to edit table.el tables"))
6956 (if arg (org-table-edit-field t)
6957 (org-table-justify-field-maybe)
6958 (call-interactively 'org-table-next-field))))
6960 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6962 ;; Global cycling: delegate to `org-cycle-internal-global'.
6963 (bob-special (org-cycle-internal-global))
6965 ;; Drawers: delegate to `org-flag-drawer'.
6966 ((save-excursion
6967 (beginning-of-line 1)
6968 (looking-at org-drawer-regexp))
6969 (org-flag-drawer ; toggle block visibility
6970 (not (get-char-property (match-end 0) 'invisible))))
6972 ;; Show-subtree, ARG levels up from here.
6973 ((integerp arg)
6974 (save-excursion
6975 (org-back-to-heading)
6976 (outline-up-heading (if (< arg 0) (- arg)
6977 (- (funcall outline-level) arg)))
6978 (org-show-subtree)))
6980 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6981 ((and (featurep 'org-inlinetask)
6982 (org-inlinetask-at-task-p)
6983 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6984 (org-inlinetask-toggle-visibility))
6986 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6987 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6988 (save-excursion (move-beginning-of-line 1)
6989 (looking-at org-outline-regexp)))
6990 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6991 (org-cycle-internal-local))
6993 ;; From there: TAB emulation and template completion.
6994 (buffer-read-only (org-back-to-heading))
6996 ((run-hook-with-args-until-success
6997 'org-tab-after-check-for-cycling-hook))
6999 ((run-hook-with-args-until-success
7000 'org-tab-before-tab-emulation-hook))
7002 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7003 (or (not (bolp))
7004 (not (looking-at org-outline-regexp))))
7005 (call-interactively (global-key-binding "\t")))
7007 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7008 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7009 (or (and (eq org-cycle-emulate-tab 'white)
7010 (= (match-end 0) (point-at-eol)))
7011 (and (eq org-cycle-emulate-tab 'whitestart)
7012 (>= (match-end 0) pos))))
7014 (eq org-cycle-emulate-tab t))
7015 (call-interactively (global-key-binding "\t")))
7017 (t (save-excursion
7018 (org-back-to-heading)
7019 (org-cycle)))))))
7021 (defun org-cycle-internal-global ()
7022 "Do the global cycling action."
7023 ;; Hack to avoid display of messages for .org attachments in Gnus
7024 (let ((ga (string-match "\\*fontification" (buffer-name))))
7025 (cond
7026 ((and (eq last-command this-command)
7027 (eq org-cycle-global-status 'overview))
7028 ;; We just created the overview - now do table of contents
7029 ;; This can be slow in very large buffers, so indicate action
7030 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7031 (unless ga (org-unlogged-message "CONTENTS..."))
7032 (org-content)
7033 (unless ga (org-unlogged-message "CONTENTS...done"))
7034 (setq org-cycle-global-status 'contents)
7035 (run-hook-with-args 'org-cycle-hook 'contents))
7037 ((and (eq last-command this-command)
7038 (eq org-cycle-global-status 'contents))
7039 ;; We just showed the table of contents - now show everything
7040 (run-hook-with-args 'org-pre-cycle-hook 'all)
7041 (org-show-all '(headings blocks))
7042 (unless ga (org-unlogged-message "SHOW ALL"))
7043 (setq org-cycle-global-status 'all)
7044 (run-hook-with-args 'org-cycle-hook 'all))
7047 ;; Default action: go to overview
7048 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7049 (org-overview)
7050 (unless ga (org-unlogged-message "OVERVIEW"))
7051 (setq org-cycle-global-status 'overview)
7052 (run-hook-with-args 'org-cycle-hook 'overview)))))
7054 (defvar org-called-with-limited-levels nil
7055 "Non-nil when `org-with-limited-levels' is currently active.")
7057 (defun org-cycle-internal-local ()
7058 "Do the local cycling action."
7059 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7060 ;; First, determine end of headline (EOH), end of subtree or item
7061 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7062 (save-excursion
7063 (if (org-at-item-p)
7064 (progn
7065 (beginning-of-line)
7066 (setq struct (org-list-struct))
7067 (setq eoh (point-at-eol))
7068 (setq eos (org-list-get-item-end-before-blank (point) struct))
7069 (setq has-children (org-list-has-child-p (point) struct)))
7070 (org-back-to-heading)
7071 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7072 (setq eos (save-excursion (org-end-of-subtree t t)
7073 (when (bolp) (backward-char)) (point)))
7074 (setq has-children
7075 (or (save-excursion
7076 (let ((level (funcall outline-level)))
7077 (outline-next-heading)
7078 (and (org-at-heading-p t)
7079 (> (funcall outline-level) level))))
7080 (save-excursion
7081 (org-list-search-forward (org-item-beginning-re) eos t)))))
7082 ;; Determine end invisible part of buffer (EOL)
7083 (beginning-of-line 2)
7084 (while (and (not (eobp)) ;This is like `next-line'.
7085 (get-char-property (1- (point)) 'invisible))
7086 (goto-char (next-single-char-property-change (point) 'invisible))
7087 (and (eolp) (beginning-of-line 2)))
7088 (setq eol (point)))
7089 ;; Find out what to do next and set `this-command'
7090 (cond
7091 ((= eos eoh)
7092 ;; Nothing is hidden behind this heading
7093 (unless (org-before-first-heading-p)
7094 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7095 (org-unlogged-message "EMPTY ENTRY")
7096 (setq org-cycle-subtree-status nil)
7097 (save-excursion
7098 (goto-char eos)
7099 (outline-next-heading)
7100 (when (org-invisible-p) (org-flag-heading nil))))
7101 ((and (or (>= eol eos)
7102 (not (string-match "\\S-" (buffer-substring eol eos))))
7103 (or has-children
7104 (not (setq children-skipped
7105 org-cycle-skip-children-state-if-no-children))))
7106 ;; Entire subtree is hidden in one line: children view
7107 (unless (org-before-first-heading-p)
7108 (run-hook-with-args 'org-pre-cycle-hook 'children))
7109 (if (org-at-item-p)
7110 (org-list-set-item-visibility (point-at-bol) struct 'children)
7111 (org-show-entry)
7112 (org-with-limited-levels (org-show-children))
7113 (org-show-set-visibility 'canonical)
7114 ;; Fold every list in subtree to top-level items.
7115 (when (eq org-cycle-include-plain-lists 'integrate)
7116 (save-excursion
7117 (org-back-to-heading)
7118 (while (org-list-search-forward (org-item-beginning-re) eos t)
7119 (beginning-of-line 1)
7120 (let* ((struct (org-list-struct))
7121 (prevs (org-list-prevs-alist struct))
7122 (end (org-list-get-bottom-point struct)))
7123 (dolist (e (org-list-get-all-items (point) struct prevs))
7124 (org-list-set-item-visibility e struct 'folded))
7125 (goto-char (if (< end eos) end eos)))))))
7126 (org-unlogged-message "CHILDREN")
7127 (save-excursion
7128 (goto-char eos)
7129 (outline-next-heading)
7130 (when (org-invisible-p) (org-flag-heading nil)))
7131 (setq org-cycle-subtree-status 'children)
7132 (unless (org-before-first-heading-p)
7133 (run-hook-with-args 'org-cycle-hook 'children)))
7134 ((or children-skipped
7135 (and (eq last-command this-command)
7136 (eq org-cycle-subtree-status 'children)))
7137 ;; We just showed the children, or no children are there,
7138 ;; now show everything.
7139 (unless (org-before-first-heading-p)
7140 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7141 (org-flag-region eoh eos nil 'outline)
7142 (org-unlogged-message
7143 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7144 (setq org-cycle-subtree-status 'subtree)
7145 (unless (org-before-first-heading-p)
7146 (run-hook-with-args 'org-cycle-hook 'subtree)))
7148 ;; Default action: hide the subtree.
7149 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7150 (org-flag-region eoh eos t 'outline)
7151 (org-unlogged-message "FOLDED")
7152 (setq org-cycle-subtree-status 'folded)
7153 (unless (org-before-first-heading-p)
7154 (run-hook-with-args 'org-cycle-hook 'folded))))))
7156 ;;;###autoload
7157 (defun org-global-cycle (&optional arg)
7158 "Cycle the global visibility. For details see `org-cycle'.
7159 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7160 With a numeric prefix, show all headlines up to that level."
7161 (interactive "P")
7162 (let ((org-cycle-include-plain-lists
7163 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7164 (cond
7165 ((integerp arg)
7166 (org-show-all '(headings blocks))
7167 (outline-hide-sublevels arg)
7168 (setq org-cycle-global-status 'contents))
7169 ((equal arg '(4))
7170 (org-set-startup-visibility)
7171 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7173 (org-cycle '(4))))))
7175 (defun org-set-startup-visibility ()
7176 "Set the visibility required by startup options and properties."
7177 (cond
7178 ((eq org-startup-folded t)
7179 (org-overview))
7180 ((eq org-startup-folded 'content)
7181 (org-content))
7182 ((or (eq org-startup-folded 'showeverything)
7183 (eq org-startup-folded nil))
7184 (org-show-all)))
7185 (unless (eq org-startup-folded 'showeverything)
7186 (when org-hide-block-startup (org-hide-block-all))
7187 (org-set-visibility-according-to-property)
7188 (org-cycle-hide-archived-subtrees 'all)
7189 (org-cycle-hide-drawers 'all)
7190 (org-cycle-show-empty-lines t)))
7192 (defun org-set-visibility-according-to-property ()
7193 "Switch subtree visibilities according to :VISIBILITY: property."
7194 (interactive)
7195 (org-with-wide-buffer
7196 (goto-char (point-min))
7197 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7198 (if (not (org-at-property-p)) (outline-next-heading)
7199 (let ((state (match-string 3)))
7200 (save-excursion
7201 (org-back-to-heading t)
7202 (outline-hide-subtree)
7203 (org-reveal)
7204 (cond
7205 ((equal state "folded")
7206 (outline-hide-subtree))
7207 ((equal state "children")
7208 (org-show-hidden-entry)
7209 (org-show-children))
7210 ((equal state "content")
7211 (save-excursion
7212 (save-restriction
7213 (org-narrow-to-subtree)
7214 (org-content))))
7215 ((member state '("all" "showall"))
7216 (outline-show-subtree)))))))))
7218 (defun org-overview ()
7219 "Switch to overview mode, showing only top-level headlines.
7220 This shows all headlines with a level equal or greater than the level
7221 of the first headline in the buffer. This is important, because if the
7222 first headline is not level one, then (hide-sublevels 1) gives confusing
7223 results."
7224 (interactive)
7225 (save-excursion
7226 (let ((level
7227 (save-excursion
7228 (goto-char (point-min))
7229 (when (re-search-forward org-outline-regexp-bol nil t)
7230 (goto-char (match-beginning 0))
7231 (funcall outline-level)))))
7232 (and level (outline-hide-sublevels level)))))
7234 (defun org-content (&optional arg)
7235 "Show all headlines in the buffer, like a table of contents.
7236 With numerical argument N, show content up to level N."
7237 (interactive "P")
7238 (org-overview)
7239 (save-excursion
7240 ;; Visit all headings and show their offspring
7241 (and (integerp arg) (org-overview))
7242 (goto-char (point-max))
7243 (catch 'exit
7244 (while (and (progn (condition-case nil
7245 (outline-previous-visible-heading 1)
7246 (error (goto-char (point-min))))
7248 (looking-at org-outline-regexp))
7249 (if (integerp arg)
7250 (org-show-children (1- arg))
7251 (outline-show-branches))
7252 (when (bobp) (throw 'exit nil))))))
7254 (defun org-optimize-window-after-visibility-change (state)
7255 "Adjust the window after a change in outline visibility.
7256 This function is the default value of the hook `org-cycle-hook'."
7257 (when (get-buffer-window (current-buffer))
7258 (cond
7259 ((eq state 'content) nil)
7260 ((eq state 'all) nil)
7261 ((eq state 'folded) nil)
7262 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7263 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7265 (defun org-clean-visibility-after-subtree-move ()
7266 "Fix visibility issues after moving a subtree."
7267 ;; First, find a reasonable region to look at:
7268 ;; Start two siblings above, end three below
7269 (let* ((beg (save-excursion
7270 (and (org-get-last-sibling)
7271 (org-get-last-sibling))
7272 (point)))
7273 (end (save-excursion
7274 (and (org-get-next-sibling)
7275 (org-get-next-sibling)
7276 (org-get-next-sibling))
7277 (if (org-at-heading-p)
7278 (point-at-eol)
7279 (point))))
7280 (level (looking-at "\\*+"))
7281 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7282 (save-excursion
7283 (save-restriction
7284 (narrow-to-region beg end)
7285 (when re
7286 ;; Properly fold already folded siblings
7287 (goto-char (point-min))
7288 (while (re-search-forward re nil t)
7289 (when (and (not (org-invisible-p))
7290 (org-invisible-p (line-end-position)))
7291 (outline-hide-entry))))
7292 (org-cycle-hide-drawers 'all)
7293 (org-cycle-show-empty-lines 'overview)))))
7295 (defun org-cycle-show-empty-lines (state)
7296 "Show empty lines above all visible headlines.
7297 The region to be covered depends on STATE when called through
7298 `org-cycle-hook'. Lisp program can use t for STATE to get the
7299 entire buffer covered. Note that an empty line is only shown if there
7300 are at least `org-cycle-separator-lines' empty lines before the headline."
7301 (when (/= org-cycle-separator-lines 0)
7302 (save-excursion
7303 (let* ((n (abs org-cycle-separator-lines))
7304 (re (cond
7305 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7306 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7307 (t (let ((ns (number-to-string (- n 2))))
7308 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7309 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7310 beg end)
7311 (cond
7312 ((memq state '(overview contents t))
7313 (setq beg (point-min) end (point-max)))
7314 ((memq state '(children folded))
7315 (setq beg (point)
7316 end (progn (org-end-of-subtree t t)
7317 (line-beginning-position 2)))))
7318 (when beg
7319 (goto-char beg)
7320 (while (re-search-forward re end t)
7321 (unless (get-char-property (match-end 1) 'invisible)
7322 (let ((e (match-end 1))
7323 (b (if (>= org-cycle-separator-lines 0)
7324 (match-beginning 1)
7325 (save-excursion
7326 (goto-char (match-beginning 0))
7327 (skip-chars-backward " \t\n")
7328 (line-end-position)))))
7329 (org-flag-region b e nil 'outline))))))))
7330 ;; Never hide empty lines at the end of the file.
7331 (save-excursion
7332 (goto-char (point-max))
7333 (outline-previous-heading)
7334 (outline-end-of-heading)
7335 (when (and (looking-at "[ \t\n]+")
7336 (= (match-end 0) (point-max)))
7337 (org-flag-region (point) (match-end 0) nil 'outline))))
7339 ;;;; Reveal point location
7341 (defun org-show-context (&optional key)
7342 "Make sure point and context are visible.
7343 Optional argument KEY, when non-nil, is a symbol. See
7344 `org-show-context-detail' for allowed values and how much is to
7345 be shown."
7346 (org-show-set-visibility
7347 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7348 ((cdr (assq key org-show-context-detail)))
7349 (t (cdr (assq 'default org-show-context-detail))))))
7351 (defun org-show-set-visibility (detail)
7352 "Set visibility around point according to DETAIL.
7353 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7354 `tree', `canonical' or t. See `org-show-context-detail' for more
7355 information."
7356 ;; Show current heading and possibly its entry, following headline
7357 ;; or all children.
7358 (if (and (org-at-heading-p) (not (eq detail 'local)))
7359 (org-flag-heading nil)
7360 (org-show-entry)
7361 ;; If point is hidden within a drawer or a block, make sure to
7362 ;; expose it.
7363 (dolist (o (overlays-at (point)))
7364 (when (memq (overlay-get o 'invisible)
7365 '(org-hide-block org-hide-drawer outline))
7366 (delete-overlay o)))
7367 (unless (org-before-first-heading-p)
7368 (org-with-limited-levels
7369 (cl-case detail
7370 ((tree canonical t) (org-show-children))
7371 ((nil minimal ancestors))
7372 (t (save-excursion
7373 (outline-next-heading)
7374 (org-flag-heading nil)))))))
7375 ;; Show all siblings.
7376 (when (eq detail 'lineage) (org-show-siblings))
7377 ;; Show ancestors, possibly with their children.
7378 (when (memq detail '(ancestors lineage tree canonical t))
7379 (save-excursion
7380 (while (org-up-heading-safe)
7381 (org-flag-heading nil)
7382 (when (memq detail '(canonical t)) (org-show-entry))
7383 (when (memq detail '(tree canonical t)) (org-show-children))))))
7385 (defvar org-reveal-start-hook nil
7386 "Hook run before revealing a location.")
7388 (defun org-reveal (&optional siblings)
7389 "Show current entry, hierarchy above it, and the following headline.
7391 This can be used to show a consistent set of context around
7392 locations exposed with `org-show-context'.
7394 With optional argument SIBLINGS, on each level of the hierarchy all
7395 siblings are shown. This repairs the tree structure to what it would
7396 look like when opened with hierarchical calls to `org-cycle'.
7398 With a \\[universal-argument] \\[universal-argument] prefix, \
7399 go to the parent and show the entire tree."
7400 (interactive "P")
7401 (run-hooks 'org-reveal-start-hook)
7402 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7403 ((equal siblings '(16))
7404 (save-excursion
7405 (when (org-up-heading-safe)
7406 (org-show-subtree)
7407 (run-hook-with-args 'org-cycle-hook 'subtree))))
7408 (t (org-show-set-visibility 'lineage))))
7411 ;;; Indirect buffer display of subtrees
7413 (defvar org-indirect-dedicated-frame nil
7414 "This is the frame being used for indirect tree display.")
7415 (defvar org-last-indirect-buffer nil)
7417 (defun org-tree-to-indirect-buffer (&optional arg)
7418 "Create indirect buffer and narrow it to current subtree.
7420 With a numerical prefix ARG, go up to this level and then take that tree.
7421 If ARG is negative, go up that many levels.
7423 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7424 indirect buffer previously made with this command, to avoid proliferation of
7425 indirect buffers. However, when you call the command with a \
7426 `\\[universal-argument]' prefix, or
7427 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7428 so that you can work with several indirect buffers at the same time. If
7429 `org-indirect-buffer-display' is `dedicated-frame', the \
7430 `\\[universal-argument]' prefix also
7431 requests that a new frame be made for the new buffer, so that the dedicated
7432 frame is not changed."
7433 (interactive "P")
7434 (let ((cbuf (current-buffer))
7435 (cwin (selected-window))
7436 (pos (point))
7437 beg end level heading ibuf)
7438 (save-excursion
7439 (org-back-to-heading t)
7440 (when (numberp arg)
7441 (setq level (org-outline-level))
7442 (when (< arg 0) (setq arg (+ level arg)))
7443 (while (> (setq level (org-outline-level)) arg)
7444 (org-up-heading-safe)))
7445 (setq beg (point)
7446 heading (org-get-heading 'no-tags))
7447 (org-end-of-subtree t t)
7448 (when (org-at-heading-p) (backward-char 1))
7449 (setq end (point)))
7450 (when (and (buffer-live-p org-last-indirect-buffer)
7451 (not (eq org-indirect-buffer-display 'new-frame))
7452 (not arg))
7453 (kill-buffer org-last-indirect-buffer))
7454 (setq ibuf (org-get-indirect-buffer cbuf heading)
7455 org-last-indirect-buffer ibuf)
7456 (cond
7457 ((or (eq org-indirect-buffer-display 'new-frame)
7458 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7459 (select-frame (make-frame))
7460 (delete-other-windows)
7461 (pop-to-buffer-same-window ibuf)
7462 (org-set-frame-title heading))
7463 ((eq org-indirect-buffer-display 'dedicated-frame)
7464 (raise-frame
7465 (select-frame (or (and org-indirect-dedicated-frame
7466 (frame-live-p org-indirect-dedicated-frame)
7467 org-indirect-dedicated-frame)
7468 (setq org-indirect-dedicated-frame (make-frame)))))
7469 (delete-other-windows)
7470 (pop-to-buffer-same-window ibuf)
7471 (org-set-frame-title (concat "Indirect: " heading)))
7472 ((eq org-indirect-buffer-display 'current-window)
7473 (pop-to-buffer-same-window ibuf))
7474 ((eq org-indirect-buffer-display 'other-window)
7475 (pop-to-buffer ibuf))
7476 (t (error "Invalid value")))
7477 (narrow-to-region beg end)
7478 (org-show-all '(headings blocks))
7479 (goto-char pos)
7480 (run-hook-with-args 'org-cycle-hook 'all)
7481 (and (window-live-p cwin) (select-window cwin))))
7483 (defun org-get-indirect-buffer (&optional buffer heading)
7484 (setq buffer (or buffer (current-buffer)))
7485 (let ((n 1) (base (buffer-name buffer)) bname)
7486 (while (buffer-live-p
7487 (get-buffer
7488 (setq bname
7489 (concat base "-"
7490 (if heading (concat heading "-" (number-to-string n))
7491 (number-to-string n))))))
7492 (setq n (1+ n)))
7493 (condition-case nil
7494 (make-indirect-buffer buffer bname 'clone)
7495 (error (make-indirect-buffer buffer bname)))))
7497 (defun org-set-frame-title (title)
7498 "Set the title of the current frame to the string TITLE."
7499 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7501 ;;;; Structure editing
7503 ;;; Inserting headlines
7505 (defun org--line-empty-p (n)
7506 "Is the Nth next line empty?
7508 Counts the current line as N = 1 and the previous line as N = 0;
7509 see `beginning-of-line'."
7510 (save-excursion
7511 (and (not (bobp))
7512 (or (beginning-of-line n) t)
7513 (save-match-data
7514 (looking-at "[ \t]*$")))))
7516 (defun org-previous-line-empty-p ()
7517 "Is the previous line a blank line?
7518 When NEXT is non-nil, check the next line instead."
7519 (org--line-empty-p 0))
7521 (defun org-next-line-empty-p ()
7522 "Is the previous line a blank line?
7523 When NEXT is non-nil, check the next line instead."
7524 (org--line-empty-p 2))
7526 (defun org--blank-before-heading-p (&optional parent)
7527 "Non-nil when an empty line should precede a new heading here.
7528 When optional argument PARENT is non-nil, consider parent
7529 headline instead of current one."
7530 (pcase (assq 'heading org-blank-before-new-entry)
7531 (`(heading . auto)
7532 (save-excursion
7533 (org-with-limited-levels
7534 (unless (and (org-before-first-heading-p)
7535 (not (outline-next-heading)))
7536 (org-back-to-heading t)
7537 (when parent (org-up-heading-safe))
7538 (cond ((not (bobp))
7539 (org-previous-line-empty-p))
7540 ((outline-next-heading)
7541 (org-previous-line-empty-p))
7542 ;; Ignore trailing spaces on last buffer line.
7543 ((progn (skip-chars-backward " \t") (bolp))
7544 (org-previous-line-empty-p))
7545 (t nil))))))
7546 (`(heading . ,value) value)
7547 (_ nil)))
7549 (defun org-insert-heading (&optional arg invisible-ok top)
7550 "Insert a new heading or an item with the same depth at point.
7552 If point is at the beginning of a heading, insert a new heading
7553 or a new headline above the current one. When at the beginning
7554 of a regular line of text, turn it into a heading.
7556 If point is in the middle of a line, split it and create a new
7557 headline with the text in the current line after point (see
7558 `org-M-RET-may-split-line' on how to modify this behavior). As
7559 a special case, on a headline, splitting can only happen on the
7560 title itself. E.g., this excludes breaking stars or tags.
7562 With a `\\[universal-argument]' prefix, set \
7563 `org-insert-heading-respect-content' to
7564 a non-nil value for the duration of the command. This forces the
7565 insertion of a heading after the current subtree, independently
7566 on the location of point.
7568 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7569 insert the heading at the end of the tree
7570 above the current heading. For example, if point is within a
7571 2nd-level heading, then it will insert a 2nd-level heading at
7572 the end of the 1st-level parent subtree.
7574 When INVISIBLE-OK is set, stop at invisible headlines when going
7575 back. This is important for non-interactive uses of the
7576 command.
7578 When optional argument TOP is non-nil, insert a level 1 heading,
7579 unconditionally."
7580 (interactive "P")
7581 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7582 (level (org-current-level))
7583 (stars (make-string (if (and level (not top)) level 1) ?*)))
7584 (cond
7585 ((or org-insert-heading-respect-content
7586 (member arg '((4) (16)))
7587 (and (not invisible-ok)
7588 (invisible-p (max (1- (point)) (point-min)))))
7589 ;; Position point at the location of insertion.
7590 (if (not level) ;before first headline
7591 (org-with-limited-levels (outline-next-heading))
7592 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7593 ;; is nil.
7594 (org-with-limited-levels (org-back-to-heading invisible-ok))
7595 (cond ((equal arg '(16))
7596 (org-up-heading-safe)
7597 (org-end-of-subtree t t))
7599 (org-end-of-subtree t t))))
7600 (unless (bolp) (insert "\n")) ;ensure final newline
7601 (unless (and blank? (org-previous-line-empty-p))
7602 (org-N-empty-lines-before-current (if blank? 1 0)))
7603 (insert stars " \n")
7604 (forward-char -1))
7605 ;; At a headline...
7606 ((org-at-heading-p)
7607 (cond ((bolp)
7608 (when blank? (save-excursion (insert "\n")))
7609 (save-excursion (insert stars " \n"))
7610 (unless (and blank? (org-previous-line-empty-p))
7611 (org-N-empty-lines-before-current (if blank? 1 0)))
7612 (end-of-line))
7613 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7614 (org-match-line org-complex-heading-regexp)
7615 (org-pos-in-match-range (point) 4))
7616 ;; Grab the text that should moved to the new headline.
7617 ;; Preserve tags.
7618 (let ((split (delete-and-extract-region (point) (match-end 4))))
7619 (if (looking-at "[ \t]*$") (replace-match "")
7620 (org-align-tags))
7621 (end-of-line)
7622 (when blank? (insert "\n"))
7623 (insert "\n" stars " ")
7624 (when (org-string-nw-p split) (insert split))
7625 (when (eobp) (save-excursion (insert "\n")))))
7627 (end-of-line)
7628 (when blank? (insert "\n"))
7629 (insert "\n" stars " ")
7630 (when (eobp) (save-excursion (insert "\n"))))))
7631 ;; On regular text, turn line into a headline or split, if
7632 ;; appropriate.
7633 ((bolp)
7634 (insert stars " ")
7635 (unless (and blank? (org-previous-line-empty-p))
7636 (org-N-empty-lines-before-current (if blank? 1 0))))
7638 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7639 (end-of-line))
7640 (insert "\n" stars " ")
7641 (unless (and blank? (org-previous-line-empty-p))
7642 (org-N-empty-lines-before-current (if blank? 1 0))))))
7643 (run-hooks 'org-insert-heading-hook))
7645 (defun org-N-empty-lines-before-current (n)
7646 "Make the number of empty lines before current exactly N.
7647 So this will delete or add empty lines."
7648 (let ((column (current-column)))
7649 (beginning-of-line)
7650 (unless (bobp)
7651 (let ((start (save-excursion
7652 (skip-chars-backward " \r\t\n")
7653 (line-end-position))))
7654 (delete-region start (line-end-position 0))))
7655 (insert (make-string n ?\n))
7656 (move-to-column column)))
7658 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7659 "Return the heading of the current entry, without the stars.
7660 When NO-TAGS is non-nil, don't include tags.
7661 When NO-TODO is non-nil, don't include TODO keywords.
7662 When NO-PRIORITY is non-nil, don't include priority cookie.
7663 When NO-COMMENT is non-nil, don't include COMMENT string."
7664 (save-excursion
7665 (org-back-to-heading t)
7666 (let ((case-fold-search nil))
7667 (looking-at org-complex-heading-regexp)
7668 (let ((todo (and (not no-todo) (match-string 2)))
7669 (priority (and (not no-priority) (match-string 3)))
7670 (headline (pcase (match-string 4)
7671 (`nil "")
7672 ((and (guard no-comment) h)
7673 (replace-regexp-in-string
7674 (eval-when-compile
7675 (format "\\`%s[ \t]+" org-comment-string))
7676 "" h))
7677 (h h)))
7678 (tags (and (not no-tags) (match-string 5))))
7679 (mapconcat #'identity
7680 (delq nil (list todo priority headline tags))
7681 " ")))))
7683 (defun org-heading-components ()
7684 "Return the components of the current heading.
7685 This is a list with the following elements:
7686 - the level as an integer
7687 - the reduced level, different if `org-odd-levels-only' is set.
7688 - the TODO keyword, or nil
7689 - the priority character, like ?A, or nil if no priority is given
7690 - the headline text itself, or the tags string if no headline text
7691 - the tags string, or nil."
7692 (save-excursion
7693 (org-back-to-heading t)
7694 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7695 (list (length (match-string 1))
7696 (org-reduced-level (length (match-string 1)))
7697 (match-string-no-properties 2)
7698 (and (match-end 3) (aref (match-string 3) 2))
7699 (match-string-no-properties 4)
7700 (match-string-no-properties 5)))))
7702 (defun org-get-entry ()
7703 "Get the entry text, after heading, entire subtree."
7704 (save-excursion
7705 (org-back-to-heading t)
7706 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7708 (defun org-edit-headline (&optional heading)
7709 "Edit the current headline.
7710 Set it to HEADING when provided."
7711 (interactive)
7712 (org-with-wide-buffer
7713 (org-back-to-heading t)
7714 (let ((case-fold-search nil))
7715 (when (looking-at org-complex-heading-regexp)
7716 (let* ((old (match-string-no-properties 4))
7717 (new (save-match-data
7718 (org-trim (or heading (read-string "Edit: " old))))))
7719 (unless (equal old new)
7720 (if old (replace-match new t t nil 4)
7721 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7722 (insert " " new))
7723 (org-align-tags)
7724 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7726 (defun org-insert-heading-after-current ()
7727 "Insert a new heading with same level as current, after current subtree."
7728 (interactive)
7729 (org-back-to-heading)
7730 (org-insert-heading)
7731 (org-move-subtree-down)
7732 (end-of-line 1))
7734 (defun org-insert-heading-respect-content (&optional invisible-ok)
7735 "Insert heading with `org-insert-heading-respect-content' set to t."
7736 (interactive)
7737 (org-insert-heading '(4) invisible-ok))
7739 (defun org-insert-todo-heading-respect-content (&optional force-state)
7740 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7741 (interactive)
7742 (org-insert-todo-heading force-state '(4)))
7744 (defun org-insert-todo-heading (arg &optional force-heading)
7745 "Insert a new heading with the same level and TODO state as current heading.
7747 If the heading has no TODO state, or if the state is DONE, use
7748 the first state (TODO by default). Also with one prefix arg,
7749 force first state. With two prefix args, force inserting at the
7750 end of the parent subtree.
7752 When called at a plain list item, insert a new item with an
7753 unchecked check box."
7754 (interactive "P")
7755 (when (or force-heading (not (org-insert-item 'checkbox)))
7756 (org-insert-heading (or (and (equal arg '(16)) '(16))
7757 force-heading))
7758 (save-excursion
7759 (org-forward-heading-same-level -1)
7760 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7761 (let* ((new-mark-x
7762 (if (or (equal arg '(4))
7763 (not (match-beginning 2))
7764 (member (match-string 2) org-done-keywords))
7765 (car org-todo-keywords-1)
7766 (match-string 2)))
7767 (new-mark
7769 (run-hook-with-args-until-success
7770 'org-todo-get-default-hook new-mark-x nil)
7771 new-mark-x)))
7772 (beginning-of-line 1)
7773 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7774 (if org-treat-insert-todo-heading-as-state-change
7775 (org-todo new-mark)
7776 (insert new-mark " "))))
7777 (when org-provide-todo-statistics
7778 (org-update-parent-todo-statistics))))
7780 (defun org-insert-subheading (arg)
7781 "Insert a new subheading and demote it.
7782 Works for outline headings and for plain lists alike."
7783 (interactive "P")
7784 (org-insert-heading arg)
7785 (cond
7786 ((org-at-heading-p) (org-do-demote))
7787 ((org-at-item-p) (org-indent-item))))
7789 (defun org-insert-todo-subheading (arg)
7790 "Insert a new subheading with TODO keyword or checkbox and demote it.
7791 Works for outline headings and for plain lists alike."
7792 (interactive "P")
7793 (org-insert-todo-heading arg)
7794 (cond
7795 ((org-at-heading-p) (org-do-demote))
7796 ((org-at-item-p) (org-indent-item))))
7798 ;;; Promotion and Demotion
7800 (defvar org-after-demote-entry-hook nil
7801 "Hook run after an entry has been demoted.
7802 The cursor will be at the beginning of the entry.
7803 When a subtree is being demoted, the hook will be called for each node.")
7805 (defvar org-after-promote-entry-hook nil
7806 "Hook run after an entry has been promoted.
7807 The cursor will be at the beginning of the entry.
7808 When a subtree is being promoted, the hook will be called for each node.")
7810 (defun org-promote-subtree ()
7811 "Promote the entire subtree.
7812 See also `org-promote'."
7813 (interactive)
7814 (save-excursion
7815 (org-with-limited-levels (org-map-tree 'org-promote)))
7816 (org-fix-position-after-promote))
7818 (defun org-demote-subtree ()
7819 "Demote the entire subtree.
7820 See `org-demote' and `org-promote'."
7821 (interactive)
7822 (save-excursion
7823 (org-with-limited-levels (org-map-tree 'org-demote)))
7824 (org-fix-position-after-promote))
7826 (defun org-do-promote ()
7827 "Promote the current heading higher up the tree.
7828 If the region is active in `transient-mark-mode', promote all
7829 headings in the region."
7830 (interactive)
7831 (save-excursion
7832 (if (org-region-active-p)
7833 (org-map-region 'org-promote (region-beginning) (region-end))
7834 (org-promote)))
7835 (org-fix-position-after-promote))
7837 (defun org-do-demote ()
7838 "Demote the current heading lower down the tree.
7839 If the region is active in `transient-mark-mode', demote all
7840 headings in the region."
7841 (interactive)
7842 (save-excursion
7843 (if (org-region-active-p)
7844 (org-map-region 'org-demote (region-beginning) (region-end))
7845 (org-demote)))
7846 (org-fix-position-after-promote))
7848 (defun org-fix-position-after-promote ()
7849 "Fix cursor position and indentation after demoting/promoting."
7850 (let ((pos (point)))
7851 (when (save-excursion
7852 (beginning-of-line)
7853 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7854 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7855 (cond ((eobp) (insert " "))
7856 ((eolp) (insert " "))
7857 ((equal (char-after) ?\s) (forward-char 1))))))
7859 (defun org-current-level ()
7860 "Return the level of the current entry, or nil if before the first headline.
7861 The level is the number of stars at the beginning of the
7862 headline. Use `org-reduced-level' to remove the effect of
7863 `org-odd-levels'. Unlike to `org-outline-level', this function
7864 ignores inlinetasks."
7865 (let ((level (org-with-limited-levels (org-outline-level))))
7866 (and (> level 0) level)))
7868 (defun org-get-previous-line-level ()
7869 "Return the outline depth of the last headline before the current line.
7870 Returns 0 for the first headline in the buffer, and nil if before the
7871 first headline."
7872 (and (org-current-level)
7873 (or (and (/= (line-beginning-position) (point-min))
7874 (save-excursion (beginning-of-line 0) (org-current-level)))
7875 0)))
7877 (defun org-reduced-level (l)
7878 "Compute the effective level of a heading.
7879 This takes into account the setting of `org-odd-levels-only'."
7880 (cond
7881 ((zerop l) 0)
7882 (org-odd-levels-only (1+ (floor (/ l 2))))
7883 (t l)))
7885 (defun org-level-increment ()
7886 "Return the number of stars that will be added or removed at a
7887 time to headlines when structure editing, based on the value of
7888 `org-odd-levels-only'."
7889 (if org-odd-levels-only 2 1))
7891 (defun org-get-valid-level (level &optional change)
7892 "Rectify a level change under the influence of `org-odd-levels-only'.
7893 LEVEL is a current level, CHANGE is by how much the level should
7894 be modified. Even if CHANGE is nil, LEVEL may be returned
7895 modified because even level numbers will become the next higher
7896 odd number. Returns values greater than 0."
7897 (if org-odd-levels-only
7898 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7899 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7900 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7901 (max 1 (+ level (or change 0)))))
7903 (defun org-promote ()
7904 "Promote the current heading higher up the tree."
7905 (org-with-wide-buffer
7906 (org-back-to-heading t)
7907 (let* ((after-change-functions (remq 'flyspell-after-change-function
7908 after-change-functions))
7909 (level (save-match-data (funcall outline-level)))
7910 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7911 (diff (abs (- level (length up-head) -1))))
7912 (cond
7913 ((and (= level 1) org-allow-promoting-top-level-subtree)
7914 (replace-match "# " nil t))
7915 ((= level 1)
7916 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7917 (t (replace-match up-head nil t)))
7918 (unless (= level 1)
7919 (when org-auto-align-tags (org-align-tags))
7920 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7921 (run-hooks 'org-after-promote-entry-hook))))
7923 (defun org-demote ()
7924 "Demote the current heading lower down the tree."
7925 (org-with-wide-buffer
7926 (org-back-to-heading t)
7927 (let* ((after-change-functions (remq 'flyspell-after-change-function
7928 after-change-functions))
7929 (level (save-match-data (funcall outline-level)))
7930 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7931 (diff (abs (- level (length down-head) -1))))
7932 (replace-match down-head nil t)
7933 (when org-auto-align-tags (org-align-tags))
7934 (when org-adapt-indentation (org-fixup-indentation diff))
7935 (run-hooks 'org-after-demote-entry-hook))))
7937 (defun org-cycle-level ()
7938 "Cycle the level of an empty headline through possible states.
7939 This goes first to child, then to parent, level, then up the hierarchy.
7940 After top level, it switches back to sibling level."
7941 (interactive)
7942 (let ((org-adapt-indentation nil))
7943 (when (org-point-at-end-of-empty-headline)
7944 (setq this-command 'org-cycle-level) ; Only needed for caching
7945 (let ((cur-level (org-current-level))
7946 (prev-level (org-get-previous-line-level)))
7947 (cond
7948 ;; If first headline in file, promote to top-level.
7949 ((= prev-level 0)
7950 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7951 do (org-do-promote)))
7952 ;; If same level as prev, demote one.
7953 ((= prev-level cur-level)
7954 (org-do-demote))
7955 ;; If parent is top-level, promote to top level if not already.
7956 ((= prev-level 1)
7957 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7958 do (org-do-promote)))
7959 ;; If top-level, return to prev-level.
7960 ((= cur-level 1)
7961 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7962 do (org-do-demote)))
7963 ;; If less than prev-level, promote one.
7964 ((< cur-level prev-level)
7965 (org-do-promote))
7966 ;; If deeper than prev-level, promote until higher than
7967 ;; prev-level.
7968 ((> cur-level prev-level)
7969 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7970 do (org-do-promote))))
7971 t))))
7973 (defun org-map-tree (fun)
7974 "Call FUN for every heading underneath the current one."
7975 (org-back-to-heading t)
7976 (let ((level (funcall outline-level)))
7977 (save-excursion
7978 (funcall fun)
7979 (while (and (progn
7980 (outline-next-heading)
7981 (> (funcall outline-level) level))
7982 (not (eobp)))
7983 (funcall fun)))))
7985 (defun org-map-region (fun beg end)
7986 "Call FUN for every heading between BEG and END."
7987 (let ((org-ignore-region t))
7988 (save-excursion
7989 (setq end (copy-marker end))
7990 (goto-char beg)
7991 (when (and (re-search-forward org-outline-regexp-bol nil t)
7992 (< (point) end))
7993 (funcall fun))
7994 (while (and (progn
7995 (outline-next-heading)
7996 (< (point) end))
7997 (not (eobp)))
7998 (funcall fun)))))
8000 (defun org-fixup-indentation (diff)
8001 "Change the indentation in the current entry by DIFF.
8003 DIFF is an integer. Indentation is done according to the
8004 following rules:
8006 - Planning information and property drawers are always indented
8007 according to the new level of the headline;
8009 - Footnote definitions and their contents are ignored;
8011 - Inlinetasks' boundaries are not shifted;
8013 - Empty lines are ignored;
8015 - Other lines' indentation are shifted by DIFF columns, unless
8016 it would introduce a structural change in the document, in
8017 which case no shifting is done at all.
8019 Assume point is at a heading or an inlinetask beginning."
8020 (org-with-wide-buffer
8021 (narrow-to-region (line-beginning-position)
8022 (save-excursion
8023 (if (org-with-limited-levels (org-at-heading-p))
8024 (org-with-limited-levels (outline-next-heading))
8025 (org-inlinetask-goto-end))
8026 (point)))
8027 (forward-line)
8028 ;; Indent properly planning info and property drawer.
8029 (when (looking-at-p org-planning-line-re)
8030 (org-indent-line)
8031 (forward-line))
8032 (when (looking-at org-property-drawer-re)
8033 (goto-char (match-end 0))
8034 (forward-line)
8035 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8036 (catch 'no-shift
8037 (when (zerop diff) (throw 'no-shift nil))
8038 ;; If DIFF is negative, first check if a shift is possible at all
8039 ;; (e.g., it doesn't break structure). This can only happen if
8040 ;; some contents are not properly indented.
8041 (let ((case-fold-search t))
8042 (when (< diff 0)
8043 (let ((diff (- diff))
8044 (forbidden-re (concat org-outline-regexp
8045 "\\|"
8046 (substring org-footnote-definition-re 1))))
8047 (save-excursion
8048 (while (not (eobp))
8049 (cond
8050 ((looking-at-p "[ \t]*$") (forward-line))
8051 ((and (looking-at-p org-footnote-definition-re)
8052 (let ((e (org-element-at-point)))
8053 (and (eq (org-element-type e) 'footnote-definition)
8054 (goto-char (org-element-property :end e))))))
8055 ((looking-at-p org-outline-regexp) (forward-line))
8056 ;; Give up if shifting would move before column 0 or
8057 ;; if it would introduce a headline or a footnote
8058 ;; definition.
8060 (skip-chars-forward " \t")
8061 (let ((ind (current-column)))
8062 (when (or (< ind diff)
8063 (and (= ind diff) (looking-at-p forbidden-re)))
8064 (throw 'no-shift nil)))
8065 ;; Ignore contents of example blocks and source
8066 ;; blocks if their indentation is meant to be
8067 ;; preserved. Jump to block's closing line.
8068 (beginning-of-line)
8069 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8070 (let ((e (org-element-at-point)))
8071 (and (memq (org-element-type e)
8072 '(example-block src-block))
8073 (or org-src-preserve-indentation
8074 (org-element-property :preserve-indent e))
8075 (goto-char (org-element-property :end e))
8076 (progn (skip-chars-backward " \r\t\n")
8077 (beginning-of-line)
8078 t))))
8079 (forward-line))))))))
8080 ;; Shift lines but footnote definitions, inlinetasks boundaries
8081 ;; by DIFF. Also skip contents of source or example blocks
8082 ;; when indentation is meant to be preserved.
8083 (while (not (eobp))
8084 (cond
8085 ((and (looking-at-p org-footnote-definition-re)
8086 (let ((e (org-element-at-point)))
8087 (and (eq (org-element-type e) 'footnote-definition)
8088 (goto-char (org-element-property :end e))))))
8089 ((looking-at-p org-outline-regexp) (forward-line))
8090 ((looking-at-p "[ \t]*$") (forward-line))
8092 (indent-line-to (+ (org-get-indentation) diff))
8093 (beginning-of-line)
8094 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8095 (let ((e (org-element-at-point)))
8096 (and (memq (org-element-type e)
8097 '(example-block src-block))
8098 (or org-src-preserve-indentation
8099 (org-element-property :preserve-indent e))
8100 (goto-char (org-element-property :end e))
8101 (progn (skip-chars-backward " \r\t\n")
8102 (beginning-of-line)
8103 t))))
8104 (forward-line)))))))))
8106 (defun org-convert-to-odd-levels ()
8107 "Convert an Org file with all levels allowed to one with odd levels.
8108 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8109 level 5 etc."
8110 (interactive)
8111 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8112 (let ((outline-level 'org-outline-level)
8113 (org-odd-levels-only nil) n)
8114 (save-excursion
8115 (goto-char (point-min))
8116 (while (re-search-forward "^\\*\\*+ " nil t)
8117 (setq n (- (length (match-string 0)) 2))
8118 (while (>= (setq n (1- n)) 0)
8119 (org-demote))
8120 (end-of-line 1))))))
8122 (defun org-convert-to-oddeven-levels ()
8123 "Convert an Org file with only odd levels to one with odd/even levels.
8124 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8125 file contains a section with an even level, conversion would
8126 destroy the structure of the file. An error is signaled in this
8127 case."
8128 (interactive)
8129 (goto-char (point-min))
8130 ;; First check if there are no even levels
8131 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8132 (org-show-set-visibility 'canonical)
8133 (error "Not all levels are odd in this file. Conversion not possible"))
8134 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8135 (let ((outline-regexp org-outline-regexp)
8136 (outline-level 'org-outline-level)
8137 (org-odd-levels-only nil) n)
8138 (save-excursion
8139 (goto-char (point-min))
8140 (while (re-search-forward "^\\*\\*+ " nil t)
8141 (setq n (/ (1- (length (match-string 0))) 2))
8142 (while (>= (setq n (1- n)) 0)
8143 (org-promote))
8144 (end-of-line 1))))))
8146 (defun org-tr-level (n)
8147 "Make N odd if required."
8148 (if org-odd-levels-only (1+ (/ n 2)) n))
8150 ;;; Vertical tree motion, cutting and pasting of subtrees
8152 (defun org-move-subtree-up (&optional arg)
8153 "Move the current subtree up past ARG headlines of the same level."
8154 (interactive "p")
8155 (org-move-subtree-down (- (prefix-numeric-value arg))))
8157 (defun org-move-subtree-down (&optional arg)
8158 "Move the current subtree down past ARG headlines of the same level."
8159 (interactive "p")
8160 (setq arg (prefix-numeric-value arg))
8161 (org-preserve-local-variables
8162 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8163 'org-get-last-sibling))
8164 (ins-point (make-marker))
8165 (cnt (abs arg))
8166 (col (current-column))
8167 beg end txt folded)
8168 ;; Select the tree
8169 (org-back-to-heading)
8170 (setq beg (point))
8171 (save-match-data
8172 (save-excursion (outline-end-of-heading)
8173 (setq folded (org-invisible-p)))
8174 (progn (org-end-of-subtree nil t)
8175 (unless (eobp) (backward-char))))
8176 (outline-next-heading)
8177 (setq end (point))
8178 (goto-char beg)
8179 ;; Find insertion point, with error handling
8180 (while (> cnt 0)
8181 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8182 (goto-char beg)
8183 (user-error "Cannot move past superior level or buffer limit"))
8184 (setq cnt (1- cnt)))
8185 (when (> arg 0)
8186 ;; Moving forward - still need to move over subtree
8187 (org-end-of-subtree t t)
8188 (save-excursion
8189 (org-back-over-empty-lines)
8190 (or (bolp) (newline))))
8191 (move-marker ins-point (point))
8192 (setq txt (buffer-substring beg end))
8193 (org-save-markers-in-region beg end)
8194 (delete-region beg end)
8195 (org-remove-empty-overlays-at beg)
8196 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8197 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8198 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8199 (let ((bbb (point)))
8200 (insert-before-markers txt)
8201 (org-reinstall-markers-in-region bbb)
8202 (move-marker ins-point bbb))
8203 (or (bolp) (insert "\n"))
8204 (goto-char ins-point)
8205 (org-skip-whitespace)
8206 (move-marker ins-point nil)
8207 (if folded
8208 (outline-hide-subtree)
8209 (org-show-entry)
8210 (org-show-children))
8211 (org-clean-visibility-after-subtree-move)
8212 ;; move back to the initial column we were at
8213 (move-to-column col))))
8215 (defvar org-subtree-clip ""
8216 "Clipboard for cut and paste of subtrees.
8217 This is actually only a copy of the kill, because we use the normal kill
8218 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8220 (defvar org-subtree-clip-folded nil
8221 "Was the last copied subtree folded?
8222 This is used to fold the tree back after pasting.")
8224 (defun org-cut-subtree (&optional n)
8225 "Cut the current subtree into the clipboard.
8226 With prefix arg N, cut this many sequential subtrees.
8227 This is a short-hand for marking the subtree and then cutting it."
8228 (interactive "p")
8229 (org-copy-subtree n 'cut))
8231 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8232 "Copy the current subtree into the clipboard.
8233 With prefix arg N, copy this many sequential subtrees.
8234 This is a short-hand for marking the subtree and then copying it.
8235 If CUT is non-nil, actually cut the subtree.
8236 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8237 of some markers in the region, even if CUT is non-nil. This is
8238 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8239 (interactive "p")
8240 (org-preserve-local-variables
8241 (let (beg end folded (beg0 (point)))
8242 (if (called-interactively-p 'any)
8243 (org-back-to-heading nil) ; take what looks like a subtree
8244 (org-back-to-heading t)) ; take what is really there
8245 (setq beg (point))
8246 (skip-chars-forward " \t\r\n")
8247 (save-match-data
8248 (if nosubtrees
8249 (outline-next-heading)
8250 (save-excursion (outline-end-of-heading)
8251 (setq folded (org-invisible-p)))
8252 (ignore-errors (org-forward-heading-same-level (1- n) t))
8253 (org-end-of-subtree t t)))
8254 ;; Include the end of an inlinetask
8255 (when (and (featurep 'org-inlinetask)
8256 (looking-at-p (concat (org-inlinetask-outline-regexp)
8257 "END[ \t]*$")))
8258 (end-of-line))
8259 (setq end (point))
8260 (goto-char beg0)
8261 (when (> end beg)
8262 (setq org-subtree-clip-folded folded)
8263 (when (or cut force-store-markers)
8264 (org-save-markers-in-region beg end))
8265 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8266 (setq org-subtree-clip (current-kill 0))
8267 (message "%s: Subtree(s) with %d characters"
8268 (if cut "Cut" "Copied")
8269 (length org-subtree-clip))))))
8271 (defun org-paste-subtree (&optional level tree for-yank remove)
8272 "Paste the clipboard as a subtree, with modification of headline level.
8274 The entire subtree is promoted or demoted in order to match a new headline
8275 level.
8277 If the cursor is at the beginning of a headline, the same level as
8278 that headline is used to paste the tree.
8280 If not, the new level is derived from the *visible* headings
8281 before and after the insertion point, and taken to be the inferior headline
8282 level of the two. So if the previous visible heading is level 3 and the
8283 next is level 4 (or vice versa), level 4 will be used for insertion.
8284 This makes sure that the subtree remains an independent subtree and does
8285 not swallow low level entries.
8287 You can also force a different level, either by using a numeric prefix
8288 argument, or by inserting the heading marker by hand. For example, if the
8289 cursor is after \"*****\", then the tree will be shifted to level 5.
8291 If optional TREE is given, use this text instead of the kill ring.
8293 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8294 move back over whitespace before inserting, and move point to the end of
8295 the inserted text when done.
8297 When REMOVE is non-nil, remove the subtree from the clipboard."
8298 (interactive "P")
8299 (setq tree (or tree (and kill-ring (current-kill 0))))
8300 (unless (org-kill-is-subtree-p tree)
8301 (user-error
8302 (substitute-command-keys
8303 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8304 (org-with-limited-levels
8305 (let* ((visp (not (org-invisible-p)))
8306 (txt tree)
8307 (old-level (if (string-match org-outline-regexp-bol txt)
8308 (- (match-end 0) (match-beginning 0) 1)
8309 -1))
8310 (force-level
8311 (cond
8312 (level (prefix-numeric-value level))
8313 ;; When point is right after the stars in an otherwise
8314 ;; empty headline, use stars as the forced level.
8315 ((and (looking-at-p "[ \t]*$")
8316 (string-match-p "^\\*+ *"
8317 (buffer-substring (line-beginning-position)
8318 (point))))
8319 (org-outline-level))
8320 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8321 (previous-level
8322 (save-excursion
8323 (org-previous-visible-heading 1)
8324 (if (org-at-heading-p) (org-outline-level) 1)))
8325 (next-level
8326 (save-excursion
8327 (if (org-at-heading-p) (org-outline-level)
8328 (org-next-visible-heading 1)
8329 (if (org-at-heading-p) (org-outline-level) 1))))
8330 (new-level (or force-level (max previous-level next-level)))
8331 (shift (if (or (= old-level -1)
8332 (= new-level -1)
8333 (= old-level new-level))
8335 (- new-level old-level)))
8336 (delta (if (> shift 0) -1 1))
8337 (func (if (> shift 0) #'org-demote #'org-promote))
8338 (org-odd-levels-only nil)
8339 beg end newend)
8340 ;; Remove the forced level indicator.
8341 (when (and force-level (not level))
8342 (delete-region (line-beginning-position) (point)))
8343 ;; Paste before the next visible heading or at end of buffer,
8344 ;; unless point is at the beginning of a headline.
8345 (unless (and (bolp) (org-at-heading-p))
8346 (org-next-visible-heading 1)
8347 (unless (bolp) (insert "\n")))
8348 (setq beg (point))
8349 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8350 (insert-before-markers txt)
8351 (unless (string-suffix-p "\n" txt) (insert "\n"))
8352 (setq newend (point))
8353 (org-reinstall-markers-in-region beg)
8354 (setq end (point))
8355 (goto-char beg)
8356 (skip-chars-forward " \t\n\r")
8357 (setq beg (point))
8358 (when (and (org-invisible-p) visp)
8359 (save-excursion (outline-show-heading)))
8360 ;; Shift if necessary.
8361 (unless (= shift 0)
8362 (save-restriction
8363 (narrow-to-region beg end)
8364 (while (not (= shift 0))
8365 (org-map-region func (point-min) (point-max))
8366 (setq shift (+ delta shift)))
8367 (goto-char (point-min))
8368 (setq newend (point-max))))
8369 (when (or for-yank (called-interactively-p 'interactive))
8370 (message "Clipboard pasted as level %d subtree" new-level))
8371 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8372 kill-ring
8373 (equal org-subtree-clip (current-kill 0))
8374 org-subtree-clip-folded)
8375 ;; The tree was folded before it was killed/copied
8376 (outline-hide-subtree))
8377 (when for-yank (goto-char newend))
8378 (when remove (pop kill-ring)))))
8380 (defun org-kill-is-subtree-p (&optional txt)
8381 "Check if the current kill is an outline subtree, or a set of trees.
8382 Returns nil if kill does not start with a headline, or if the first
8383 headline level is not the largest headline level in the tree.
8384 So this will actually accept several entries of equal levels as well,
8385 which is OK for `org-paste-subtree'.
8386 If optional TXT is given, check this string instead of the current kill."
8387 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8388 (re (org-get-limited-outline-regexp))
8389 (^re (concat "^" re))
8390 (start-level (and kill
8391 (string-match
8392 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8393 kill)
8394 (- (match-end 2) (match-beginning 2) 1)))
8395 (start (1+ (or (match-beginning 2) -1))))
8396 (if (not start-level)
8397 (progn
8398 nil) ;; does not even start with a heading
8399 (catch 'exit
8400 (while (setq start (string-match ^re kill (1+ start)))
8401 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8402 (throw 'exit nil)))
8403 t))))
8405 (defvar org-markers-to-move nil
8406 "Markers that should be moved with a cut-and-paste operation.
8407 Those markers are stored together with their positions relative to
8408 the start of the region.")
8410 (defun org-save-markers-in-region (beg end)
8411 "Check markers in region.
8412 If these markers are between BEG and END, record their position relative
8413 to BEG, so that after moving the block of text, we can put the markers back
8414 into place.
8415 This function gets called just before an entry or tree gets cut from the
8416 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8417 called immediately, to move the markers with the entries."
8418 (setq org-markers-to-move nil)
8419 (when (featurep 'org-clock)
8420 (org-clock-save-markers-for-cut-and-paste beg end))
8421 (when (featurep 'org-agenda)
8422 (org-agenda-save-markers-for-cut-and-paste beg end)))
8424 (defun org-check-and-save-marker (marker beg end)
8425 "Check if MARKER is between BEG and END.
8426 If yes, remember the marker and the distance to BEG."
8427 (when (and (marker-buffer marker)
8428 (equal (marker-buffer marker) (current-buffer))
8429 (>= marker beg) (< marker end))
8430 (push (cons marker (- marker beg)) org-markers-to-move)))
8432 (defun org-reinstall-markers-in-region (beg)
8433 "Move all remembered markers to their position relative to BEG."
8434 (dolist (x org-markers-to-move)
8435 (move-marker (car x) (+ beg (cdr x))))
8436 (setq org-markers-to-move nil))
8438 (defun org-narrow-to-subtree ()
8439 "Narrow buffer to the current subtree."
8440 (interactive)
8441 (save-excursion
8442 (save-match-data
8443 (org-with-limited-levels
8444 (narrow-to-region
8445 (progn (org-back-to-heading t) (point))
8446 (progn (org-end-of-subtree t t)
8447 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8448 (point)))))))
8450 (defun org-narrow-to-block ()
8451 "Narrow buffer to the current block."
8452 (interactive)
8453 (let* ((case-fold-search t)
8454 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8455 "^[ \t]*#\\+end_.*")))
8456 (if blockp
8457 (narrow-to-region (car blockp) (cdr blockp))
8458 (user-error "Not in a block"))))
8460 (defun org-clone-subtree-with-time-shift (n &optional shift)
8461 "Clone the task (subtree) at point N times.
8462 The clones will be inserted as siblings.
8464 In interactive use, the user will be prompted for the number of
8465 clones to be produced. If the entry has a timestamp, the user
8466 will also be prompted for a time shift, which may be a repeater
8467 as used in time stamps, for example `+3d'. To disable this,
8468 you can call the function with a universal prefix argument.
8470 When a valid repeater is given and the entry contains any time
8471 stamps, the clones will become a sequence in time, with time
8472 stamps in the subtree shifted for each clone produced. If SHIFT
8473 is nil or the empty string, time stamps will be left alone. The
8474 ID property of the original subtree is removed.
8476 In each clone, all the CLOCK entries will be removed. This
8477 prevents Org from considering that the clocked times overlap.
8479 If the original subtree did contain time stamps with a repeater,
8480 the following will happen:
8481 - the repeater will be removed in each clone
8482 - an additional clone will be produced, with the current, unshifted
8483 date(s) in the entry.
8484 - the original entry will be placed *after* all the clones, with
8485 repeater intact.
8486 - the start days in the repeater in the original entry will be shifted
8487 to past the last clone.
8488 In this way you can spell out a number of instances of a repeating task,
8489 and still retain the repeater to cover future instances of the task.
8491 As described above, N+1 clones are produced when the original
8492 subtree has a repeater. Setting N to 0, then, can be used to
8493 remove the repeater from a subtree and create a shifted clone
8494 with the original repeater."
8495 (interactive "nNumber of clones to produce: ")
8496 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8497 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8498 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8499 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8500 (shift
8501 (or shift
8502 (if (and (not (equal current-prefix-arg '(4)))
8503 (save-excursion
8504 (goto-char beg)
8505 (re-search-forward org-ts-regexp-both end-of-tree t)))
8506 (read-from-minibuffer
8507 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8508 ""))) ;No time shift
8509 (doshift
8510 (and (org-string-nw-p shift)
8511 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8512 shift)
8513 (user-error "Invalid shift specification %s" shift)))))
8514 (goto-char end-of-tree)
8515 (unless (bolp) (insert "\n"))
8516 (let* ((end (point))
8517 (template (buffer-substring beg end))
8518 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8519 (shift-what (pcase (and doshift (match-string 2 shift))
8520 (`nil nil)
8521 ("d" 'day)
8522 ("w" (setq shift-n (* 7 shift-n)) 'day)
8523 ("m" 'month)
8524 ("y" 'year)
8525 (_ (error "Unsupported time unit"))))
8526 (nmin 1)
8527 (nmax n)
8528 (n-no-remove -1)
8529 (idprop (org-entry-get nil "ID")))
8530 (when (and doshift
8531 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8532 template))
8533 (delete-region beg end)
8534 (setq end beg)
8535 (setq nmin 0)
8536 (setq nmax (1+ nmax))
8537 (setq n-no-remove nmax))
8538 (goto-char end)
8539 (cl-loop for n from nmin to nmax do
8540 (insert
8541 ;; Prepare clone.
8542 (with-temp-buffer
8543 (insert template)
8544 (org-mode)
8545 (goto-char (point-min))
8546 (org-show-subtree)
8547 (and idprop (if org-clone-delete-id
8548 (org-entry-delete nil "ID")
8549 (org-id-get-create t)))
8550 (unless (= n 0)
8551 (while (re-search-forward org-clock-line-re nil t)
8552 (delete-region (line-beginning-position)
8553 (line-beginning-position 2)))
8554 (goto-char (point-min))
8555 (while (re-search-forward org-drawer-regexp nil t)
8556 (org-remove-empty-drawer-at (point))))
8557 (goto-char (point-min))
8558 (when doshift
8559 (while (re-search-forward org-ts-regexp-both nil t)
8560 (org-timestamp-change (* n shift-n) shift-what))
8561 (unless (= n n-no-remove)
8562 (goto-char (point-min))
8563 (while (re-search-forward org-ts-regexp nil t)
8564 (save-excursion
8565 (goto-char (match-beginning 0))
8566 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8567 (delete-region (match-beginning 1) (match-end 1)))))))
8568 (buffer-string)))))
8569 (goto-char beg)))
8571 ;;; Outline Sorting
8573 (defun org-sort (&optional with-case)
8574 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8575 Optional argument WITH-CASE means sort case-sensitively."
8576 (interactive "P")
8577 (org-call-with-arg
8578 (cond ((org-at-table-p) #'org-table-sort-lines)
8579 ((org-at-item-p) #'org-sort-list)
8580 (t #'org-sort-entries))
8581 with-case))
8583 (defun org-sort-remove-invisible (s)
8584 "Remove invisible part of links and emphasis markers from string S."
8585 (remove-text-properties 0 (length s) org-rm-props s)
8586 (replace-regexp-in-string
8587 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8588 (replace-regexp-in-string
8589 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8590 (org-link-display-format s)
8591 t t) t t))
8593 (defvar org-priority-regexp) ; defined later in the file
8595 (defvar org-after-sorting-entries-or-items-hook nil
8596 "Hook that is run after a bunch of entries or items have been sorted.
8597 When children are sorted, the cursor is in the parent line when this
8598 hook gets called. When a region or a plain list is sorted, the cursor
8599 will be in the first entry of the sorted region/list.")
8601 (defun org-sort-entries
8602 (&optional with-case sorting-type getkey-func compare-func property
8603 interactive?)
8604 "Sort entries on a certain level of an outline tree.
8605 If there is an active region, the entries in the region are sorted.
8606 Else, if the cursor is before the first entry, sort the top-level items.
8607 Else, the children of the entry at point are sorted.
8609 Sorting can be alphabetically, numerically, by date/time as given by
8610 a time stamp, by a property, by priority order, or by a custom function.
8612 The command prompts for the sorting type unless it has been given to the
8613 function through the SORTING-TYPE argument, which needs to be a character,
8614 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8615 the precise meaning of each character:
8617 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8618 c By creation time, which is assumed to be the first inactive time stamp
8619 at the beginning of a line.
8620 d By deadline date/time.
8621 k By clocking time.
8622 n Numerically, by converting the beginning of the entry/item to a number.
8623 o By order of TODO keywords.
8624 p By priority according to the cookie.
8625 r By the value of a property.
8626 s By scheduled date/time.
8627 t By date/time, either the first active time stamp in the entry, or, if
8628 none exist, by the first inactive one.
8630 Capital letters will reverse the sort order.
8632 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8633 called with point at the beginning of the record. It must return a
8634 value that is compatible with COMPARE-FUNC, the function used to
8635 compare entries.
8637 Comparing entries ignores case by default. However, with an optional argument
8638 WITH-CASE, the sorting considers case as well.
8640 Sorting is done against the visible part of the headlines, it ignores hidden
8641 links.
8643 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8645 A non-nil value for INTERACTIVE? is used to signal that this
8646 function is being called interactively."
8647 (interactive (list current-prefix-arg nil nil nil nil t))
8648 (let ((case-func (if with-case 'identity 'downcase))
8649 start beg end stars re re2
8650 txt what tmp)
8651 ;; Find beginning and end of region to sort
8652 (cond
8653 ((org-region-active-p)
8654 ;; we will sort the region
8655 (setq end (region-end)
8656 what "region")
8657 (goto-char (region-beginning))
8658 (unless (org-at-heading-p) (outline-next-heading))
8659 (setq start (point)))
8660 ((or (org-at-heading-p)
8661 (ignore-errors (progn (org-back-to-heading) t)))
8662 ;; we will sort the children of the current headline
8663 (org-back-to-heading)
8664 (setq start (point)
8665 end (progn (org-end-of-subtree t t)
8666 (or (bolp) (insert "\n"))
8667 (when (>= (org-back-over-empty-lines) 1)
8668 (forward-line 1))
8669 (point))
8670 what "children")
8671 (goto-char start)
8672 (outline-show-subtree)
8673 (outline-next-heading))
8675 ;; we will sort the top-level entries in this file
8676 (goto-char (point-min))
8677 (or (org-at-heading-p) (outline-next-heading))
8678 (setq start (point))
8679 (goto-char (point-max))
8680 (beginning-of-line 1)
8681 (when (looking-at ".*?\\S-")
8682 ;; File ends in a non-white line
8683 (end-of-line 1)
8684 (insert "\n"))
8685 (setq end (point-max))
8686 (setq what "top-level")
8687 (goto-char start)
8688 (org-show-all '(headings blocks))))
8690 (setq beg (point))
8691 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8693 (looking-at "\\(\\*+\\)")
8694 (setq stars (match-string 1)
8695 re (concat "^" (regexp-quote stars) " +")
8696 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8697 txt (buffer-substring beg end))
8698 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8699 (when (and (not (equal stars "*")) (string-match re2 txt))
8700 (user-error "Region to sort contains a level above the first entry"))
8702 (unless sorting-type
8703 (message
8704 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8705 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8706 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8707 what)
8708 (setq sorting-type (read-char-exclusive)))
8710 (unless getkey-func
8711 (and (= (downcase sorting-type) ?f)
8712 (setq getkey-func
8713 (or (and interactive?
8714 (org-read-function
8715 "Function for extracting keys: "))
8716 (error "Missing key extractor")))))
8718 (and (= (downcase sorting-type) ?r)
8719 (not property)
8720 (setq property
8721 (completing-read "Property: "
8722 (mapcar #'list (org-buffer-property-keys t))
8723 nil t)))
8725 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8726 (message "Sorting entries...")
8728 (save-restriction
8729 (narrow-to-region start end)
8730 (let ((restore-clock?
8731 ;; The clock marker is lost when using `sort-subr'; mark
8732 ;; the clock with temporary `:org-clock-marker-backup'
8733 ;; text property.
8734 (when (and (eq (org-clock-is-active) (current-buffer))
8735 (<= start (marker-position org-clock-marker))
8736 (>= end (marker-position org-clock-marker)))
8737 (org-with-silent-modifications
8738 (put-text-property (1- org-clock-marker) org-clock-marker
8739 :org-clock-marker-backup t))
8741 (dcst (downcase sorting-type))
8742 (case-fold-search nil)
8743 (now (current-time)))
8744 (org-preserve-local-variables
8745 (sort-subr
8746 (/= dcst sorting-type)
8747 ;; This function moves to the beginning character of the
8748 ;; "record" to be sorted.
8749 (lambda nil
8750 (if (re-search-forward re nil t)
8751 (goto-char (match-beginning 0))
8752 (goto-char (point-max))))
8753 ;; This function moves to the last character of the "record" being
8754 ;; sorted.
8755 (lambda nil
8756 (save-match-data
8757 (condition-case nil
8758 (outline-forward-same-level 1)
8759 (error
8760 (goto-char (point-max))))))
8761 ;; This function returns the value that gets sorted against.
8762 (lambda ()
8763 (cond
8764 ((= dcst ?n)
8765 (string-to-number
8766 (org-sort-remove-invisible (org-get-heading t t t t))))
8767 ((= dcst ?a)
8768 (funcall case-func
8769 (org-sort-remove-invisible (org-get-heading t t t t))))
8770 ((= dcst ?k)
8771 (or (get-text-property (point) :org-clock-minutes) 0))
8772 ((= dcst ?t)
8773 (let ((end (save-excursion (outline-next-heading) (point))))
8774 (if (or (re-search-forward org-ts-regexp end t)
8775 (re-search-forward org-ts-regexp-both end t))
8776 (org-time-string-to-seconds (match-string 0))
8777 (float-time now))))
8778 ((= dcst ?c)
8779 (let ((end (save-excursion (outline-next-heading) (point))))
8780 (if (re-search-forward
8781 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8782 end t)
8783 (org-time-string-to-seconds (match-string 0))
8784 (float-time now))))
8785 ((= dcst ?s)
8786 (let ((end (save-excursion (outline-next-heading) (point))))
8787 (if (re-search-forward org-scheduled-time-regexp end t)
8788 (org-time-string-to-seconds (match-string 1))
8789 (float-time now))))
8790 ((= dcst ?d)
8791 (let ((end (save-excursion (outline-next-heading) (point))))
8792 (if (re-search-forward org-deadline-time-regexp end t)
8793 (org-time-string-to-seconds (match-string 1))
8794 (float-time now))))
8795 ((= dcst ?p)
8796 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8797 (string-to-char (match-string 2))
8798 org-default-priority))
8799 ((= dcst ?r)
8800 (or (org-entry-get nil property) ""))
8801 ((= dcst ?o)
8802 (when (looking-at org-complex-heading-regexp)
8803 (let* ((m (match-string 2))
8804 (s (if (member m org-done-keywords) '- '+)))
8805 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8806 ((= dcst ?f)
8807 (if getkey-func
8808 (progn
8809 (setq tmp (funcall getkey-func))
8810 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8811 tmp)
8812 (error "Invalid key function `%s'" getkey-func)))
8813 (t (error "Invalid sorting type `%c'" sorting-type))))
8815 (cond
8816 ((= dcst ?a) 'org-string-collate-lessp)
8817 ((= dcst ?f)
8818 (or compare-func
8819 (and interactive?
8820 (org-read-function
8821 (concat "Function for comparing keys "
8822 "(empty for default `sort-subr' predicate): ")
8823 'allow-empty))))
8824 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8825 (when restore-clock?
8826 (move-marker org-clock-marker
8827 (1+ (next-single-property-change
8828 start :org-clock-marker-backup)))
8829 (remove-text-properties (1- org-clock-marker) org-clock-marker
8830 '(:org-clock-marker-backup t)))))
8831 (run-hooks 'org-after-sorting-entries-or-items-hook)
8832 (message "Sorting entries...done")))
8834 (defun org-contextualize-keys (alist contexts)
8835 "Return valid elements in ALIST depending on CONTEXTS.
8837 `org-agenda-custom-commands' or `org-capture-templates' are the
8838 values used for ALIST, and `org-agenda-custom-commands-contexts'
8839 or `org-capture-templates-contexts' are the associated contexts
8840 definitions."
8841 (let ((contexts
8842 ;; normalize contexts
8843 (mapcar
8844 (lambda(c) (cond ((listp (cadr c))
8845 (list (car c) (car c) (nth 1 c)))
8846 ((string= "" (cadr c))
8847 (list (car c) (car c) (nth 2 c)))
8848 (t c)))
8849 contexts))
8850 (a alist) r s)
8851 ;; loop over all commands or templates
8852 (dolist (c a)
8853 (let (vrules repl)
8854 (cond
8855 ((not (assoc (car c) contexts))
8856 (push c r))
8857 ((and (assoc (car c) contexts)
8858 (setq vrules (org-contextualize-validate-key
8859 (car c) contexts)))
8860 (mapc (lambda (vr)
8861 (unless (equal (car vr) (cadr vr))
8862 (setq repl vr)))
8863 vrules)
8864 (if (not repl) (push c r)
8865 (push (cadr repl) s)
8866 (push
8867 (cons (car c)
8868 (cdr (or (assoc (cadr repl) alist)
8869 (error "Undefined key `%s' as contextual replacement for `%s'"
8870 (cadr repl) (car c)))))
8871 r))))))
8872 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8873 (delq
8875 (delete-dups
8876 (mapcar (lambda (x)
8877 (let ((tpl (car x)))
8878 (unless (delq
8880 (mapcar (lambda (y)
8881 (equal y tpl))
8883 x)))
8884 (reverse r))))))
8886 (defun org-contextualize-validate-key (key contexts)
8887 "Check CONTEXTS for agenda or capture KEY."
8888 (let (res)
8889 (dolist (r contexts)
8890 (dolist (rr (car (last r)))
8891 (when
8892 (and (equal key (car r))
8893 (if (functionp rr) (funcall rr)
8894 (or (and (eq (car rr) 'in-file)
8895 (buffer-file-name)
8896 (string-match (cdr rr) (buffer-file-name)))
8897 (and (eq (car rr) 'in-mode)
8898 (string-match (cdr rr) (symbol-name major-mode)))
8899 (and (eq (car rr) 'in-buffer)
8900 (string-match (cdr rr) (buffer-name)))
8901 (when (and (eq (car rr) 'not-in-file)
8902 (buffer-file-name))
8903 (not (string-match (cdr rr) (buffer-file-name))))
8904 (when (eq (car rr) 'not-in-mode)
8905 (not (string-match (cdr rr) (symbol-name major-mode))))
8906 (when (eq (car rr) 'not-in-buffer)
8907 (not (string-match (cdr rr) (buffer-name)))))))
8908 (push r res))))
8909 (delete-dups (delq nil res))))
8911 ;; Defined to provide a value for defcustom, since there is no
8912 ;; string-collate-greaterp in Emacs.
8913 (defun org-string-collate-greaterp (s1 s2)
8914 "Return non-nil if S1 is greater than S2 in collation order."
8915 (not (org-string-collate-lessp s1 s2)))
8917 ;;;###autoload
8918 (defun org-run-like-in-org-mode (cmd)
8919 "Run a command, pretending that the current buffer is in Org mode.
8920 This will temporarily bind local variables that are typically bound in
8921 Org mode to the values they have in Org mode, and then interactively
8922 call CMD."
8923 (org-load-modules-maybe)
8924 (let (binds)
8925 (dolist (var (org-get-local-variables))
8926 (when (or (not (boundp (car var)))
8927 (eq (symbol-value (car var))
8928 (default-value (car var))))
8929 (push (list (car var) `(quote ,(cadr var))) binds)))
8930 (eval `(let ,binds
8931 (call-interactively (quote ,cmd))))))
8933 (defun org-get-category (&optional pos force-refresh)
8934 "Get the category applying to position POS."
8935 (save-match-data
8936 (when force-refresh (org-refresh-category-properties))
8937 (let ((pos (or pos (point))))
8938 (or (get-text-property pos 'org-category)
8939 (progn (org-refresh-category-properties)
8940 (get-text-property pos 'org-category))))))
8942 ;;; Refresh properties
8944 (defun org-refresh-properties (dprop tprop)
8945 "Refresh buffer text properties.
8946 DPROP is the drawer property and TPROP is either the
8947 corresponding text property to set, or an alist with each element
8948 being a text property (as a symbol) and a function to apply to
8949 the value of the drawer property."
8950 (let* ((case-fold-search t)
8951 (inhibit-read-only t)
8952 (inherit? (org-property-inherit-p dprop))
8953 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8954 (global (and inherit? (org--property-global-value dprop nil))))
8955 (org-with-silent-modifications
8956 (org-with-point-at 1
8957 ;; Set global values (e.g., values defined through
8958 ;; "#+PROPERTY:" keywords) to the whole buffer.
8959 (when global (put-text-property (point-min) (point-max) tprop global))
8960 ;; Set local values.
8961 (while (re-search-forward property-re nil t)
8962 (when (org-at-property-p)
8963 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8964 (outline-next-heading))))))
8966 (defun org-refresh-property (tprop p &optional inherit)
8967 "Refresh the buffer text property TPROP from the drawer property P.
8968 The refresh happens only for the current headline, or the whole
8969 sub-tree if optional argument INHERIT is non-nil."
8970 (unless (org-before-first-heading-p)
8971 (save-excursion
8972 (org-back-to-heading t)
8973 (let ((start (point))
8974 (end (save-excursion
8975 (if inherit (org-end-of-subtree t t)
8976 (or (outline-next-heading) (point-max))))))
8977 (if (symbolp tprop)
8978 ;; TPROP is a text property symbol.
8979 (put-text-property start end tprop p)
8980 ;; TPROP is an alist with (property . function) elements.
8981 (pcase-dolist (`(,prop . ,f) tprop)
8982 (put-text-property start end prop (funcall f p))))))))
8984 (defun org-refresh-category-properties ()
8985 "Refresh category text properties in the buffer."
8986 (let ((case-fold-search t)
8987 (inhibit-read-only t)
8988 (default-category
8989 (cond ((null org-category)
8990 (if buffer-file-name
8991 (file-name-sans-extension
8992 (file-name-nondirectory buffer-file-name))
8993 "???"))
8994 ((symbolp org-category) (symbol-name org-category))
8995 (t org-category))))
8996 (org-with-silent-modifications
8997 (org-with-wide-buffer
8998 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8999 ;; This is the default category for the buffer. If none is
9000 ;; found, fall-back to `org-category' or buffer file name.
9001 (put-text-property
9002 (point-min) (point-max)
9003 'org-category
9004 (catch 'buffer-category
9005 (goto-char (point-max))
9006 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9007 (let ((element (org-element-at-point)))
9008 (when (eq (org-element-type element) 'keyword)
9009 (throw 'buffer-category
9010 (org-element-property :value element)))))
9011 default-category))
9012 ;; Set sub-tree specific categories.
9013 (goto-char (point-min))
9014 (let ((regexp (org-re-property "CATEGORY")))
9015 (while (re-search-forward regexp nil t)
9016 (let ((value (match-string-no-properties 3)))
9017 (when (org-at-property-p)
9018 (put-text-property
9019 (save-excursion (org-back-to-heading t) (point))
9020 (save-excursion (org-end-of-subtree t t) (point))
9021 'org-category
9022 value)))))))))
9024 (defun org-refresh-stats-properties ()
9025 "Refresh stats text properties in the buffer."
9026 (org-with-silent-modifications
9027 (org-with-point-at 1
9028 (let ((regexp (concat org-outline-regexp-bol
9029 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9030 (while (re-search-forward regexp nil t)
9031 (let* ((numerator (string-to-number (match-string 1)))
9032 (denominator (and (match-end 2)
9033 (string-to-number (match-string 2))))
9034 (stats (cond ((not denominator) numerator) ;percent
9035 ((= denominator 0) 0)
9036 (t (/ (* numerator 100) denominator)))))
9037 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9038 'org-stats stats)))))))
9040 (defun org-refresh-effort-properties ()
9041 "Refresh effort properties"
9042 (org-refresh-properties
9043 org-effort-property
9044 '((effort . identity)
9045 (effort-minutes . org-duration-to-minutes))))
9047 ;;;; Link Stuff
9049 ;;; Link abbreviations
9051 (defun org-link-expand-abbrev (link)
9052 "Apply replacements as defined in `org-link-abbrev-alist'."
9053 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9054 (let* ((key (match-string 1 link))
9055 (as (or (assoc key org-link-abbrev-alist-local)
9056 (assoc key org-link-abbrev-alist)))
9057 (tag (and (match-end 2) (match-string 3 link)))
9058 rpl)
9059 (if (not as)
9060 link
9061 (setq rpl (cdr as))
9062 (cond
9063 ((symbolp rpl) (funcall rpl tag))
9064 ((string-match "%(\\([^)]+\\))" rpl)
9065 (replace-match
9066 (save-match-data
9067 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9068 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9069 ((string-match "%h" rpl)
9070 (replace-match (url-hexify-string (or tag "")) t t rpl))
9071 (t (concat rpl tag)))))
9072 link))
9074 ;;; Storing and inserting links
9076 (defvar org-insert-link-history nil
9077 "Minibuffer history for links inserted with `org-insert-link'.")
9079 (defvar org-stored-links nil
9080 "Contains the links stored with `org-store-link'.")
9082 (defvar org-store-link-plist nil
9083 "Plist with info about the most recently link created with `org-store-link'.")
9085 (defun org-store-link-functions ()
9086 "Return a list of functions that are called to create and store a link.
9087 The functions defined in the :store property of
9088 `org-link-parameters'.
9090 Each function will be called in turn until one returns a non-nil
9091 value. Each function should check if it is responsible for
9092 creating this link (for example by looking at the major mode).
9093 If not, it must exit and return nil. If yes, it should return
9094 a non-nil value after calling `org-store-link-props' with a list
9095 of properties and values. Special properties are:
9097 :type The link prefix, like \"http\". This must be given.
9098 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9099 This is obligatory as well.
9100 :description Optional default description for the second pair
9101 of brackets in an Org mode link. The user can still change
9102 this when inserting this link into an Org mode buffer.
9104 In addition to these, any additional properties can be specified
9105 and then used in capture templates."
9106 (cl-loop for link in org-link-parameters
9107 with store-func
9108 do (setq store-func (org-link-get-parameter (car link) :store))
9109 if store-func
9110 collect store-func))
9112 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9113 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9115 ;;;###autoload
9116 (defun org-store-link (arg &optional interactive?)
9117 "Store an org-link to the current location.
9118 \\<org-mode-map>
9119 This link is added to `org-stored-links' and can later be inserted
9120 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9122 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9123 A single
9124 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9125 `org-gnus-prefer-web-links' for links to Usenet articles.
9127 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9128 skipping storing functions that are not
9129 part of Org core.
9131 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9132 prefix ARG forces storing a link for each line in the
9133 active region.
9135 Assume the function is called interactively if INTERACTIVE? is
9136 non-nil."
9137 (interactive "P\np")
9138 (org-load-modules-maybe)
9139 (if (and (equal arg '(64)) (org-region-active-p))
9140 (save-excursion
9141 (let ((end (region-end)))
9142 (goto-char (region-beginning))
9143 (set-mark (point))
9144 (while (< (point-at-eol) end)
9145 (move-end-of-line 1) (activate-mark)
9146 (let (current-prefix-arg)
9147 (call-interactively 'org-store-link))
9148 (move-beginning-of-line 2)
9149 (set-mark (point)))))
9150 (setq org-store-link-plist nil)
9151 (let (link cpltxt desc description search txt custom-id agenda-link)
9152 (cond
9153 ;; Store a link using an external link type, if any function is
9154 ;; available. If more than one can generate a link from current
9155 ;; location, ask which one to use.
9156 ((and (not (equal arg '(16)))
9157 (let ((results-alist nil))
9158 (dolist (f (org-store-link-functions))
9159 (when (funcall f)
9160 ;; XXX: return value is not link's plist, so we
9161 ;; store the new value before it is modified. It
9162 ;; would be cleaner to ask store link functions to
9163 ;; return the plist instead.
9164 (push (cons f (copy-sequence org-store-link-plist))
9165 results-alist)))
9166 (pcase results-alist
9167 (`nil nil)
9168 (`((,_ . ,_)) t) ;single choice: nothing to do
9169 (`((,name . ,_) . ,_)
9170 ;; Reinstate link plist associated to the chosen
9171 ;; function.
9172 (apply #'org-store-link-props
9173 (cdr (assoc-string
9174 (completing-read
9175 "Which function for creating the link? "
9176 (mapcar #'car results-alist)
9177 nil t (symbol-name name))
9178 results-alist)))
9179 t))))
9180 (setq link (plist-get org-store-link-plist :link))
9181 (setq desc (or (plist-get org-store-link-plist :description)
9182 link)))
9184 ;; Store a link from a source code buffer.
9185 ((org-src-edit-buffer-p)
9186 (let ((coderef-format (org-src-coderef-format)))
9187 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9188 (setq link (format "(%s)" (match-string-no-properties 3))))
9189 (interactive?
9190 (let ((label (read-string "Code line label: ")))
9191 (end-of-line)
9192 (setq link (format coderef-format label))
9193 (let ((gc (- 79 (length link))))
9194 (if (< (current-column) gc)
9195 (org-move-to-column gc t)
9196 (insert " ")))
9197 (insert link)
9198 (setq link (concat "(" label ")"))
9199 (setq desc nil)))
9200 (t (setq link nil)))))
9202 ;; We are in the agenda, link to referenced location
9203 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9204 (let ((m (or (get-text-property (point) 'org-hd-marker)
9205 (get-text-property (point) 'org-marker))))
9206 (when m
9207 (org-with-point-at m
9208 (setq agenda-link (org-store-link nil interactive?))))))
9210 ((eq major-mode 'calendar-mode)
9211 (let ((cd (calendar-cursor-to-date)))
9212 (setq link
9213 (format-time-string
9214 (car org-time-stamp-formats)
9215 (apply 'encode-time
9216 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9217 nil nil nil))))
9218 (org-store-link-props :type "calendar" :date cd)))
9220 ((eq major-mode 'help-mode)
9221 (setq link (concat "help:" (save-excursion
9222 (goto-char (point-min))
9223 (looking-at "^[^ ]+")
9224 (match-string 0))))
9225 (org-store-link-props :type "help"))
9227 ((eq major-mode 'w3-mode)
9228 (setq cpltxt (if (and (buffer-name)
9229 (not (string-match "Untitled" (buffer-name))))
9230 (buffer-name)
9231 (url-view-url t))
9232 link (url-view-url t))
9233 (org-store-link-props :type "w3" :url (url-view-url t)))
9235 ((eq major-mode 'image-mode)
9236 (setq cpltxt (concat "file:"
9237 (abbreviate-file-name buffer-file-name))
9238 link cpltxt)
9239 (org-store-link-props :type "image" :file buffer-file-name))
9241 ;; In dired, store a link to the file of the current line
9242 ((derived-mode-p 'dired-mode)
9243 (let ((file (dired-get-filename nil t)))
9244 (setq file (if file
9245 (abbreviate-file-name
9246 (expand-file-name (dired-get-filename nil t)))
9247 ;; otherwise, no file so use current directory.
9248 default-directory))
9249 (setq cpltxt (concat "file:" file)
9250 link cpltxt)))
9252 ((setq search (run-hook-with-args-until-success
9253 'org-create-file-search-functions))
9254 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9255 "::" search))
9256 (setq cpltxt (or description link)))
9258 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9259 (org-with-limited-levels
9260 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9261 (cond
9262 ;; Store a link using the target at point
9263 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9264 (setq cpltxt
9265 (concat "file:"
9266 (abbreviate-file-name
9267 (buffer-file-name (buffer-base-buffer)))
9268 "::" (match-string 1))
9269 link cpltxt))
9270 ((and (featurep 'org-id)
9271 (or (eq org-id-link-to-org-use-id t)
9272 (and interactive?
9273 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9274 (and (eq org-id-link-to-org-use-id
9275 'create-if-interactive-and-no-custom-id)
9276 (not custom-id))))
9277 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9278 ;; Store a link using the ID at point
9279 (setq link (condition-case nil
9280 (prog1 (org-id-store-link)
9281 (setq desc (or (plist-get org-store-link-plist
9282 :description)
9283 "")))
9284 (error
9285 ;; Probably before first headline, link only to file
9286 (concat "file:"
9287 (abbreviate-file-name
9288 (buffer-file-name (buffer-base-buffer))))))))
9290 ;; Just link to current headline
9291 (setq cpltxt (concat "file:"
9292 (abbreviate-file-name
9293 (buffer-file-name (buffer-base-buffer)))))
9294 ;; Add a context search string
9295 (when (org-xor org-context-in-file-links
9296 (equal arg '(4)))
9297 (let* ((element (org-element-at-point))
9298 (name (org-element-property :name element)))
9299 (setq txt (cond
9300 ((org-at-heading-p) nil)
9301 (name)
9302 ((org-region-active-p)
9303 (buffer-substring (region-beginning) (region-end)))))
9304 (when (or (null txt) (string-match "\\S-" txt))
9305 (setq cpltxt
9306 (concat cpltxt "::"
9307 (condition-case nil
9308 (org-make-org-heading-search-string txt)
9309 (error "")))
9310 desc (or name
9311 (nth 4 (ignore-errors (org-heading-components)))
9312 "NONE")))))
9313 (when (string-match "::\\'" cpltxt)
9314 (setq cpltxt (substring cpltxt 0 -2)))
9315 (setq link cpltxt)))))
9317 ((buffer-file-name (buffer-base-buffer))
9318 ;; Just link to this file here.
9319 (setq cpltxt (concat "file:"
9320 (abbreviate-file-name
9321 (buffer-file-name (buffer-base-buffer)))))
9322 ;; Add a context string.
9323 (when (org-xor org-context-in-file-links
9324 (equal arg '(4)))
9325 (setq txt (if (org-region-active-p)
9326 (buffer-substring (region-beginning) (region-end))
9327 (buffer-substring (point-at-bol) (point-at-eol))))
9328 ;; Only use search option if there is some text.
9329 (when (string-match "\\S-" txt)
9330 (setq cpltxt
9331 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9332 desc "NONE")))
9333 (setq link cpltxt))
9335 (interactive?
9336 (user-error "No method for storing a link from this buffer"))
9338 (t (setq link nil)))
9340 ;; We're done setting link and desc, clean up
9341 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9342 (setq link (or link cpltxt)
9343 desc (or desc cpltxt))
9344 (cond ((not desc))
9345 ((equal desc "NONE") (setq desc nil))
9346 (t (setq desc
9347 (replace-regexp-in-string
9348 org-bracket-link-analytic-regexp
9349 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9350 desc))))
9351 ;; Return the link
9352 (if (not (and interactive? link))
9353 (or agenda-link (and link (org-make-link-string link desc)))
9354 (push (list link desc) org-stored-links)
9355 (message "Stored: %s" (or desc link))
9356 (when custom-id
9357 (setq link (concat "file:" (abbreviate-file-name
9358 (buffer-file-name)) "::#" custom-id))
9359 (push (list link desc) org-stored-links))
9360 (car org-stored-links)))))
9362 (defun org-store-link-props (&rest plist)
9363 "Store link properties.
9364 The properties are pre-processed by extracting names, addresses
9365 and dates."
9366 (let ((x (plist-get plist :from)))
9367 (when x
9368 (let ((adr (mail-extract-address-components x)))
9369 (setq plist (plist-put plist :fromname (car adr)))
9370 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9371 (let ((x (plist-get plist :to)))
9372 (when x
9373 (let ((adr (mail-extract-address-components x)))
9374 (setq plist (plist-put plist :toname (car adr)))
9375 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9376 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9377 (when x
9378 (setq plist (plist-put plist :date-timestamp
9379 (format-time-string
9380 (org-time-stamp-format t) x)))
9381 (setq plist (plist-put plist :date-timestamp-inactive
9382 (format-time-string
9383 (org-time-stamp-format t t) x)))))
9384 (let ((from (plist-get plist :from))
9385 (to (plist-get plist :to)))
9386 (when (and from to org-from-is-user-regexp)
9387 (setq plist
9388 (plist-put plist :fromto
9389 (if (string-match org-from-is-user-regexp from)
9390 (concat "to %t")
9391 (concat "from %f"))))))
9392 (setq org-store-link-plist plist))
9394 (defun org-add-link-props (&rest plist)
9395 "Add these properties to the link property list."
9396 (let (key value)
9397 (while plist
9398 (setq key (pop plist) value (pop plist))
9399 (setq org-store-link-plist
9400 (plist-put org-store-link-plist key value)))))
9402 (defun org-email-link-description (&optional fmt)
9403 "Return the description part of an email link.
9404 This takes information from `org-store-link-plist' and formats it
9405 according to FMT (default from `org-email-link-description-format')."
9406 (setq fmt (or fmt org-email-link-description-format))
9407 (let* ((p org-store-link-plist)
9408 (to (plist-get p :toaddress))
9409 (from (plist-get p :fromaddress))
9410 (table
9411 (list
9412 (cons "%c" (plist-get p :fromto))
9413 (cons "%F" (plist-get p :from))
9414 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9415 (cons "%T" (plist-get p :to))
9416 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9417 (cons "%s" (plist-get p :subject))
9418 (cons "%d" (plist-get p :date))
9419 (cons "%m" (plist-get p :message-id)))))
9420 (when (string-match "%c" fmt)
9421 ;; Check if the user wrote this message
9422 (if (and org-from-is-user-regexp from to
9423 (save-match-data (string-match org-from-is-user-regexp from)))
9424 (setq fmt (replace-match "to %t" t t fmt))
9425 (setq fmt (replace-match "from %f" t t fmt))))
9426 (org-replace-escapes fmt table)))
9428 (defun org-make-org-heading-search-string (&optional string)
9429 "Make search string for the current headline or STRING."
9430 (let ((s (or string
9431 (and (derived-mode-p 'org-mode)
9432 (save-excursion
9433 (org-back-to-heading t)
9434 (org-element-property :raw-value (org-element-at-point))))))
9435 (lines org-context-in-file-links))
9436 (unless string (setq s (concat "*" s))) ;Add * for headlines
9437 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9438 (when (and string (integerp lines) (> lines 0))
9439 (let ((slines (org-split-string s "\n")))
9440 (when (< lines (length slines))
9441 (setq s (mapconcat
9442 'identity
9443 (reverse (nthcdr (- (length slines) lines)
9444 (reverse slines))) "\n")))))
9445 (mapconcat #'identity (split-string s) " ")))
9447 (defconst org-link-escape-chars
9448 ;;%20 %5B %5D %25
9449 '(?\s ?\[ ?\] ?%)
9450 "List of characters that should be escaped in a link when stored to Org.
9451 This is the list that is used for internal purposes.")
9453 (defun org-make-link-string (link &optional description)
9454 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9455 (unless (org-string-nw-p link) (error "Empty link"))
9456 (let ((uri (cond ((string-match org-link-types-re link)
9457 (concat (match-string 1 link)
9458 (org-link-escape (substring link (match-end 1)))))
9459 ((or (file-name-absolute-p link)
9460 (string-match-p "\\`\\.\\.?/" link))
9461 (org-link-escape link))
9462 ;; For readability, do not encode space characters
9463 ;; in fuzzy links.
9464 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9465 (description
9466 (and (org-string-nw-p description)
9467 ;; Remove brackets from description, as they are fatal.
9468 (replace-regexp-in-string
9469 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9470 (org-trim description)))))
9471 (format "[[%s]%s]"
9473 (if description (format "[%s]" description) ""))))
9475 (defun org-link-escape (text &optional table merge)
9476 "Return percent escaped representation of TEXT.
9477 TEXT is a string with the text to escape.
9478 Optional argument TABLE is a list with characters that should be
9479 escaped. When nil, `org-link-escape-chars' is used.
9480 If optional argument MERGE is set, merge TABLE into
9481 `org-link-escape-chars'."
9482 (let ((characters-to-encode
9483 (cond ((null table) org-link-escape-chars)
9484 (merge (append org-link-escape-chars table))
9485 (t table))))
9486 (mapconcat
9487 (lambda (c)
9488 (if (or (memq c characters-to-encode)
9489 (and org-url-hexify-p (or (< c 32) (> c 126))))
9490 (mapconcat (lambda (e) (format "%%%.2X" e))
9491 (or (encode-coding-char c 'utf-8)
9492 (error "Unable to percent escape character: %c" c))
9494 (char-to-string c)))
9495 text "")))
9497 (defun org-link-unescape (str)
9498 "Unhex hexified Unicode parts in string STR.
9499 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9500 reciprocal of `org-link-escape', which see."
9501 (if (org-string-nw-p str)
9502 (replace-regexp-in-string
9503 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9504 str))
9506 (defun org-link-unescape-compound (hex)
9507 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9508 Note: this function also decodes single byte encodings like
9509 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9510 (save-match-data
9511 (let* ((bytes (cdr (split-string hex "%")))
9512 (ret "")
9513 (eat 0)
9514 (sum 0))
9515 (while bytes
9516 (let* ((val (string-to-number (pop bytes) 16))
9517 (shift-xor
9518 (if (= 0 eat)
9519 (cond
9520 ((>= val 252) (cons 6 252))
9521 ((>= val 248) (cons 5 248))
9522 ((>= val 240) (cons 4 240))
9523 ((>= val 224) (cons 3 224))
9524 ((>= val 192) (cons 2 192))
9525 (t (cons 0 0)))
9526 (cons 6 128))))
9527 (when (>= val 192) (setq eat (car shift-xor)))
9528 (setq val (logxor val (cdr shift-xor)))
9529 (setq sum (+ (lsh sum (car shift-xor)) val))
9530 (when (> eat 0) (setq eat (- eat 1)))
9531 (cond
9532 ((= 0 eat) ;multi byte
9533 (setq ret (concat ret (char-to-string sum)))
9534 (setq sum 0))
9535 ((not bytes) ; single byte(s)
9536 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9537 ret)))
9539 (defun org-link-unescape-single-byte-sequence (hex)
9540 "Unhexify hex-encoded single byte character sequences."
9541 (mapconcat (lambda (byte)
9542 (char-to-string (string-to-number byte 16)))
9543 (cdr (split-string hex "%")) ""))
9545 (defun org-fixup-message-id-for-http (s)
9546 "Replace special characters in a message id, so it can be used in an http query."
9547 (when (string-match "%" s)
9548 (setq s (mapconcat (lambda (c)
9549 (if (eq c ?%)
9550 "%25"
9551 (char-to-string c)))
9552 s "")))
9553 (while (string-match "<" s)
9554 (setq s (replace-match "%3C" t t s)))
9555 (while (string-match ">" s)
9556 (setq s (replace-match "%3E" t t s)))
9557 (while (string-match "@" s)
9558 (setq s (replace-match "%40" t t s)))
9561 (defun org-link-prettify (link)
9562 "Return a human-readable representation of LINK.
9563 The car of LINK must be a raw link.
9564 The cdr of LINK must be either a link description or nil."
9565 (let ((desc (or (cadr link) "<no description>")))
9566 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9567 "<" (car link) ">")))
9569 ;;;###autoload
9570 (defun org-insert-link-global ()
9571 "Insert a link like Org mode does.
9572 This command can be called in any mode to insert a link in Org syntax."
9573 (interactive)
9574 (org-load-modules-maybe)
9575 (org-run-like-in-org-mode 'org-insert-link))
9577 (defun org-insert-all-links (arg &optional pre post)
9578 "Insert all links in `org-stored-links'.
9579 When a universal prefix, do not delete the links from `org-stored-links'.
9580 When `ARG' is a number, insert the last N link(s).
9581 `PRE' and `POST' are optional arguments to define a string to
9582 prepend or to append."
9583 (interactive "P")
9584 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9585 (links (copy-sequence org-stored-links))
9586 (pr (or pre "- "))
9587 (po (or post "\n"))
9588 (cnt 1) l)
9589 (if (null org-stored-links)
9590 (message "No link to insert")
9591 (while (and (or (listp arg) (>= arg cnt))
9592 (setq l (if (listp arg)
9593 (pop links)
9594 (pop org-stored-links))))
9595 (setq cnt (1+ cnt))
9596 (insert pr)
9597 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9598 (insert po)))))
9600 (defun org-insert-last-stored-link (arg)
9601 "Insert the last link stored in `org-stored-links'."
9602 (interactive "p")
9603 (org-insert-all-links arg "" "\n"))
9605 (defun org-link-fontify-links-to-this-file ()
9606 "Fontify links to the current file in `org-stored-links'."
9607 (let ((f (buffer-file-name)) a b)
9608 (setq a (mapcar (lambda(l)
9609 (let ((ll (car l)))
9610 (when (and (string-match "^file:\\(.+\\)::" ll)
9611 (equal f (expand-file-name (match-string 1 ll))))
9612 ll)))
9613 org-stored-links))
9614 (when (featurep 'org-id)
9615 (setq b (mapcar (lambda(l)
9616 (let ((ll (car l)))
9617 (when (and (string-match "^id:\\(.+\\)$" ll)
9618 (equal f (expand-file-name
9619 (or (org-id-find-id-file
9620 (match-string 1 ll)) ""))))
9621 ll)))
9622 org-stored-links)))
9623 (mapcar (lambda(l)
9624 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9625 (delq nil (append a b)))))
9627 (defvar org--links-history nil)
9628 (defun org-insert-link (&optional complete-file link-location default-description)
9629 "Insert a link. At the prompt, enter the link.
9631 Completion can be used to insert any of the link protocol prefixes in use.
9633 The history can be used to select a link previously stored with
9634 `org-store-link'. When the empty string is entered (i.e. if you just
9635 press `RET' at the prompt), the link defaults to the most recently
9636 stored link. As `SPC' triggers completion in the minibuffer, you need to
9637 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9639 You will also be prompted for a description, and if one is given, it will
9640 be displayed in the buffer instead of the link.
9642 If there is already a link at point, this command will allow you to edit
9643 link and description parts.
9645 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9646 file name can be
9647 selected using completion. The path to the file will be relative to the
9648 current directory if the file is in the current directory or a subdirectory.
9649 Otherwise, the link will be the absolute path as completed in the minibuffer
9650 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9651 option `org-link-file-path-type'.
9653 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9654 absolute path even if the file is in
9655 the current directory or below.
9657 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9658 prefix negates `org-keep-stored-link-after-insertion'.
9660 If the LINK-LOCATION parameter is non-nil, this value will be used as
9661 the link location instead of reading one interactively.
9663 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9664 be used as the default description. Otherwise, if
9665 `org-make-link-description-function' is non-nil, this function
9666 will be called with the link target, and the result will be the
9667 default link description. When called non-interactivily, don't
9668 allow to edit the default description."
9669 (interactive "P")
9670 (let* ((wcf (current-window-configuration))
9671 (origbuf (current-buffer))
9672 (region (when (org-region-active-p)
9673 (buffer-substring (region-beginning) (region-end))))
9674 (remove (and region (list (region-beginning) (region-end))))
9675 (desc region)
9676 (link link-location)
9677 (abbrevs org-link-abbrev-alist-local)
9678 entry all-prefixes auto-desc)
9679 (cond
9680 (link-location) ; specified by arg, just use it.
9681 ((org-in-regexp org-bracket-link-regexp 1)
9682 ;; We do have a link at point, and we are going to edit it.
9683 (setq remove (list (match-beginning 0) (match-end 0)))
9684 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9685 (setq link (read-string "Link: "
9686 (org-link-unescape
9687 (match-string-no-properties 1)))))
9688 ((or (org-in-regexp org-angle-link-re)
9689 (org-in-regexp org-plain-link-re))
9690 ;; Convert to bracket link
9691 (setq remove (list (match-beginning 0) (match-end 0))
9692 link (read-string "Link: "
9693 (org-unbracket-string "<" ">" (match-string 0)))))
9694 ((member complete-file '((4) (16)))
9695 ;; Completing read for file names.
9696 (setq link (org-file-complete-link complete-file)))
9698 ;; Read link, with completion for stored links.
9699 (org-link-fontify-links-to-this-file)
9700 (org-switch-to-buffer-other-window "*Org Links*")
9701 (with-current-buffer "*Org Links*"
9702 (erase-buffer)
9703 (insert "Insert a link.
9704 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9705 (when org-stored-links
9706 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9707 (insert (mapconcat 'org-link-prettify
9708 (reverse org-stored-links) "\n")))
9709 (goto-char (point-min)))
9710 (let ((cw (selected-window)))
9711 (select-window (get-buffer-window "*Org Links*" 'visible))
9712 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9713 (unless (pos-visible-in-window-p (point-max))
9714 (org-fit-window-to-buffer))
9715 (and (window-live-p cw) (select-window cw)))
9716 (setq all-prefixes (append (mapcar 'car abbrevs)
9717 (mapcar 'car org-link-abbrev-alist)
9718 (org-link-types)))
9719 (unwind-protect
9720 ;; Fake a link history, containing the stored links.
9721 (let ((org--links-history
9722 (append (mapcar #'car org-stored-links)
9723 org-insert-link-history)))
9724 (setq link
9725 (org-completing-read
9726 "Link: "
9727 (append
9728 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9729 (mapcar #'car org-stored-links))
9730 nil nil nil
9731 'org--links-history
9732 (caar org-stored-links)))
9733 (unless (org-string-nw-p link) (user-error "No link selected"))
9734 (dolist (l org-stored-links)
9735 (when (equal link (cadr l))
9736 (setq link (car l))
9737 (setq auto-desc t)))
9738 (when (or (member link all-prefixes)
9739 (and (equal ":" (substring link -1))
9740 (member (substring link 0 -1) all-prefixes)
9741 (setq link (substring link 0 -1))))
9742 (setq link (with-current-buffer origbuf
9743 (org-link-try-special-completion link)))))
9744 (set-window-configuration wcf)
9745 (kill-buffer "*Org Links*"))
9746 (setq entry (assoc link org-stored-links))
9747 (or entry (push link org-insert-link-history))
9748 (setq desc (or desc (nth 1 entry)))))
9750 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9751 (not org-keep-stored-link-after-insertion))
9752 (setq org-stored-links (delq (assoc link org-stored-links)
9753 org-stored-links)))
9755 (when (and (string-match org-plain-link-re link)
9756 (not (string-match org-ts-regexp link)))
9757 ;; URL-like link, normalize the use of angular brackets.
9758 (setq link (org-unbracket-string "<" ">" link)))
9760 ;; Check if we are linking to the current file with a search
9761 ;; option If yes, simplify the link by using only the search
9762 ;; option.
9763 (when (and buffer-file-name
9764 (let ((case-fold-search nil))
9765 (string-match "\\`file:\\(.+?\\)::" link)))
9766 (let ((path (match-string-no-properties 1 link))
9767 (search (substring-no-properties link (match-end 0))))
9768 (save-match-data
9769 (when (equal (file-truename buffer-file-name) (file-truename path))
9770 ;; We are linking to this same file, with a search option
9771 (setq link search)))))
9773 ;; Check if we can/should use a relative path. If yes, simplify
9774 ;; the link.
9775 (let ((case-fold-search nil))
9776 (when (string-match "\\`\\(file\\|docview\\):" link)
9777 (let* ((type (match-string-no-properties 0 link))
9778 (path-start (match-end 0))
9779 (search (and (string-match "::\\(.*\\)\\'" link)
9780 (match-string 1 link)))
9781 (path
9782 (if search
9783 (substring-no-properties
9784 link path-start (match-beginning 0))
9785 (substring-no-properties link (match-end 0))))
9786 (origpath path))
9787 (cond
9788 ((or (eq org-link-file-path-type 'absolute)
9789 (equal complete-file '(16)))
9790 (setq path (abbreviate-file-name (expand-file-name path))))
9791 ((eq org-link-file-path-type 'noabbrev)
9792 (setq path (expand-file-name path)))
9793 ((eq org-link-file-path-type 'relative)
9794 (setq path (file-relative-name path)))
9796 (save-match-data
9797 (if (string-match (concat "^" (regexp-quote
9798 (expand-file-name
9799 (file-name-as-directory
9800 default-directory))))
9801 (expand-file-name path))
9802 ;; We are linking a file with relative path name.
9803 (setq path (substring (expand-file-name path)
9804 (match-end 0)))
9805 (setq path (abbreviate-file-name (expand-file-name path)))))))
9806 (setq link (concat type path (and search (concat "::" search))))
9807 (when (equal desc origpath)
9808 (setq desc path)))))
9810 (unless auto-desc
9811 (let ((initial-input
9812 (cond
9813 (default-description)
9814 ((not org-make-link-description-function) desc)
9815 (t (condition-case nil
9816 (funcall org-make-link-description-function link desc)
9817 (error
9818 (message "Can't get link description from `%s'"
9819 (symbol-name org-make-link-description-function))
9820 (sit-for 2)
9821 nil))))))
9822 (setq desc (if (called-interactively-p 'any)
9823 (read-string "Description: " initial-input)
9824 initial-input))))
9826 (unless (string-match "\\S-" desc) (setq desc nil))
9827 (when remove (apply 'delete-region remove))
9828 (insert (org-make-link-string link desc))
9829 ;; Redisplay so as the new link has proper invisible characters.
9830 (sit-for 0)))
9832 (defun org-link-try-special-completion (type)
9833 "If there is completion support for link type TYPE, offer it."
9834 (let ((fun (org-link-get-parameter type :complete)))
9835 (if (functionp fun)
9836 (funcall fun)
9837 (read-string "Link (no completion support): " (concat type ":")))))
9839 (defun org-file-complete-link (&optional arg)
9840 "Create a file link using completion."
9841 (let ((file (read-file-name "File: "))
9842 (pwd (file-name-as-directory (expand-file-name ".")))
9843 (pwd1 (file-name-as-directory (abbreviate-file-name
9844 (expand-file-name ".")))))
9845 (cond ((equal arg '(16))
9846 (concat "file:"
9847 (abbreviate-file-name (expand-file-name file))))
9848 ((string-match
9849 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9850 (concat "file:" (match-string 1 file)))
9851 ((string-match
9852 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9853 (expand-file-name file))
9854 (concat "file:"
9855 (match-string 1 (expand-file-name file))))
9856 (t (concat "file:" file)))))
9859 ;;; Opening/following a link
9861 (defvar org-link-search-failed nil)
9863 (defvar org-open-link-functions nil
9864 "Hook for functions finding a plain text link.
9865 These functions must take a single argument, the link content.
9866 They will be called for links that look like [[link text][description]]
9867 when LINK TEXT does not have a protocol like \"http:\" and does not look
9868 like a filename (e.g. \"./blue.png\").
9870 These functions will be called *before* Org attempts to resolve the
9871 link by doing text searches in the current buffer - so if you want a
9872 link \"[[target]]\" to still find \"<<target>>\", your function should
9873 handle this as a special case.
9875 When the function does handle the link, it must return a non-nil value.
9876 If it decides that it is not responsible for this link, it must return
9877 nil to indicate that that Org can continue with other options like
9878 exact and fuzzy text search.")
9880 (defun org-next-link (&optional search-backward)
9881 "Move forward to the next link.
9882 If the link is in hidden text, expose it."
9883 (interactive "P")
9884 (when (and org-link-search-failed (eq this-command last-command))
9885 (goto-char (point-min))
9886 (message "Link search wrapped back to beginning of buffer"))
9887 (setq org-link-search-failed nil)
9888 (let* ((pos (point))
9889 (ct (org-context))
9890 (a (assq :link ct))
9891 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9892 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9893 ((looking-at org-any-link-re)
9894 ;; Don't stay stuck at link without an org-link face
9895 (forward-char (if search-backward -1 1))))
9896 (if (funcall srch-fun org-any-link-re nil t)
9897 (progn
9898 (goto-char (match-beginning 0))
9899 (when (org-invisible-p) (org-show-context)))
9900 (goto-char pos)
9901 (setq org-link-search-failed t)
9902 (message "No further link found"))))
9904 (defun org-previous-link ()
9905 "Move backward to the previous link.
9906 If the link is in hidden text, expose it."
9907 (interactive)
9908 (funcall 'org-next-link t))
9910 (defun org-translate-link (s)
9911 "Translate a link string if a translation function has been defined."
9912 (with-temp-buffer
9913 (insert (org-trim s))
9914 (org-trim (org-element-interpret-data (org-element-context)))))
9916 (defun org-translate-link-from-planner (type path)
9917 "Translate a link from Emacs Planner syntax so that Org can follow it.
9918 This is still an experimental function, your mileage may vary."
9919 (cond
9920 ((member type '("http" "https" "news" "ftp"))
9921 ;; standard Internet links are the same.
9922 nil)
9923 ((and (equal type "irc") (string-match "^//" path))
9924 ;; Planner has two / at the beginning of an irc link, we have 1.
9925 ;; We should have zero, actually....
9926 (setq path (substring path 1)))
9927 ((and (equal type "lisp") (string-match "^/" path))
9928 ;; Planner has a slash, we do not.
9929 (setq type "elisp" path (substring path 1)))
9930 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9931 ;; A typical message link. Planner has the id after the final slash,
9932 ;; we separate it with a hash mark
9933 (setq path (concat (match-string 1 path) "#"
9934 (org-unbracket-string "<" ">" (match-string 2 path))))))
9935 (cons type path))
9937 (defun org-find-file-at-mouse (ev)
9938 "Open file link or URL at mouse."
9939 (interactive "e")
9940 (mouse-set-point ev)
9941 (org-open-at-point 'in-emacs))
9943 (defun org-open-at-mouse (ev)
9944 "Open file link or URL at mouse.
9945 See the docstring of `org-open-file' for details."
9946 (interactive "e")
9947 (mouse-set-point ev)
9948 (when (eq major-mode 'org-agenda-mode)
9949 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9950 (org-open-at-point))
9952 (defvar org-window-config-before-follow-link nil
9953 "The window configuration before following a link.
9954 This is saved in case the need arises to restore it.")
9956 ;;;###autoload
9957 (defun org-open-at-point-global ()
9958 "Follow a link or a time-stamp like Org mode does.
9959 Also follow links and emails as seen by `thing-at-point'.
9960 This command can be called in any mode to follow an external
9961 link or a time-stamp that has Org mode syntax. Its behavior
9962 is undefined when called on internal links like fuzzy links.
9963 Raise a user error when there is nothing to follow."
9964 (interactive)
9965 (let ((tap-url (thing-at-point 'url))
9966 (tap-email (thing-at-point 'email)))
9967 (cond ((org-in-regexp org-any-link-re)
9968 (org-open-link-from-string (match-string-no-properties 0)))
9969 ((or (org-in-regexp org-ts-regexp-both nil t)
9970 (org-in-regexp org-tsr-regexp-both nil t))
9971 (org-follow-timestamp-link))
9972 (tap-url (org-open-link-from-string tap-url))
9973 (tap-email (org-open-link-from-string
9974 (concat "mailto:" tap-email)))
9975 (t (user-error "No link found")))))
9977 ;;;###autoload
9978 (defun org-open-link-from-string (s &optional arg reference-buffer)
9979 "Open a link in the string S, as if it was in Org mode."
9980 (interactive "sLink: \nP")
9981 (let ((reference-buffer (or reference-buffer (current-buffer))))
9982 (with-temp-buffer
9983 (let ((org-inhibit-startup (not reference-buffer)))
9984 (org-mode)
9985 (insert s)
9986 (goto-char (point-min))
9987 (when reference-buffer
9988 (setq org-link-abbrev-alist-local
9989 (with-current-buffer reference-buffer
9990 org-link-abbrev-alist-local)))
9991 (org-open-at-point arg reference-buffer)))))
9993 (defvar org-open-at-point-functions nil
9994 "Hook that is run when following a link at point.
9996 Functions in this hook must return t if they identify and follow
9997 a link at point. If they don't find anything interesting at point,
9998 they must return nil.")
10000 (defvar org-link-search-inhibit-query nil)
10001 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10002 (defun org--open-doi-link (path)
10003 "Open a \"doi\" type link.
10004 PATH is a the path to search for, as a string."
10005 (browse-url (url-encode-url (concat org-doi-server-url path))))
10007 (defun org--open-elisp-link (path)
10008 "Open a \"elisp\" type link.
10009 PATH is the sexp to evaluate, as a string."
10010 (let ((cmd path))
10011 (if (or (and (org-string-nw-p
10012 org-confirm-elisp-link-not-regexp)
10013 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10014 (not org-confirm-elisp-link-function)
10015 (funcall org-confirm-elisp-link-function
10016 (format "Execute \"%s\" as elisp? "
10017 (org-add-props cmd nil 'face 'org-warning))))
10018 (message "%s => %s" cmd
10019 (if (eq (string-to-char cmd) ?\()
10020 (eval (read cmd))
10021 (call-interactively (read cmd))))
10022 (user-error "Abort"))))
10024 (defun org--open-help-link (path)
10025 "Open a \"help\" type link.
10026 PATH is a symbol name, as a string."
10027 (pcase (intern path)
10028 ((and (pred fboundp) variable) (describe-function variable))
10029 ((and (pred boundp) function) (describe-variable function))
10030 (name (user-error "Unknown function or variable: %s" name))))
10032 (defun org--open-shell-link (path)
10033 "Open a \"shell\" type link.
10034 PATH is the command to execute, as a string."
10035 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10036 (cmd path))
10037 (if (or (and (org-string-nw-p
10038 org-confirm-shell-link-not-regexp)
10039 (string-match
10040 org-confirm-shell-link-not-regexp cmd))
10041 (not org-confirm-shell-link-function)
10042 (funcall org-confirm-shell-link-function
10043 (format "Execute \"%s\" in shell? "
10044 (org-add-props cmd nil
10045 'face 'org-warning))))
10046 (progn
10047 (message "Executing %s" cmd)
10048 (shell-command cmd buf)
10049 (when (featurep 'midnight)
10050 (setq clean-buffer-list-kill-buffer-names
10051 (cons (buffer-name buf)
10052 clean-buffer-list-kill-buffer-names))))
10053 (user-error "Abort"))))
10055 (defun org-open-at-point (&optional arg reference-buffer)
10056 "Open link, timestamp, footnote or tags at point.
10058 When point is on a link, follow it. Normally, files will be
10059 opened by an appropriate application. If the optional prefix
10060 argument ARG is non-nil, Emacs will visit the file. With
10061 a double prefix argument, try to open outside of Emacs, in the
10062 application the system uses for this file type.
10064 When point is on a timestamp, open the agenda at the day
10065 specified.
10067 When point is a footnote definition, move to the first reference
10068 found. If it is on a reference, move to the associated
10069 definition.
10071 When point is on a headline, display a list of every link in the
10072 entry, so it is possible to pick one, or all, of them. If point
10073 is on a tag, call `org-tags-view' instead.
10075 When optional argument REFERENCE-BUFFER is non-nil, it should
10076 specify a buffer from where the link search should happen. This
10077 is used internally by `org-open-link-from-string'.
10079 On top of syntactically correct links, this function will also
10080 try to open links and time-stamps in comments, example
10081 blocks... i.e., whenever point is on something looking like
10082 a timestamp or a link."
10083 (interactive "P")
10084 ;; On a code block, open block's results.
10085 (unless (call-interactively 'org-babel-open-src-block-result)
10086 (org-load-modules-maybe)
10087 (setq org-window-config-before-follow-link (current-window-configuration))
10088 (org-remove-occur-highlights nil nil t)
10089 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10090 (let* ((context
10091 ;; Only consider supported types, even if they are not
10092 ;; the closest one.
10093 (org-element-lineage
10094 (org-element-context)
10095 '(clock footnote-definition footnote-reference headline
10096 inlinetask link timestamp)
10098 (type (org-element-type context))
10099 (value (org-element-property :value context)))
10100 (cond
10101 ;; On a headline or an inlinetask, but not on a timestamp,
10102 ;; a link, a footnote reference.
10103 ((memq type '(headline inlinetask))
10104 (org-match-line org-complex-heading-regexp)
10105 (if (and (match-beginning 5)
10106 (>= (point) (match-beginning 5))
10107 (< (point) (match-end 5)))
10108 ;; On tags.
10109 (org-tags-view arg (substring (match-string 5) 0 -1))
10110 ;; Not on tags.
10111 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10112 (`(nil . ,_)
10113 (require 'org-attach)
10114 (org-attach-reveal 'if-exists))
10115 (`(,links . ,links-end)
10116 (dolist (link (if (stringp links) (list links) links))
10117 (search-forward link nil links-end)
10118 (goto-char (match-beginning 0))
10119 (org-open-at-point))))))
10120 ;; On a footnote reference or at definition's label.
10121 ((or (eq type 'footnote-reference)
10122 (and (eq type 'footnote-definition)
10123 (save-excursion
10124 ;; Do not validate action when point is on the
10125 ;; spaces right after the footnote label, in
10126 ;; order to be on par with behavior on links.
10127 (skip-chars-forward " \t")
10128 (let ((begin
10129 (org-element-property :contents-begin context)))
10130 (if begin (< (point) begin)
10131 (= (org-element-property :post-affiliated context)
10132 (line-beginning-position)))))))
10133 (org-footnote-action))
10134 ;; No valid context. Ignore catch-all types like `headline'.
10135 ;; If point is on something looking like a link or
10136 ;; a time-stamp, try opening it. It may be useful in
10137 ;; comments, example blocks...
10138 ((memq type '(footnote-definition headline inlinetask nil))
10139 (call-interactively #'org-open-at-point-global))
10140 ;; On a clock line, make sure point is on the timestamp
10141 ;; before opening it.
10142 ((and (eq type 'clock)
10143 value
10144 (>= (point) (org-element-property :begin value))
10145 (<= (point) (org-element-property :end value)))
10146 (org-follow-timestamp-link))
10147 ;; Do nothing on white spaces after an object.
10148 ((>= (point)
10149 (save-excursion
10150 (goto-char (org-element-property :end context))
10151 (skip-chars-backward " \t")
10152 (point)))
10153 (user-error "No link found"))
10154 ((eq type 'timestamp) (org-follow-timestamp-link))
10155 ((eq type 'link)
10156 (let ((type (org-element-property :type context))
10157 (path (org-link-unescape (org-element-property :path context))))
10158 ;; Switch back to REFERENCE-BUFFER needed when called in
10159 ;; a temporary buffer through `org-open-link-from-string'.
10160 (with-current-buffer (or reference-buffer (current-buffer))
10161 (cond
10162 ((equal type "file")
10163 (if (string-match "[*?{]" (file-name-nondirectory path))
10164 (dired path)
10165 ;; Look into `org-link-parameters' in order to find
10166 ;; a DEDICATED-FUNCTION to open file. The function
10167 ;; will be applied on raw link instead of parsed
10168 ;; link due to the limitation in `org-add-link-type'
10169 ;; ("open" function called with a single argument).
10170 ;; If no such function is found, fallback to
10171 ;; `org-open-file'.
10172 (let* ((option (org-element-property :search-option context))
10173 (app (org-element-property :application context))
10174 (dedicated-function
10175 (org-link-get-parameter
10176 (if app (concat type "+" app) type)
10177 :follow)))
10178 (if dedicated-function
10179 (funcall dedicated-function
10180 (concat path
10181 (and option (concat "::" option))))
10182 (apply #'org-open-file
10183 path
10184 (cond (arg)
10185 ((equal app "emacs") 'emacs)
10186 ((equal app "sys") 'system))
10187 (cond ((not option) nil)
10188 ((string-match-p "\\`[0-9]+\\'" option)
10189 (list (string-to-number option)))
10190 (t (list nil
10191 (org-link-unescape option)))))))))
10192 ((functionp (org-link-get-parameter type :follow))
10193 (funcall (org-link-get-parameter type :follow) path))
10194 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10195 (unless (run-hook-with-args-until-success
10196 'org-open-link-functions path)
10197 (if (not arg) (org-mark-ring-push)
10198 (switch-to-buffer-other-window
10199 (org-get-buffer-for-internal-link (current-buffer))))
10200 (let ((destination
10201 (org-with-wide-buffer
10202 (if (equal type "radio")
10203 (org-search-radio-target
10204 (org-element-property :path context))
10205 (org-link-search
10206 (if (member type '("custom-id" "coderef"))
10207 (org-element-property :raw-link context)
10208 path)
10209 ;; Prevent fuzzy links from matching
10210 ;; themselves.
10211 (and (equal type "fuzzy")
10212 (+ 2 (org-element-property :begin context)))))
10213 (point))))
10214 (unless (and (<= (point-min) destination)
10215 (>= (point-max) destination))
10216 (widen))
10217 (goto-char destination))))
10218 (t (browse-url-at-point))))))
10219 (t (user-error "No link found")))))
10220 (run-hook-with-args 'org-follow-link-hook)))
10222 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10223 "Offer links in the current entry and return the selected link.
10224 If there is only one link, return it.
10225 If NTH is an integer, return the NTH link found.
10226 If ZERO is a string, check also this string for a link, and if
10227 there is one, return it."
10228 (with-current-buffer buffer
10229 (org-with-wide-buffer
10230 (goto-char marker)
10231 (let ((cnt ?0)
10232 have-zero end links link c)
10233 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10234 (push (match-string 0 zero) links)
10235 (setq cnt (1- cnt) have-zero t))
10236 (save-excursion
10237 (org-back-to-heading t)
10238 (setq end (save-excursion (outline-next-heading) (point)))
10239 (while (re-search-forward org-any-link-re end t)
10240 (push (match-string 0) links))
10241 (setq links (org-uniquify (reverse links))))
10242 (cond
10243 ((null links)
10244 (message "No links"))
10245 ((equal (length links) 1)
10246 (setq link (car links)))
10247 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10248 (setq link (nth (if have-zero nth (1- nth)) links)))
10249 (t ; we have to select a link
10250 (save-excursion
10251 (save-window-excursion
10252 (delete-other-windows)
10253 (with-output-to-temp-buffer "*Select Link*"
10254 (dolist (l links)
10255 (cond
10256 ((not (string-match org-bracket-link-regexp l))
10257 (princ (format "[%c] %s\n" (cl-incf cnt)
10258 (org-unbracket-string "<" ">" l))))
10259 ((match-end 3)
10260 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10261 (match-string 3 l) (match-string 1 l))))
10262 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10263 (match-string 1 l)))))))
10264 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10265 (message "Select link to open, RET to open all:")
10266 (setq c (read-char-exclusive))
10267 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10268 (when (equal c ?q) (user-error "Abort"))
10269 (if (equal c ?\C-m)
10270 (setq link links)
10271 (setq nth (- c ?0))
10272 (when have-zero (setq nth (1+ nth)))
10273 (unless (and (integerp nth) (>= (length links) nth))
10274 (user-error "Invalid link selection"))
10275 (setq link (nth (1- nth) links)))))
10276 (cons link end)))))
10278 ;; TODO: These functions are deprecated since `org-open-at-point'
10279 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10280 (defun org-open-file-with-system (path)
10281 "Open file at PATH using the system way of opening it."
10282 (org-open-file path 'system))
10283 (defun org-open-file-with-emacs (path)
10284 "Open file at PATH in Emacs."
10285 (org-open-file path 'emacs))
10288 ;;; File search
10290 (defvar org-create-file-search-functions nil
10291 "List of functions to construct the right search string for a file link.
10292 These functions are called in turn with point at the location to
10293 which the link should point.
10295 A function in the hook should first test if it would like to
10296 handle this file type, for example by checking the `major-mode'
10297 or the file extension. If it decides not to handle this file, it
10298 should just return nil to give other functions a chance. If it
10299 does handle the file, it must return the search string to be used
10300 when following the link. The search string will be part of the
10301 file link, given after a double colon, and `org-open-at-point'
10302 will automatically search for it. If special measures must be
10303 taken to make the search successful, another function should be
10304 added to the companion hook `org-execute-file-search-functions',
10305 which see.
10307 A function in this hook may also use `setq' to set the variable
10308 `description' to provide a suggestion for the descriptive text to
10309 be used for this link when it gets inserted into an Org buffer
10310 with \\[org-insert-link].")
10312 (defvar org-execute-file-search-functions nil
10313 "List of functions to execute a file search triggered by a link.
10315 Functions added to this hook must accept a single argument, the
10316 search string that was part of the file link, the part after the
10317 double colon. The function must first check if it would like to
10318 handle this search, for example by checking the `major-mode' or
10319 the file extension. If it decides not to handle this search, it
10320 should just return nil to give other functions a chance. If it
10321 does handle the search, it must return a non-nil value to keep
10322 other functions from trying.
10324 Each function can access the current prefix argument through the
10325 variable `current-prefix-arg'. Note that a single prefix is used
10326 to force opening a link in Emacs, so it may be good to only use a
10327 numeric or double prefix to guide the search function.
10329 In case this is needed, a function in this hook can also restore
10330 the window configuration before `org-open-at-point' was called using:
10332 (set-window-configuration org-window-config-before-follow-link)")
10334 (defun org-search-radio-target (target)
10335 "Search a radio target matching TARGET in current buffer.
10336 White spaces are not significant."
10337 (let ((re (format "<<<%s>>>"
10338 (mapconcat #'regexp-quote
10339 (split-string target)
10340 "[ \t]+\\(?:\n[ \t]*\\)?")))
10341 (origin (point)))
10342 (goto-char (point-min))
10343 (catch :radio-match
10344 (while (re-search-forward re nil t)
10345 (backward-char)
10346 (let ((object (org-element-context)))
10347 (when (eq (org-element-type object) 'radio-target)
10348 (goto-char (org-element-property :begin object))
10349 (org-show-context 'link-search)
10350 (throw :radio-match nil))))
10351 (goto-char origin)
10352 (user-error "No match for radio target: %s" target))))
10354 (defun org-link-search (s &optional avoid-pos stealth)
10355 "Search for a search string S.
10357 If S starts with \"#\", it triggers a custom ID search.
10359 If S is enclosed within parenthesis, it initiates a coderef
10360 search.
10362 If S is surrounded by forward slashes, it is interpreted as
10363 a regular expression. In Org mode files, this will create an
10364 `org-occur' sparse tree. In ordinary files, `occur' will be used
10365 to list matches. If the current buffer is in `dired-mode', grep
10366 will be used to search in all files.
10368 When AVOID-POS is given, ignore matches near that position.
10370 When optional argument STEALTH is non-nil, do not modify
10371 visibility around point, thus ignoring `org-show-context-detail'
10372 variable.
10374 Search is case-insensitive and ignores white spaces. Return type
10375 of matched result, which is either `dedicated' or `fuzzy'."
10376 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10377 (let* ((case-fold-search t)
10378 (origin (point))
10379 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10380 (starred (eq (string-to-char normalized) ?*))
10381 (words (split-string (if starred (substring s 1) s)))
10382 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10383 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10384 type)
10385 (cond
10386 ;; Check if there are any special search functions.
10387 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10388 ((eq (string-to-char s) ?#)
10389 ;; Look for a custom ID S if S starts with "#".
10390 (let* ((id (substring normalized 1))
10391 (match (org-find-property "CUSTOM_ID" id)))
10392 (if match (progn (goto-char match) (setf type 'dedicated))
10393 (error "No match for custom ID: %s" id))))
10394 ((string-match "\\`(\\(.*\\))\\'" normalized)
10395 ;; Look for coderef targets if S is enclosed within parenthesis.
10396 (let ((coderef (match-string-no-properties 1 normalized))
10397 (re (substring s-single-re 1 -1)))
10398 (goto-char (point-min))
10399 (catch :coderef-match
10400 (while (re-search-forward re nil t)
10401 (let ((element (org-element-at-point)))
10402 (when (and (memq (org-element-type element)
10403 '(example-block src-block))
10404 ;; Build proper regexp according to current
10405 ;; block's label format.
10406 (let ((label-fmt
10407 (regexp-quote
10408 (or (org-element-property :label-fmt element)
10409 org-coderef-label-format))))
10410 (save-excursion
10411 (beginning-of-line)
10412 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10413 (format label-fmt coderef))))))
10414 (setq type 'dedicated)
10415 (goto-char (match-beginning 1))
10416 (throw :coderef-match nil))))
10417 (goto-char origin)
10418 (error "No match for coderef: %s" coderef))))
10419 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10420 ;; Look for a regular expression.
10421 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10422 (match-string 1 s)))
10423 ;; From here, we handle fuzzy links.
10425 ;; Look for targets, only if not in a headline search.
10426 ((and (not starred)
10427 (let ((target (format "<<%s>>" s-multi-re)))
10428 (catch :target-match
10429 (goto-char (point-min))
10430 (while (re-search-forward target nil t)
10431 (backward-char)
10432 (let ((context (org-element-context)))
10433 (when (eq (org-element-type context) 'target)
10434 (setq type 'dedicated)
10435 (goto-char (org-element-property :begin context))
10436 (throw :target-match t))))
10437 nil))))
10438 ;; Look for elements named after S, only if not in a headline
10439 ;; search.
10440 ((and (not starred)
10441 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10442 (catch :name-match
10443 (goto-char (point-min))
10444 (while (re-search-forward name nil t)
10445 (let ((element (org-element-at-point)))
10446 (when (equal words
10447 (split-string
10448 (org-element-property :name element)))
10449 (setq type 'dedicated)
10450 (beginning-of-line)
10451 (throw :name-match t))))
10452 nil))))
10453 ;; Regular text search. Prefer headlines in Org mode buffers.
10454 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10455 ;; statistics cookies and tags.
10456 ((and (derived-mode-p 'org-mode)
10457 (let ((title-re
10458 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10459 org-outline-regexp-bol
10460 org-comment-string
10461 (mapconcat #'regexp-quote words ".+")))
10462 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10463 (comment-re (eval-when-compile
10464 (format "\\`%s[ \t]+" org-comment-string))))
10465 (goto-char (point-min))
10466 (catch :found
10467 (while (re-search-forward title-re nil t)
10468 (when (equal words
10469 (split-string
10470 (replace-regexp-in-string
10471 cookie-re ""
10472 (replace-regexp-in-string
10473 comment-re "" (org-get-heading t t t)))))
10474 (throw :found t)))
10475 nil)))
10476 (beginning-of-line)
10477 (setq type 'dedicated))
10478 ;; Offer to create non-existent headline depending on
10479 ;; `org-link-search-must-match-exact-headline'.
10480 ((and (derived-mode-p 'org-mode)
10481 (not org-link-search-inhibit-query)
10482 (eq org-link-search-must-match-exact-headline 'query-to-create)
10483 (yes-or-no-p "No match - create this as a new heading? "))
10484 (goto-char (point-max))
10485 (unless (bolp) (newline))
10486 (org-insert-heading nil t t)
10487 (insert s "\n")
10488 (beginning-of-line 0))
10489 ;; Only headlines are looked after. No need to process
10490 ;; further: throw an error.
10491 ((and (derived-mode-p 'org-mode)
10492 (or starred org-link-search-must-match-exact-headline))
10493 (goto-char origin)
10494 (error "No match for fuzzy expression: %s" normalized))
10495 ;; Regular text search.
10496 ((catch :fuzzy-match
10497 (goto-char (point-min))
10498 (while (re-search-forward s-multi-re nil t)
10499 ;; Skip match if it contains AVOID-POS or it is included in
10500 ;; a link with a description but outside the description.
10501 (unless (or (and avoid-pos
10502 (<= (match-beginning 0) avoid-pos)
10503 (> (match-end 0) avoid-pos))
10504 (and (save-match-data
10505 (org-in-regexp org-bracket-link-regexp))
10506 (match-beginning 3)
10507 (or (> (match-beginning 3) (point))
10508 (<= (match-end 3) (point)))
10509 (org-element-lineage
10510 (save-match-data (org-element-context))
10511 '(link) t)))
10512 (goto-char (match-beginning 0))
10513 (setq type 'fuzzy)
10514 (throw :fuzzy-match t)))
10515 nil))
10516 ;; All failed. Throw an error.
10517 (t (goto-char origin)
10518 (error "No match for fuzzy expression: %s" normalized)))
10519 ;; Disclose surroundings of match, if appropriate.
10520 (when (and (derived-mode-p 'org-mode) (not stealth))
10521 (org-show-context 'link-search))
10522 type))
10524 (defun org-get-buffer-for-internal-link (buffer)
10525 "Return a buffer to be used for displaying the link target of internal links."
10526 (cond
10527 ((not org-display-internal-link-with-indirect-buffer)
10528 buffer)
10529 ((string-suffix-p "(Clone)" (buffer-name buffer))
10530 (message "Buffer is already a clone, not making another one")
10531 ;; we also do not modify visibility in this case
10532 buffer)
10533 (t ; make a new indirect buffer for displaying the link
10534 (let* ((bn (buffer-name buffer))
10535 (ibn (concat bn "(Clone)"))
10536 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10537 (with-current-buffer ib (org-overview))
10538 ib))))
10540 (defun org-do-occur (regexp &optional cleanup)
10541 "Call the Emacs command `occur'.
10542 If CLEANUP is non-nil, remove the printout of the regular expression
10543 in the *Occur* buffer. This is useful if the regex is long and not useful
10544 to read."
10545 (occur regexp)
10546 (when cleanup
10547 (let ((cwin (selected-window)) win beg end)
10548 (when (setq win (get-buffer-window "*Occur*"))
10549 (select-window win))
10550 (goto-char (point-min))
10551 (when (re-search-forward "match[a-z]+" nil t)
10552 (setq beg (match-end 0))
10553 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10554 (setq end (1- (match-beginning 0)))))
10555 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10556 (goto-char (point-min))
10557 (select-window cwin))))
10560 ;;; The Mark Ring
10562 (defvar org-mark-ring nil
10563 "Mark ring for positions before jumps in Org mode.")
10565 (defvar org-mark-ring-last-goto nil
10566 "Last position in the mark ring used to go back.")
10568 ;; Fill and close the ring
10569 (setq org-mark-ring nil)
10570 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10572 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10573 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10574 org-mark-ring)
10576 (defun org-mark-ring-push (&optional pos buffer)
10577 "Put the current position into the mark ring and rotate it.
10578 Also push position into the Emacs mark ring. If optional
10579 argument POS and BUFFER are not nil, mark this location instead."
10580 (interactive)
10581 (let ((pos (or pos (point)))
10582 (buffer (or buffer (current-buffer))))
10583 (with-current-buffer buffer
10584 (org-with-point-at pos (push-mark nil t)))
10585 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10586 (move-marker (car org-mark-ring) pos buffer))
10587 (message
10588 (substitute-command-keys
10589 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10591 (defun org-mark-ring-goto (&optional n)
10592 "Jump to the previous position in the mark ring.
10593 With prefix arg N, jump back that many stored positions. When
10594 called several times in succession, walk through the entire ring.
10595 Org mode commands jumping to a different position in the current file,
10596 or to another Org file, automatically push the old position onto the ring."
10597 (interactive "p")
10598 (let (p m)
10599 (if (eq last-command this-command)
10600 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10601 (setq p org-mark-ring))
10602 (setq org-mark-ring-last-goto p)
10603 (setq m (car p))
10604 (pop-to-buffer-same-window (marker-buffer m))
10605 (goto-char m)
10606 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10608 (defun org-add-angle-brackets (s)
10609 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10610 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10613 ;;; Following specific links
10615 (defvar org-agenda-buffer-tmp-name)
10616 (defvar org-agenda-start-on-weekday)
10617 (defun org-follow-timestamp-link ()
10618 "Open an agenda view for the time-stamp date/range at point."
10619 (cond
10620 ((org-at-date-range-p t)
10621 (let ((org-agenda-start-on-weekday)
10622 (t1 (match-string 1))
10623 (t2 (match-string 2)) tt1 tt2)
10624 (setq tt1 (time-to-days (org-time-string-to-time t1))
10625 tt2 (time-to-days (org-time-string-to-time t2)))
10626 (let ((org-agenda-buffer-tmp-name
10627 (format "*Org Agenda(a:%s)"
10628 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10629 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10630 ((org-at-timestamp-p 'lax)
10631 (let ((org-agenda-buffer-tmp-name
10632 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10633 (org-agenda-list nil (time-to-days (org-time-string-to-time
10634 (substring (match-string 1) 0 10)))
10635 1)))
10636 (t (error "This should not happen"))))
10639 ;;; Following file links
10640 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10641 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10642 (declare-function mailcap-mime-info
10643 "mailcap" (string &optional request no-decode))
10644 (defvar org-wait nil)
10645 (defun org-open-file (path &optional in-emacs line search)
10646 "Open the file at PATH.
10647 First, this expands any special file name abbreviations. Then the
10648 configuration variable `org-file-apps' is checked if it contains an
10649 entry for this file type, and if yes, the corresponding command is launched.
10651 If no application is found, Emacs simply visits the file.
10653 With optional prefix argument IN-EMACS, Emacs will visit the file.
10654 With a double \\[universal-argument] \\[universal-argument] \
10655 prefix arg, Org tries to avoid opening in Emacs
10656 and to use an external application to visit the file.
10658 Optional LINE specifies a line to go to, optional SEARCH a string
10659 to search for. If LINE or SEARCH is given, the file will be
10660 opened in Emacs, unless an entry from org-file-apps that makes
10661 use of groups in a regexp matches.
10663 If you want to change the way frames are used when following a
10664 link, please customize `org-link-frame-setup'.
10666 If the file does not exist, an error is thrown."
10667 (let* ((file (if (equal path "")
10668 buffer-file-name
10669 (substitute-in-file-name (expand-file-name path))))
10670 (file-apps (append org-file-apps (org-default-apps)))
10671 (apps (cl-remove-if
10672 'org-file-apps-entry-match-against-dlink-p file-apps))
10673 (apps-dlink (cl-remove-if-not
10674 'org-file-apps-entry-match-against-dlink-p file-apps))
10675 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10676 (dirp (unless remp (file-directory-p file)))
10677 (file (if (and dirp org-open-directory-means-index-dot-org)
10678 (concat (file-name-as-directory file) "index.org")
10679 file))
10680 (a-m-a-p (assq 'auto-mode apps))
10681 (dfile (downcase file))
10682 ;; Reconstruct the original link from the PATH, LINE and
10683 ;; SEARCH args.
10684 (link (cond (line (concat file "::" (number-to-string line)))
10685 (search (concat file "::" search))
10686 (t file)))
10687 (dlink (downcase link))
10688 (ext
10689 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10690 (match-string 1 dfile)))
10691 (save-position-maybe
10692 (let ((old-buffer (current-buffer))
10693 (old-pos (point))
10694 (old-mode major-mode))
10695 (lambda ()
10696 (and (derived-mode-p 'org-mode)
10697 (eq old-mode 'org-mode)
10698 (or (not (eq old-buffer (current-buffer)))
10699 (not (eq old-pos (point))))
10700 (org-mark-ring-push old-pos old-buffer)))))
10701 cmd link-match-data)
10702 (cond
10703 ((member in-emacs '((16) system))
10704 (setq cmd (cdr (assq 'system apps))))
10705 (in-emacs (setq cmd 'emacs))
10707 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10708 (and dirp (cdr (assq 'directory apps)))
10709 ;; First, try matching against apps-dlink if we
10710 ;; get a match here, store the match data for
10711 ;; later.
10712 (let ((match (assoc-default dlink apps-dlink
10713 'string-match)))
10714 (if match
10715 (progn (setq link-match-data (match-data))
10716 match)
10717 (progn (setq in-emacs (or in-emacs line search))
10718 nil))) ; if we have no match in apps-dlink,
10719 ; always open the file in emacs if line or search
10720 ; is given (for backwards compatibility)
10721 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10722 'string-match)
10723 (cdr (assoc ext apps))
10724 (cdr (assq t apps))))))
10725 (when (eq cmd 'system)
10726 (setq cmd (cdr (assq 'system apps))))
10727 (when (eq cmd 'default)
10728 (setq cmd (cdr (assoc t apps))))
10729 (when (eq cmd 'mailcap)
10730 (require 'mailcap)
10731 (mailcap-parse-mailcaps)
10732 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10733 (command (mailcap-mime-info mime-type)))
10734 (if (stringp command)
10735 (setq cmd command)
10736 (setq cmd 'emacs))))
10737 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10738 (not (file-exists-p file))
10739 (not org-open-non-existing-files))
10740 (user-error "No such file: %s" file))
10741 (cond
10742 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10743 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10744 (while (string-match "['\"]%s['\"]" cmd)
10745 (setq cmd (replace-match "%s" t t cmd)))
10746 (setq cmd (replace-regexp-in-string
10747 "%s"
10748 (shell-quote-argument (convert-standard-filename file))
10750 nil t))
10752 ;; Replace "%1", "%2" etc. in command with group matches from regex
10753 (save-match-data
10754 (let ((match-index 1)
10755 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10756 (set-match-data link-match-data)
10757 (while (<= match-index number-of-groups)
10758 (let ((regex (concat "%" (number-to-string match-index)))
10759 (replace-with (match-string match-index dlink)))
10760 (while (string-match regex cmd)
10761 (setq cmd (replace-match replace-with t t cmd))))
10762 (setq match-index (+ match-index 1)))))
10764 (save-window-excursion
10765 (message "Running %s...done" cmd)
10766 (start-process-shell-command cmd nil cmd)
10767 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10768 ((or (stringp cmd)
10769 (eq cmd 'emacs))
10770 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10771 (widen)
10772 (cond (line (org-goto-line line)
10773 (when (derived-mode-p 'org-mode) (org-reveal)))
10774 (search (condition-case err
10775 (org-link-search search)
10776 ;; Save position before error-ing out so user
10777 ;; can easily move back to the original buffer.
10778 (error (funcall save-position-maybe)
10779 (error (nth 1 err)))))))
10780 ((functionp cmd)
10781 (save-match-data
10782 (set-match-data link-match-data)
10783 (condition-case nil
10784 (funcall cmd file link)
10785 ;; FIXME: Remove this check when most default installations
10786 ;; of Emacs have at least Org 9.0.
10787 ((debug wrong-number-of-arguments wrong-type-argument
10788 invalid-function)
10789 (user-error "Please see Org News for version 9.0 about \
10790 `org-file-apps'--Lisp error: %S" cmd)))))
10791 ((consp cmd)
10792 ;; FIXME: Remove this check when most default installations of
10793 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10794 ;; fall back to `org-link-frame-setup' for an old usage of
10795 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10796 (user-error "Please see Org News for version 9.0 about \
10797 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10798 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10799 (funcall save-position-maybe)))
10801 (defun org-file-apps-entry-match-against-dlink-p (entry)
10802 "This function returns non-nil if `entry' uses a regular
10803 expression which should be matched against the whole link by
10804 org-open-file.
10806 It assumes that is the case when the entry uses a regular
10807 expression which has at least one grouping construct and the
10808 action is either a lisp form or a command string containing
10809 `%1', i.e. using at least one subexpression match as a
10810 parameter."
10811 (let ((selector (car entry))
10812 (action (cdr entry)))
10813 (if (stringp selector)
10814 (and (> (regexp-opt-depth selector) 0)
10815 (or (and (stringp action)
10816 (string-match "%[0-9]" action))
10817 (consp action)))
10818 nil)))
10820 (defun org-default-apps ()
10821 "Return the default applications for this operating system."
10822 (cond
10823 ((eq system-type 'darwin)
10824 org-file-apps-defaults-macosx)
10825 ((eq system-type 'windows-nt)
10826 org-file-apps-defaults-windowsnt)
10827 (t org-file-apps-defaults-gnu)))
10829 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10830 "Convert extensions to regular expressions in the cars of LIST.
10831 Also, weed out any non-string entries, because the return value is used
10832 only for regexp matching.
10833 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10834 point to the symbol `emacs', indicating that the file should
10835 be opened in Emacs."
10836 (append
10837 (delq nil
10838 (mapcar (lambda (x)
10839 (unless (not (stringp (car x)))
10840 (if (string-match "\\W" (car x))
10842 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10843 list))
10844 (when add-auto-mode
10845 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10847 (defvar ange-ftp-name-format)
10848 (defun org-file-remote-p (file)
10849 "Test whether FILE specifies a location on a remote system.
10850 Return non-nil if the location is indeed remote.
10852 For example, the filename \"/user@host:/foo\" specifies a location
10853 on the system \"/user@host:\"."
10854 (cond ((fboundp 'file-remote-p)
10855 (file-remote-p file))
10856 ((fboundp 'tramp-handle-file-remote-p)
10857 (tramp-handle-file-remote-p file))
10858 ((and (boundp 'ange-ftp-name-format)
10859 (string-match (car ange-ftp-name-format) file))
10860 t)))
10863 ;;;; Refiling
10865 (defun org-get-org-file ()
10866 "Read a filename, with default directory `org-directory'."
10867 (let ((default (or org-default-notes-file remember-data-file)))
10868 (read-file-name (format "File name [%s]: " default)
10869 (file-name-as-directory org-directory)
10870 default)))
10872 (defun org-notes-order-reversed-p ()
10873 "Check if the current file should receive notes in reversed order."
10874 (cond
10875 ((not org-reverse-note-order) nil)
10876 ((eq t org-reverse-note-order) t)
10877 ((not (listp org-reverse-note-order)) nil)
10878 (t (catch 'exit
10879 (dolist (entry org-reverse-note-order)
10880 (when (string-match (car entry) buffer-file-name)
10881 (throw 'exit (cdr entry))))))))
10883 (defvar org-refile-target-table nil
10884 "The list of refile targets, created by `org-refile'.")
10886 (defvar org-agenda-new-buffers nil
10887 "Buffers created to visit agenda files.")
10889 (defvar org-refile-cache nil
10890 "Cache for refile targets.")
10892 (defvar org-refile-markers nil
10893 "All the markers used for caching refile locations.")
10895 (defun org-refile-marker (pos)
10896 "Get a new refile marker, but only if caching is in use."
10897 (if (not org-refile-use-cache)
10899 (let ((m (make-marker)))
10900 (move-marker m pos)
10901 (push m org-refile-markers)
10902 m)))
10904 (defun org-refile-cache-clear ()
10905 "Clear the refile cache and disable all the markers."
10906 (dolist (m org-refile-markers) (move-marker m nil))
10907 (setq org-refile-markers nil)
10908 (setq org-refile-cache nil)
10909 (message "Refile cache has been cleared"))
10911 (defun org-refile-cache-check-set (set)
10912 "Check if all the markers in the cache still have live buffers."
10913 (let (marker)
10914 (catch 'exit
10915 (while (and set (setq marker (nth 3 (pop set))))
10916 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10917 (when (and marker (null (marker-buffer marker)))
10918 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10919 (sit-for 3)
10920 (throw 'exit nil)))
10921 t)))
10923 (defun org-refile-cache-put (set &rest identifiers)
10924 "Push the refile targets SET into the cache, under IDENTIFIERS."
10925 (let* ((key (sha1 (prin1-to-string identifiers)))
10926 (entry (assoc key org-refile-cache)))
10927 (if entry
10928 (setcdr entry set)
10929 (push (cons key set) org-refile-cache))))
10931 (defun org-refile-cache-get (&rest identifiers)
10932 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10933 (cond
10934 ((not org-refile-cache) nil)
10935 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10937 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10938 org-refile-cache))))
10939 (and set (org-refile-cache-check-set set) set)))))
10941 (defvar org-outline-path-cache nil
10942 "Alist between buffer positions and outline paths.
10943 It value is an alist (POSITION . PATH) where POSITION is the
10944 buffer position at the beginning of an entry and PATH is a list
10945 of strings describing the outline path for that entry, in reverse
10946 order.")
10948 (defun org-refile-get-targets (&optional default-buffer)
10949 "Produce a table with refile targets."
10950 (let ((case-fold-search nil)
10951 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10952 (entries (or org-refile-targets '((nil . (:level . 1)))))
10953 targets tgs files desc descre)
10954 (message "Getting targets...")
10955 (with-current-buffer (or default-buffer (current-buffer))
10956 (dolist (entry entries)
10957 (setq files (car entry) desc (cdr entry))
10958 (cond
10959 ((null files) (setq files (list (current-buffer))))
10960 ((eq files 'org-agenda-files)
10961 (setq files (org-agenda-files 'unrestricted)))
10962 ((and (symbolp files) (fboundp files))
10963 (setq files (funcall files)))
10964 ((and (symbolp files) (boundp files))
10965 (setq files (symbol-value files))))
10966 (when (stringp files) (setq files (list files)))
10967 (cond
10968 ((eq (car desc) :tag)
10969 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10970 ((eq (car desc) :todo)
10971 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10972 ((eq (car desc) :regexp)
10973 (setq descre (cdr desc)))
10974 ((eq (car desc) :level)
10975 (setq descre (concat "^\\*\\{" (number-to-string
10976 (if org-odd-levels-only
10977 (1- (* 2 (cdr desc)))
10978 (cdr desc)))
10979 "\\}[ \t]")))
10980 ((eq (car desc) :maxlevel)
10981 (setq descre (concat "^\\*\\{1," (number-to-string
10982 (if org-odd-levels-only
10983 (1- (* 2 (cdr desc)))
10984 (cdr desc)))
10985 "\\}[ \t]")))
10986 (t (error "Bad refiling target description %s" desc)))
10987 (dolist (f files)
10988 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10990 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10991 (progn
10992 (when (bufferp f)
10993 (setq f (buffer-file-name (buffer-base-buffer f))))
10994 (setq f (and f (expand-file-name f)))
10995 (when (eq org-refile-use-outline-path 'file)
10996 (push (list (file-name-nondirectory f) f nil nil) tgs))
10997 (when (eq org-refile-use-outline-path 'buffer-name)
10998 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10999 (when (eq org-refile-use-outline-path 'full-file-path)
11000 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11001 (org-with-wide-buffer
11002 (goto-char (point-min))
11003 (setq org-outline-path-cache nil)
11004 (while (re-search-forward descre nil t)
11005 (beginning-of-line)
11006 (let ((case-fold-search nil))
11007 (looking-at org-complex-heading-regexp))
11008 (let ((begin (point))
11009 (heading (match-string-no-properties 4)))
11010 (unless (or (and
11011 org-refile-target-verify-function
11012 (not
11013 (funcall org-refile-target-verify-function)))
11014 (not heading))
11015 (let ((re (format org-complex-heading-regexp-format
11016 (regexp-quote heading)))
11017 (target
11018 (if (not org-refile-use-outline-path) heading
11019 (mapconcat
11020 #'identity
11021 (append
11022 (pcase org-refile-use-outline-path
11023 (`file (list (file-name-nondirectory
11024 (buffer-file-name
11025 (buffer-base-buffer)))))
11026 (`full-file-path
11027 (list (buffer-file-name
11028 (buffer-base-buffer))))
11029 (`buffer-name
11030 (list (buffer-name
11031 (buffer-base-buffer))))
11032 (_ nil))
11033 (mapcar (lambda (s) (replace-regexp-in-string
11034 "/" "\\/" s nil t))
11035 (org-get-outline-path t t)))
11036 "/"))))
11037 (push (list target f re (org-refile-marker (point)))
11038 tgs)))
11039 (when (= (point) begin)
11040 ;; Verification function has not moved point.
11041 (end-of-line)))))))
11042 (when org-refile-use-cache
11043 (org-refile-cache-put tgs (buffer-file-name) descre))
11044 (setq targets (append tgs targets))))))
11045 (message "Getting targets...done")
11046 (delete-dups (nreverse targets))))
11048 (defun org--get-outline-path-1 (&optional use-cache)
11049 "Return outline path to current headline.
11051 Outline path is a list of strings, in reverse order. When
11052 optional argument USE-CACHE is non-nil, make use of a cache. See
11053 `org-get-outline-path' for details.
11055 Assume buffer is widened and point is on a headline."
11056 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11057 (let ((p (point))
11058 (heading (let ((case-fold-search nil))
11059 (looking-at org-complex-heading-regexp)
11060 (if (not (match-end 4)) ""
11061 ;; Remove statistics cookies.
11062 (org-trim
11063 (org-link-display-format
11064 (replace-regexp-in-string
11065 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11066 (match-string-no-properties 4))))))))
11067 (if (org-up-heading-safe)
11068 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11069 (when use-cache
11070 (push (cons p path) org-outline-path-cache))
11071 path)
11072 ;; This is a new root node. Since we assume we are moving
11073 ;; forward, we can drop previous cache so as to limit number
11074 ;; of associations there.
11075 (let ((path (list heading)))
11076 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11077 path)))))
11079 (defun org-get-outline-path (&optional with-self use-cache)
11080 "Return the outline path to the current entry.
11082 An outline path is a list of ancestors for current headline, as
11083 a list of strings. Statistics cookies are removed and links are
11084 replaced with their description, if any, or their path otherwise.
11086 When optional argument WITH-SELF is non-nil, the path also
11087 includes the current headline.
11089 When optional argument USE-CACHE is non-nil, cache outline paths
11090 between calls to this function so as to avoid backtracking. This
11091 argument is useful when planning to find more than one outline
11092 path in the same document. In that case, there are two
11093 conditions to satisfy:
11094 - `org-outline-path-cache' is set to nil before starting the
11095 process;
11096 - outline paths are computed by increasing buffer positions."
11097 (org-with-wide-buffer
11098 (and (or (and with-self (org-back-to-heading t))
11099 (org-up-heading-safe))
11100 (reverse (org--get-outline-path-1 use-cache)))))
11102 (defun org-format-outline-path (path &optional width prefix separator)
11103 "Format the outline path PATH for display.
11104 WIDTH is the maximum number of characters that is available.
11105 PREFIX is a prefix to be included in the returned string,
11106 such as the file name.
11107 SEPARATOR is inserted between the different parts of the path,
11108 the default is \"/\"."
11109 (setq width (or width 79))
11110 (setq path (delq nil path))
11111 (unless (> width 0)
11112 (user-error "Argument `width' must be positive"))
11113 (setq separator (or separator "/"))
11114 (let* ((org-odd-levels-only nil)
11115 (fpath (concat
11116 prefix (and prefix path separator)
11117 (mapconcat
11118 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11119 (cl-loop for head in path
11120 for n from 0
11121 collect (org-add-props
11122 head nil 'face
11123 (nth (% n org-n-level-faces) org-level-faces)))
11124 separator))))
11125 (when (> (length fpath) width)
11126 (if (< width 7)
11127 ;; It's unlikely that `width' will be this small, but don't
11128 ;; waste characters by adding ".." if it is.
11129 (setq fpath (substring fpath 0 width))
11130 (setf (substring fpath (- width 2)) "..")))
11131 fpath))
11133 (defun org-display-outline-path (&optional file current separator just-return-string)
11134 "Display the current outline path in the echo area.
11136 If FILE is non-nil, prepend the output with the file name.
11137 If CURRENT is non-nil, append the current heading to the output.
11138 SEPARATOR is passed through to `org-format-outline-path'. It separates
11139 the different parts of the path and defaults to \"/\".
11140 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11141 (interactive "P")
11142 (let* (case-fold-search
11143 (bfn (buffer-file-name (buffer-base-buffer)))
11144 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11145 res)
11146 (when current (setq path (append path
11147 (save-excursion
11148 (org-back-to-heading t)
11149 (when (looking-at org-complex-heading-regexp)
11150 (list (match-string 4)))))))
11151 (setq res
11152 (org-format-outline-path
11153 path
11154 (1- (frame-width))
11155 (and file bfn (concat (file-name-nondirectory bfn) separator))
11156 separator))
11157 (if just-return-string
11158 (org-no-properties res)
11159 (org-unlogged-message "%s" res))))
11161 (defvar org-refile-history nil
11162 "History for refiling operations.")
11164 (defvar org-after-refile-insert-hook nil
11165 "Hook run after `org-refile' has inserted its stuff at the new location.
11166 Note that this is still *before* the stuff will be removed from
11167 the *old* location.")
11169 (defvar org-capture-last-stored-marker)
11170 (defvar org-refile-keep nil
11171 "Non-nil means `org-refile' will copy instead of refile.")
11173 (defun org-copy ()
11174 "Like `org-refile', but copy."
11175 (interactive)
11176 (let ((org-refile-keep t))
11177 (funcall 'org-refile nil nil nil "Copy")))
11179 (defun org-refile (&optional arg default-buffer rfloc msg)
11180 "Move the entry or entries at point to another heading.
11182 The list of target headings is compiled using the information in
11183 `org-refile-targets', which see.
11185 At the target location, the entry is filed as a subitem of the
11186 target heading. Depending on `org-reverse-note-order', the new
11187 subitem will either be the first or the last subitem.
11189 If there is an active region, all entries in that region will be
11190 refiled. However, the region must fulfill the requirement that
11191 the first heading sets the top-level of the moved text.
11193 With a `\\[universal-argument]' ARG, the command will only visit the target \
11194 location
11195 and not actually move anything.
11197 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11198 location where the last
11199 refiling operation has put the subtree.
11201 With a numeric prefix argument of `2', refile to the running clock.
11203 With a numeric prefix argument of `3', emulate `org-refile-keep'
11204 being set to t and copy to the target location, don't move it.
11205 Beware that keeping refiled entries may result in duplicated ID
11206 properties.
11208 RFLOC can be a refile location obtained in a different way.
11210 MSG is a string to replace \"Refile\" in the default prompt with
11211 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11213 See also `org-refile-use-outline-path'.
11215 If you are using target caching (see `org-refile-use-cache'), you
11216 have to clear the target cache in order to find new targets.
11217 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11218 prefix argument (`C-u C-u C-u C-c C-w')."
11219 (interactive "P")
11220 (if (member arg '(0 (64)))
11221 (org-refile-cache-clear)
11222 (let* ((actionmsg (cond (msg msg)
11223 ((equal arg 3) "Refile (and keep)")
11224 (t "Refile")))
11225 (regionp (org-region-active-p))
11226 (region-start (and regionp (region-beginning)))
11227 (region-end (and regionp (region-end)))
11228 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11229 pos it nbuf file level reversed)
11230 (setq last-command nil)
11231 (when regionp
11232 (goto-char region-start)
11233 (or (bolp) (goto-char (point-at-bol)))
11234 (setq region-start (point))
11235 (unless (or (org-kill-is-subtree-p
11236 (buffer-substring region-start region-end))
11237 (prog1 org-refile-active-region-within-subtree
11238 (let ((s (point-at-eol)))
11239 (org-toggle-heading)
11240 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11241 (user-error "The region is not a (sequence of) subtree(s)")))
11242 (if (equal arg '(16))
11243 (org-refile-goto-last-stored)
11244 (when (or
11245 (and (equal arg 2)
11246 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11247 (prog1
11248 (setq it (list (or org-clock-heading "running clock")
11249 (buffer-file-name
11250 (marker-buffer org-clock-hd-marker))
11252 (marker-position org-clock-hd-marker)))
11253 (setq arg nil)))
11254 (setq it
11255 (or rfloc
11256 (let (heading-text)
11257 (save-excursion
11258 (unless (and arg (listp arg))
11259 (org-back-to-heading t)
11260 (setq heading-text
11261 (replace-regexp-in-string
11262 org-bracket-link-regexp
11263 "\\3"
11264 (or (nth 4 (org-heading-components))
11265 ""))))
11266 (org-refile-get-location
11267 (cond ((and arg (listp arg)) "Goto")
11268 (regionp (concat actionmsg " region to"))
11269 (t (concat actionmsg " subtree \""
11270 heading-text "\" to")))
11271 default-buffer
11272 (and (not (equal '(4) arg))
11273 org-refile-allow-creating-parent-nodes)))))))
11274 (setq file (nth 1 it)
11275 pos (nth 3 it))
11276 (when (and (not arg)
11278 (equal (buffer-file-name) file)
11279 (if regionp
11280 (and (>= pos region-start)
11281 (<= pos region-end))
11282 (and (>= pos (point))
11283 (< pos (save-excursion
11284 (org-end-of-subtree t t))))))
11285 (error "Cannot refile to position inside the tree or region"))
11286 (setq nbuf (or (find-buffer-visiting file)
11287 (find-file-noselect file)))
11288 (if (and arg (not (equal arg 3)))
11289 (progn
11290 (pop-to-buffer-same-window nbuf)
11291 (goto-char (cond (pos)
11292 ((org-notes-order-reversed-p) (point-min))
11293 (t (point-max))))
11294 (org-show-context 'org-goto))
11295 (if regionp
11296 (progn
11297 (org-kill-new (buffer-substring region-start region-end))
11298 (org-save-markers-in-region region-start region-end))
11299 (org-copy-subtree 1 nil t))
11300 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11301 (find-file-noselect file)))
11302 (setq reversed (org-notes-order-reversed-p))
11303 (org-with-wide-buffer
11304 (if pos
11305 (progn
11306 (goto-char pos)
11307 (setq level (org-get-valid-level (funcall outline-level) 1))
11308 (goto-char
11309 (if reversed
11310 (or (outline-next-heading) (point-max))
11311 (or (save-excursion (org-get-next-sibling))
11312 (org-end-of-subtree t t)
11313 (point-max)))))
11314 (setq level 1)
11315 (if (not reversed)
11316 (goto-char (point-max))
11317 (goto-char (point-min))
11318 (or (outline-next-heading) (goto-char (point-max)))))
11319 (unless (bolp) (newline))
11320 (org-paste-subtree level nil nil t)
11321 (when org-log-refile
11322 (org-add-log-setup 'refile nil nil org-log-refile)
11323 (unless (eq org-log-refile 'note)
11324 (save-excursion (org-add-log-note))))
11325 (and org-auto-align-tags
11326 (let ((org-loop-over-headlines-in-active-region nil))
11327 (org-align-tags)))
11328 (let ((bookmark-name (plist-get org-bookmark-names-plist
11329 :last-refile)))
11330 (when bookmark-name
11331 (with-demoted-errors
11332 (bookmark-set bookmark-name))))
11333 ;; If we are refiling for capture, make sure that the
11334 ;; last-capture pointers point here
11335 (when (bound-and-true-p org-capture-is-refiling)
11336 (let ((bookmark-name (plist-get org-bookmark-names-plist
11337 :last-capture-marker)))
11338 (when bookmark-name
11339 (with-demoted-errors
11340 (bookmark-set bookmark-name))))
11341 (move-marker org-capture-last-stored-marker (point)))
11342 (when (fboundp 'deactivate-mark) (deactivate-mark))
11343 (run-hooks 'org-after-refile-insert-hook)))
11344 (unless org-refile-keep
11345 (if regionp
11346 (delete-region (point) (+ (point) (- region-end region-start)))
11347 (org-preserve-local-variables
11348 (delete-region
11349 (and (org-back-to-heading t) (point))
11350 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11351 (when (featurep 'org-inlinetask)
11352 (org-inlinetask-remove-END-maybe))
11353 (setq org-markers-to-move nil)
11354 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11356 (defun org-refile-goto-last-stored ()
11357 "Go to the location where the last refile was stored."
11358 (interactive)
11359 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11360 (message "This is the location of the last refile"))
11362 (defun org-refile--get-location (refloc tbl)
11363 "When user refile to REFLOC, find the associated target in TBL.
11364 Also check `org-refile-target-table'."
11365 (car (delq
11367 (mapcar
11368 (lambda (r) (or (assoc r tbl)
11369 (assoc r org-refile-target-table)))
11370 (list (replace-regexp-in-string "/$" "" refloc)
11371 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11373 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11374 "Prompt the user for a refile location, using PROMPT.
11375 PROMPT should not be suffixed with a colon and a space, because
11376 this function appends the default value from
11377 `org-refile-history' automatically, if that is not empty."
11378 (let ((org-refile-targets org-refile-targets)
11379 (org-refile-use-outline-path org-refile-use-outline-path))
11380 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11381 (unless org-refile-target-table
11382 (user-error "No refile targets"))
11383 (let* ((cbuf (current-buffer))
11384 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11385 (cfunc (if (and org-refile-use-outline-path
11386 org-outline-path-complete-in-steps)
11387 #'org-olpath-completing-read
11388 #'completing-read))
11389 (extra (if org-refile-use-outline-path "/" ""))
11390 (cbnex (concat (buffer-name) extra))
11391 (filename (and cfn (expand-file-name cfn)))
11392 (tbl (mapcar
11393 (lambda (x)
11394 (if (and (not (member org-refile-use-outline-path
11395 '(file full-file-path)))
11396 (not (equal filename (nth 1 x))))
11397 (cons (concat (car x) extra " ("
11398 (file-name-nondirectory (nth 1 x)) ")")
11399 (cdr x))
11400 (cons (concat (car x) extra) (cdr x))))
11401 org-refile-target-table))
11402 (completion-ignore-case t)
11403 cdef
11404 (prompt (concat prompt
11405 (or (and (car org-refile-history)
11406 (concat " (default " (car org-refile-history) ")"))
11407 (and (assoc cbnex tbl) (setq cdef cbnex)
11408 (concat " (default " cbnex ")"))) ": "))
11409 pa answ parent-target child parent old-hist)
11410 (setq old-hist org-refile-history)
11411 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11412 nil 'org-refile-history (or cdef (car org-refile-history))))
11413 (if (setq pa (org-refile--get-location answ tbl))
11414 (progn
11415 (org-refile-check-position pa)
11416 (when (or (not org-refile-history)
11417 (not (eq old-hist org-refile-history))
11418 (not (equal (car pa) (car org-refile-history))))
11419 (setq org-refile-history
11420 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11421 org-refile-history
11422 (cdr org-refile-history))))
11423 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11424 (pop org-refile-history)))
11426 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11427 (progn
11428 (setq parent (match-string 1 answ)
11429 child (match-string 2 answ))
11430 (setq parent-target (org-refile--get-location parent tbl))
11431 (when (and parent-target
11432 (or (eq new-nodes t)
11433 (and (eq new-nodes 'confirm)
11434 (y-or-n-p (format "Create new node \"%s\"? "
11435 child)))))
11436 (org-refile-new-child parent-target child)))
11437 (user-error "Invalid target location")))))
11439 (declare-function org-string-nw-p "org-macs" (s))
11440 (defun org-refile-check-position (refile-pointer)
11441 "Check if the refile pointer matches the headline to which it points."
11442 (let* ((file (nth 1 refile-pointer))
11443 (re (nth 2 refile-pointer))
11444 (pos (nth 3 refile-pointer))
11445 buffer)
11446 (if (and (not (markerp pos)) (not file))
11447 (user-error "Please indicate a target file in the refile path")
11448 (when (org-string-nw-p re)
11449 (setq buffer (if (markerp pos)
11450 (marker-buffer pos)
11451 (or (find-buffer-visiting file)
11452 (find-file-noselect file))))
11453 (with-current-buffer buffer
11454 (org-with-wide-buffer
11455 (goto-char pos)
11456 (beginning-of-line 1)
11457 (unless (looking-at-p re)
11458 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11460 (defun org-refile-new-child (parent-target child)
11461 "Use refile target PARENT-TARGET to add new CHILD below it."
11462 (unless parent-target
11463 (error "Cannot find parent for new node"))
11464 (let ((file (nth 1 parent-target))
11465 (pos (nth 3 parent-target))
11466 level)
11467 (with-current-buffer (or (find-buffer-visiting file)
11468 (find-file-noselect file))
11469 (org-with-wide-buffer
11470 (if pos
11471 (goto-char pos)
11472 (goto-char (point-max))
11473 (unless (bolp) (newline)))
11474 (when (looking-at org-outline-regexp)
11475 (setq level (funcall outline-level))
11476 (org-end-of-subtree t t))
11477 (org-back-over-empty-lines)
11478 (insert "\n" (make-string
11479 (if pos (org-get-valid-level level 1) 1) ?*)
11480 " " child "\n")
11481 (beginning-of-line 0)
11482 (list (concat (car parent-target) "/" child) file "" (point))))))
11484 (defun org-olpath-completing-read (prompt collection &rest args)
11485 "Read an outline path like a file name."
11486 (let ((thetable collection))
11487 (apply #'completing-read
11488 prompt
11489 (lambda (string predicate &optional flag)
11490 (cond
11491 ((eq flag nil) (try-completion string thetable))
11492 ((eq flag t)
11493 (let ((l (length string)))
11494 (mapcar (lambda (x)
11495 (let ((r (substring x l))
11496 (f (if (string-match " ([^)]*)$" x)
11497 (match-string 0 x)
11498 "")))
11499 (if (string-match "/" r)
11500 (concat string (substring r 0 (match-end 0)) f)
11501 x)))
11502 (all-completions string thetable predicate))))
11503 ;; Exact match?
11504 ((eq flag 'lambda) (assoc string thetable))))
11505 args)))
11507 ;;;; Dynamic blocks
11509 (defun org-find-dblock (name)
11510 "Find the first dynamic block with name NAME in the buffer.
11511 If not found, stay at current position and return nil."
11512 (let ((case-fold-search t) pos)
11513 (save-excursion
11514 (goto-char (point-min))
11515 (setq pos (and (re-search-forward
11516 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11517 (match-beginning 0))))
11518 (when pos (goto-char pos))
11519 pos))
11521 (defun org-create-dblock (plist)
11522 "Create a dynamic block section, with parameters taken from PLIST.
11523 PLIST must contain a :name entry which is used as the name of the block."
11524 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11525 (end-of-line 1)
11526 (newline))
11527 (let ((col (current-column))
11528 (name (plist-get plist :name)))
11529 (insert "#+BEGIN: " name)
11530 (while plist
11531 (if (eq (car plist) :name)
11532 (setq plist (cddr plist))
11533 (insert " " (prin1-to-string (pop plist)))))
11534 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11535 (beginning-of-line -2)))
11537 (defun org-prepare-dblock ()
11538 "Prepare dynamic block for refresh.
11539 This empties the block, puts the cursor at the insert position and returns
11540 the property list including an extra property :name with the block name."
11541 (unless (looking-at org-dblock-start-re)
11542 (user-error "Not at a dynamic block"))
11543 (let* ((begdel (1+ (match-end 0)))
11544 (name (org-no-properties (match-string 1)))
11545 (params (append (list :name name)
11546 (read (concat "(" (match-string 3) ")")))))
11547 (save-excursion
11548 (beginning-of-line 1)
11549 (skip-chars-forward " \t")
11550 (setq params (plist-put params :indentation-column (current-column))))
11551 (unless (re-search-forward org-dblock-end-re nil t)
11552 (error "Dynamic block not terminated"))
11553 (setq params
11554 (append params
11555 (list :content (buffer-substring
11556 begdel (match-beginning 0)))))
11557 (delete-region begdel (match-beginning 0))
11558 (goto-char begdel)
11559 (open-line 1)
11560 params))
11562 (defun org-map-dblocks (&optional command)
11563 "Apply COMMAND to all dynamic blocks in the current buffer.
11564 If COMMAND is not given, use `org-update-dblock'."
11565 (let ((cmd (or command 'org-update-dblock)))
11566 (save-excursion
11567 (goto-char (point-min))
11568 (while (re-search-forward org-dblock-start-re nil t)
11569 (goto-char (match-beginning 0))
11570 (save-excursion
11571 (condition-case nil
11572 (funcall cmd)
11573 (error (message "Error during update of dynamic block"))))
11574 (unless (re-search-forward org-dblock-end-re nil t)
11575 (error "Dynamic block not terminated"))))))
11577 (defun org-dblock-update (&optional arg)
11578 "User command for updating dynamic blocks.
11579 Update the dynamic block at point. With prefix ARG, update all dynamic
11580 blocks in the buffer."
11581 (interactive "P")
11582 (if arg
11583 (org-update-all-dblocks)
11584 (or (looking-at org-dblock-start-re)
11585 (org-beginning-of-dblock))
11586 (org-update-dblock)))
11588 (defun org-update-dblock ()
11589 "Update the dynamic block at point.
11590 This means to empty the block, parse for parameters and then call
11591 the correct writing function."
11592 (interactive)
11593 (save-excursion
11594 (let* ((win (selected-window))
11595 (pos (point))
11596 (line (org-current-line))
11597 (params (org-prepare-dblock))
11598 (name (plist-get params :name))
11599 (indent (plist-get params :indentation-column))
11600 (cmd (intern (concat "org-dblock-write:" name))))
11601 (message "Updating dynamic block `%s' at line %d..." name line)
11602 (funcall cmd params)
11603 (message "Updating dynamic block `%s' at line %d...done" name line)
11604 (goto-char pos)
11605 (when (and indent (> indent 0))
11606 (setq indent (make-string indent ?\ ))
11607 (save-excursion
11608 (select-window win)
11609 (org-beginning-of-dblock)
11610 (forward-line 1)
11611 (while (not (looking-at org-dblock-end-re))
11612 (insert indent)
11613 (beginning-of-line 2))
11614 (when (looking-at org-dblock-end-re)
11615 (and (looking-at "[ \t]+")
11616 (replace-match ""))
11617 (insert indent)))))))
11619 (defun org-beginning-of-dblock ()
11620 "Find the beginning of the dynamic block at point.
11621 Error if there is no such block at point."
11622 (let ((pos (point))
11623 beg)
11624 (end-of-line 1)
11625 (if (and (re-search-backward org-dblock-start-re nil t)
11626 (setq beg (match-beginning 0))
11627 (re-search-forward org-dblock-end-re nil t)
11628 (> (match-end 0) pos))
11629 (goto-char beg)
11630 (goto-char pos)
11631 (error "Not in a dynamic block"))))
11633 (defun org-update-all-dblocks ()
11634 "Update all dynamic blocks in the buffer.
11635 This function can be used in a hook."
11636 (interactive)
11637 (when (derived-mode-p 'org-mode)
11638 (org-map-dblocks 'org-update-dblock)))
11641 ;;;; Completion
11643 (declare-function org-export-backend-options "ox" (cl-x) t)
11644 (defun org-get-export-keywords ()
11645 "Return a list of all currently understood export keywords.
11646 Export keywords include options, block names, attributes and
11647 keywords relative to each registered export back-end."
11648 (let (keywords)
11649 (dolist (backend
11650 (bound-and-true-p org-export-registered-backends)
11651 (delq nil keywords))
11652 ;; Back-end name (for keywords, like #+LATEX:)
11653 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11654 (dolist (option-entry (org-export-backend-options backend))
11655 ;; Back-end options.
11656 (push (nth 1 option-entry) keywords)))))
11658 (defconst org-options-keywords
11659 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11660 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11661 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11662 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11663 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11665 (defcustom org-structure-template-alist
11666 '(("a" . "export ascii")
11667 ("c" . "center")
11668 ("C" . "comment")
11669 ("e" . "example")
11670 ("E" . "export")
11671 ("h" . "export html")
11672 ("l" . "export latex")
11673 ("q" . "quote")
11674 ("s" . "src")
11675 ("v" . "verse"))
11676 "Structure completion elements.
11677 This is an alist of keys and block types. With
11678 `org-insert-structure-template' a block can be inserted through a
11679 menu. The block type is inserted, with \"#+BEGIN_\" and
11680 \"#+END_\" added automatically. The menukeys are determined
11681 based on the key elements in the `org-structure-template-alist'.
11682 If two entries have the keys \"a\" and \"aa\" respectively, the
11683 former will be inserted by typing \"a TAB/RET/SPC\" and the
11684 latter will be inserted by typing \"aa\". If an entry with the
11685 key \"aab\" is later added it would be inserted by typing \"ab\".
11687 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11688 block can be inserted by pressing TAB after the string \"<KEY\".
11690 :group 'org-edit-structure
11691 :type '(repeat
11692 (cons (string :tag "Key")
11693 (string :tag "Template")))
11694 :package-version '(Org . "9.2"))
11696 (defun org--insert-structure-template-mks ()
11697 "Present `org-structure-template-alist' with `org-mks'.
11699 Menus are added if keys require more than one keystroke.
11700 Tabs are added to single key entires when needing more than one stroke.
11701 Keys longer than two characters are reduced to two characters."
11702 (let* (case-fold-search
11703 (templates (append org-structure-template-alist
11704 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11705 (keys (mapcar #'car templates))
11706 (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11707 ;; Sort each element of `org-structure-template-alist' into
11708 ;; sublists according to the first letter.
11709 (superlist (mapcar (lambda (letter)
11710 (list letter
11711 (cl-remove-if-not
11712 (apply-partially #'string-match-p (concat "^" letter))
11713 templates :key #'car)))
11714 start-letters)))
11715 (org-mks
11716 (apply #'append
11717 ;; Make an `org-mks' table. If only one element is
11718 ;; present in a sublist, make it part of the top-menu,
11719 ;; otherwise make a submenu according to the starting
11720 ;; letter and populate it.
11721 (mapcar (lambda (sublist)
11722 (if (eq 1 (length (cadr sublist)))
11723 (mapcar (lambda (elm)
11724 (list (substring (car elm) 0 1)
11725 (cdr elm) ""))
11726 (cadr sublist))
11727 ;; Create submenu.
11728 (let* ((topkey (car sublist))
11729 (elms (cadr sublist))
11730 (keys (mapcar #'car elms))
11731 (long (> (length elms) 3)))
11732 (append
11733 (list
11734 ;; Make a description of the submenu.
11735 (list topkey
11736 (concat
11737 (mapconcat #'cdr
11738 (cl-subseq elms 0 (if long 3 (length elms)))
11739 ", ")
11740 (when long ", ..."))))
11741 ;; List of entries in submenu.
11742 (cl-mapcar #'list
11743 (org--insert-structure-template-unique-keys keys)
11744 (mapcar #'cdr elms)
11745 (make-list (length elms) ""))))))
11746 superlist))
11747 "Select a key\n============"
11748 "Key: ")))
11750 (defun org--insert-structure-template-unique-keys (keys)
11751 "Make list of unique, two character long elements from KEYS.
11753 Elements of length one have a tab appended. Elements of length
11754 two are kept as is. Longer elements are truncated to length two.
11756 If an element cannot be made unique an error is raised."
11757 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11758 menu-keys)
11759 (dolist (key orderd-keys)
11760 (let ((potential-key
11761 (cl-case (length key)
11762 (1 (concat key "\t"))
11763 (2 key)
11764 (otherwise
11765 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11766 (mapcar (apply-partially #'concat (substring key 0 1))
11767 (split-string (substring key 1) "" t)))))))
11768 (if (or (not potential-key) (assoc potential-key menu-keys))
11769 (user-error "Could not make unique key for %s." key)
11770 (push (cons potential-key key) menu-keys))))
11771 (mapcar #'car
11772 (cl-sort menu-keys #'<
11773 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11775 (defun org-insert-structure-template (type)
11776 "Insert a block structure of the type #+begin_foo/#+end_foo.
11777 First choose a block based on `org-structure-template-alist'.
11778 Alternatively, type RET, TAB or SPC to write the block type.
11779 With an active region, wrap the region in the block. Otherwise,
11780 insert an empty block."
11781 (interactive
11782 (list (pcase (org--insert-structure-template-mks)
11783 (`("\t" . ,_) (read-string "Structure type: "))
11784 (`(,_ ,choice . ,_) choice))))
11785 (let* ((region? (use-region-p))
11786 (col (current-indentation))
11787 (indent (make-string col ?\s))
11788 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11789 (region-string (and region?
11790 (buffer-substring (region-beginning)
11791 (region-end))))
11792 (region-end-blank (and region?
11793 (save-excursion
11794 (goto-char (region-end))
11795 (when (looking-at "[ \t]*$")
11796 (replace-match "")
11797 t))))
11799 (when region? (delete-region (region-beginning) (region-end)))
11800 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11801 (insert "\n"))
11802 (beginning-of-line)
11803 (save-excursion
11804 (insert
11805 (with-temp-buffer
11806 (when region?
11807 (insert region-string "\n")
11808 (when (string-match-p
11809 (concat "\\`" (regexp-opt '("example" "export" "src")))
11810 type)
11811 (org-escape-code-in-region (point-min) (point-max))))
11812 (goto-char (point-min))
11813 ;; Delete trailing white-lines.
11814 (when region?
11815 (while (looking-at-p "^[ \t]*$")
11816 (delete-region (line-beginning-position)
11817 (line-beginning-position 2))))
11818 (save-excursion
11819 (while (not (eobp))
11820 (unless (looking-at-p indent)
11821 (insert indent))
11822 (forward-line)))
11823 (insert
11824 indent
11825 (format "#+begin_%s%s\n" type (if special? " " "")))
11826 (unless region? (indent-to col))
11827 (setq s (point))
11828 (goto-char (point-max))
11829 (skip-chars-backward "[ \t\n]" s)
11830 (delete-region (line-end-position) (point-max))
11831 (insert "\n" indent
11832 (format "#+end_%s" (car (split-string type)))
11833 (if region-end-blank "" "\n"))
11834 (buffer-substring (point-min) (point))))
11835 (when (and (eobp) (not (bolp))) (insert "\n")))
11836 (cond (special?
11837 (end-of-line))
11839 (forward-line)
11840 (skip-chars-forward "[ \t]*")))))
11843 ;;;; TODO, DEADLINE, Comments
11845 (defun org-toggle-comment ()
11846 "Change the COMMENT state of an entry."
11847 (interactive)
11848 (save-excursion
11849 (org-back-to-heading)
11850 (let ((case-fold-search nil))
11851 (looking-at org-complex-heading-regexp))
11852 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11853 (skip-chars-forward " \t")
11854 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11855 (if (org-in-commented-heading-p t)
11856 (delete-region (point)
11857 (progn (search-forward " " (line-end-position) 'move)
11858 (skip-chars-forward " \t")
11859 (point)))
11860 (insert org-comment-string)
11861 (unless (eolp) (insert " ")))))
11863 (defvar org-last-todo-state-is-todo nil
11864 "This is non-nil when the last TODO state change led to a TODO state.
11865 If the last change removed the TODO tag or switched to DONE, then
11866 this is nil.")
11868 (defvar org-todo-setup-filter-hook nil
11869 "Hook for functions that pre-filter todo specs.
11870 Each function takes a todo spec and returns either nil or the spec
11871 transformed into canonical form." )
11873 (defvar org-todo-get-default-hook nil
11874 "Hook for functions that get a default item for todo.
11875 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11876 nil or a string to be used for the todo mark." )
11878 (defvar org-agenda-headline-snapshot-before-repeat)
11880 (defun org-current-effective-time ()
11881 "Return current time adjusted for `org-extend-today-until' variable."
11882 (let* ((ct (org-current-time))
11883 (dct (decode-time ct))
11884 (ct1
11885 (cond
11886 (org-use-last-clock-out-time-as-effective-time
11887 (or (org-clock-get-last-clock-out-time) ct))
11888 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11889 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11890 (t ct))))
11891 ct1))
11893 (defun org-todo-yesterday (&optional arg)
11894 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11895 (interactive "P")
11896 (if (eq major-mode 'org-agenda-mode)
11897 (apply 'org-agenda-todo-yesterday arg)
11898 (let* ((org-use-effective-time t)
11899 (hour (nth 2 (decode-time (org-current-time))))
11900 (org-extend-today-until (1+ hour)))
11901 (org-todo arg))))
11903 (defvar org-block-entry-blocking ""
11904 "First entry preventing the TODO state change.")
11906 (defun org-cancel-repeater ()
11907 "Cancel a repeater by setting its numeric value to zero."
11908 (interactive)
11909 (save-excursion
11910 (org-back-to-heading t)
11911 (let ((bound1 (point))
11912 (bound0 (save-excursion (outline-next-heading) (point))))
11913 (when (and (re-search-forward
11914 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11915 org-deadline-time-regexp "\\)\\|\\("
11916 org-ts-regexp "\\)")
11917 bound0 t)
11918 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11919 bound1 t))
11920 (replace-match "0" t nil nil 1)))))
11922 (defvar org-state)
11923 (defvar org-blocked-by-checkboxes)
11924 (defun org-todo (&optional arg)
11925 "Change the TODO state of an item.
11927 The state of an item is given by a keyword at the start of the heading,
11928 like
11929 *** TODO Write paper
11930 *** DONE Call mom
11932 The different keywords are specified in the variable `org-todo-keywords'.
11933 By default the available states are \"TODO\" and \"DONE\". So, for this
11934 example: when the item starts with TODO, it is changed to DONE.
11935 When it starts with DONE, the DONE is removed. And when neither TODO nor
11936 DONE are present, add TODO at the beginning of the heading.
11938 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11939 state.
11940 With numeric prefix ARG, switch to that state.
11941 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11942 next set of TODO \
11943 keywords (nextset).
11944 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11945 prefix, circumvent any state blocking.
11946 With a numeric prefix arg of 0, inhibit note taking for the change.
11947 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11949 When called through ELisp, arg is also interpreted in the following way:
11950 `none' -> empty state
11951 \"\" -> switch to empty state
11952 `done' -> switch to DONE
11953 `nextset' -> switch to the next set of keywords
11954 `previousset' -> switch to the previous set of keywords
11955 \"WAITING\" -> switch to the specified keyword, but only if it
11956 really is a member of `org-todo-keywords'."
11957 (interactive "P")
11958 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11959 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11960 'region-start-level 'region))
11961 org-loop-over-headlines-in-active-region)
11962 (org-map-entries
11963 `(org-todo ,arg)
11964 org-loop-over-headlines-in-active-region
11965 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11966 (when (equal arg '(16)) (setq arg 'nextset))
11967 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11968 (let ((org-blocker-hook org-blocker-hook)
11969 commentp
11970 case-fold-search)
11971 (when (equal arg '(64))
11972 (setq arg nil org-blocker-hook nil))
11973 (when (and org-blocker-hook
11974 (or org-inhibit-blocking
11975 (org-entry-get nil "NOBLOCKING")))
11976 (setq org-blocker-hook nil))
11977 (save-excursion
11978 (catch 'exit
11979 (org-back-to-heading t)
11980 (when (org-in-commented-heading-p t)
11981 (org-toggle-comment)
11982 (setq commentp t))
11983 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11984 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11985 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11986 (let* ((match-data (match-data))
11987 (startpos (copy-marker (line-beginning-position)))
11988 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11989 (org-log-done org-log-done)
11990 (org-log-repeat org-log-repeat)
11991 (org-todo-log-states org-todo-log-states)
11992 (org-inhibit-logging
11993 (if (equal arg 0)
11994 (progn (setq arg nil) 'note) org-inhibit-logging))
11995 (this (match-string 1))
11996 (hl-pos (match-beginning 0))
11997 (head (org-get-todo-sequence-head this))
11998 (ass (assoc head org-todo-kwd-alist))
11999 (interpret (nth 1 ass))
12000 (done-word (nth 3 ass))
12001 (final-done-word (nth 4 ass))
12002 (org-last-state (or this ""))
12003 (completion-ignore-case t)
12004 (member (member this org-todo-keywords-1))
12005 (tail (cdr member))
12006 (org-state (cond
12007 ((and org-todo-key-trigger
12008 (or (and (equal arg '(4))
12009 (eq org-use-fast-todo-selection 'prefix))
12010 (and (not arg) org-use-fast-todo-selection
12011 (not (eq org-use-fast-todo-selection
12012 'prefix)))))
12013 ;; Use fast selection.
12014 (org-fast-todo-selection))
12015 ((and (equal arg '(4))
12016 (or (not org-use-fast-todo-selection)
12017 (not org-todo-key-trigger)))
12018 ;; Read a state with completion.
12019 (completing-read
12020 "State: " (mapcar #'list org-todo-keywords-1)
12021 nil t))
12022 ((eq arg 'right)
12023 (if this
12024 (if tail (car tail) nil)
12025 (car org-todo-keywords-1)))
12026 ((eq arg 'left)
12027 (unless (equal member org-todo-keywords-1)
12028 (if this
12029 (nth (- (length org-todo-keywords-1)
12030 (length tail) 2)
12031 org-todo-keywords-1)
12032 (org-last org-todo-keywords-1))))
12033 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12034 (setq arg nil))) ;hack to fall back to cycling
12035 (arg
12036 ;; User or caller requests a specific state.
12037 (cond
12038 ((equal arg "") nil)
12039 ((eq arg 'none) nil)
12040 ((eq arg 'done) (or done-word (car org-done-keywords)))
12041 ((eq arg 'nextset)
12042 (or (car (cdr (member head org-todo-heads)))
12043 (car org-todo-heads)))
12044 ((eq arg 'previousset)
12045 (let ((org-todo-heads (reverse org-todo-heads)))
12046 (or (car (cdr (member head org-todo-heads)))
12047 (car org-todo-heads))))
12048 ((car (member arg org-todo-keywords-1)))
12049 ((stringp arg)
12050 (user-error "State `%s' not valid in this file" arg))
12051 ((nth (1- (prefix-numeric-value arg))
12052 org-todo-keywords-1))))
12053 ((null member) (or head (car org-todo-keywords-1)))
12054 ((equal this final-done-word) nil) ;-> make empty
12055 ((null tail) nil) ;-> first entry
12056 ((memq interpret '(type priority))
12057 (if (eq this-command last-command)
12058 (car tail)
12059 (if (> (length tail) 0)
12060 (or done-word (car org-done-keywords))
12061 nil)))
12063 (car tail))))
12064 (org-state (or
12065 (run-hook-with-args-until-success
12066 'org-todo-get-default-hook org-state org-last-state)
12067 org-state))
12068 (next (if org-state (concat " " org-state " ") " "))
12069 (change-plist (list :type 'todo-state-change :from this :to org-state
12070 :position startpos))
12071 dolog now-done-p)
12072 (when org-blocker-hook
12073 (let (org-blocked-by-checkboxes block-reason)
12074 (setq org-last-todo-state-is-todo
12075 (not (member this org-done-keywords)))
12076 (unless (save-excursion
12077 (save-match-data
12078 (org-with-wide-buffer
12079 (run-hook-with-args-until-failure
12080 'org-blocker-hook change-plist))))
12081 (setq block-reason (if org-blocked-by-checkboxes
12082 "contained checkboxes"
12083 (format "\"%s\"" org-block-entry-blocking)))
12084 (if (called-interactively-p 'interactive)
12085 (user-error "TODO state change from %s to %s blocked (by %s)"
12086 this org-state block-reason)
12087 ;; Fail silently.
12088 (message "TODO state change from %s to %s blocked (by %s)"
12089 this org-state block-reason)
12090 (throw 'exit nil)))))
12091 (store-match-data match-data)
12092 (replace-match next t t)
12093 (cond ((equal this org-state)
12094 (message "TODO state was already %s" (org-trim next)))
12095 ((not (pos-visible-in-window-p hl-pos))
12096 (message "TODO state changed to %s" (org-trim next))))
12097 (unless head
12098 (setq head (org-get-todo-sequence-head org-state)
12099 ass (assoc head org-todo-kwd-alist)
12100 interpret (nth 1 ass)
12101 done-word (nth 3 ass)
12102 final-done-word (nth 4 ass)))
12103 (when (memq arg '(nextset previousset))
12104 (message "Keyword-Set %d/%d: %s"
12105 (- (length org-todo-sets) -1
12106 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12107 (length org-todo-sets)
12108 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12109 (setq org-last-todo-state-is-todo
12110 (not (member org-state org-done-keywords)))
12111 (setq now-done-p (and (member org-state org-done-keywords)
12112 (not (member this org-done-keywords))))
12113 (and logging (org-local-logging logging))
12114 (when (and (or org-todo-log-states org-log-done)
12115 (not (eq org-inhibit-logging t))
12116 (not (memq arg '(nextset previousset))))
12117 ;; We need to look at recording a time and note.
12118 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12119 (nth 2 (assoc this org-todo-log-states))))
12120 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12121 (setq dolog 'time))
12122 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12123 (and org-state
12124 (member org-state org-not-done-keywords)
12125 (not (member this org-not-done-keywords))))
12126 ;; This is now a todo state and was not one before
12127 ;; If there was a CLOSED time stamp, get rid of it.
12128 (org-add-planning-info nil nil 'closed))
12129 (when (and now-done-p org-log-done)
12130 ;; It is now done, and it was not done before.
12131 (org-add-planning-info 'closed (org-current-effective-time))
12132 (when (and (not dolog) (eq 'note org-log-done))
12133 (org-add-log-setup 'done org-state this 'note)))
12134 (when (and org-state dolog)
12135 ;; This is a non-nil state, and we need to log it.
12136 (org-add-log-setup 'state org-state this dolog)))
12137 ;; Fixup tag positioning.
12138 (org-todo-trigger-tag-changes org-state)
12139 (when org-auto-align-tags (org-align-tags))
12140 (when org-provide-todo-statistics
12141 (org-update-parent-todo-statistics))
12142 (run-hooks 'org-after-todo-state-change-hook)
12143 (when (and arg (not (member org-state org-done-keywords)))
12144 (setq head (org-get-todo-sequence-head org-state)))
12145 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12146 ;; Do we need to trigger a repeat?
12147 (when now-done-p
12148 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12149 ;; This is for the agenda, take a snapshot of the headline.
12150 (save-match-data
12151 (setq org-agenda-headline-snapshot-before-repeat
12152 (org-get-heading))))
12153 (org-auto-repeat-maybe org-state))
12154 ;; Fixup cursor location if close to the keyword.
12155 (when (and (outline-on-heading-p)
12156 (not (bolp))
12157 (save-excursion (beginning-of-line 1)
12158 (looking-at org-todo-line-regexp))
12159 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12160 (goto-char (or (match-end 2) (match-end 1)))
12161 (and (looking-at " ") (just-one-space)))
12162 (when org-trigger-hook
12163 (save-excursion
12164 (run-hook-with-args 'org-trigger-hook change-plist)))
12165 (when commentp (org-toggle-comment))))))))
12167 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12168 "Block turning an entry into a TODO, using the hierarchy.
12169 This checks whether the current task should be blocked from state
12170 changes. Such blocking occurs when:
12172 1. The task has children which are not all in a completed state.
12174 2. A task has a parent with the property :ORDERED:, and there
12175 are siblings prior to the current task with incomplete
12176 status.
12178 3. The parent of the task is blocked because it has siblings that should
12179 be done first, or is child of a block grandparent TODO entry."
12181 (if (not org-enforce-todo-dependencies)
12182 t ; if locally turned off don't block
12183 (catch 'dont-block
12184 ;; If this is not a todo state change, or if this entry is already DONE,
12185 ;; do not block
12186 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12187 (member (plist-get change-plist :from)
12188 (cons 'done org-done-keywords))
12189 (member (plist-get change-plist :to)
12190 (cons 'todo org-not-done-keywords))
12191 (not (plist-get change-plist :to)))
12192 (throw 'dont-block t))
12193 ;; If this task has children, and any are undone, it's blocked
12194 (save-excursion
12195 (org-back-to-heading t)
12196 (let ((this-level (funcall outline-level)))
12197 (outline-next-heading)
12198 (let ((child-level (funcall outline-level)))
12199 (while (and (not (eobp))
12200 (> child-level this-level))
12201 ;; this todo has children, check whether they are all
12202 ;; completed
12203 (when (and (not (org-entry-is-done-p))
12204 (org-entry-is-todo-p))
12205 (setq org-block-entry-blocking (org-get-heading))
12206 (throw 'dont-block nil))
12207 (outline-next-heading)
12208 (setq child-level (funcall outline-level))))))
12209 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12210 ;; any previous siblings are undone, it's blocked
12211 (save-excursion
12212 (org-back-to-heading t)
12213 (let* ((pos (point))
12214 (parent-pos (and (org-up-heading-safe) (point)))
12215 (case-fold-search nil))
12216 (unless parent-pos (throw 'dont-block t)) ; no parent
12217 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12218 (forward-line 1)
12219 (re-search-forward org-not-done-heading-regexp pos t))
12220 (setq org-block-entry-blocking (match-string 0))
12221 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12222 ;; Search further up the hierarchy, to see if an ancestor is blocked
12223 (while t
12224 (goto-char parent-pos)
12225 (unless (looking-at org-not-done-heading-regexp)
12226 (throw 'dont-block t)) ; do not block, parent is not a TODO
12227 (setq pos (point))
12228 (setq parent-pos (and (org-up-heading-safe) (point)))
12229 (unless parent-pos (throw 'dont-block t)) ; no parent
12230 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12231 (forward-line 1)
12232 (re-search-forward org-not-done-heading-regexp pos t)
12233 (setq org-block-entry-blocking (org-get-heading)))
12234 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12236 (defcustom org-track-ordered-property-with-tag nil
12237 "Should the ORDERED property also be shown as a tag?
12238 The ORDERED property decides if an entry should require subtasks to be
12239 completed in sequence. Since a property is not very visible, setting
12240 this option means that toggling the ORDERED property with the command
12241 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12242 not relevant for the behavior, but it makes things more visible.
12244 Note that toggling the tag with tags commands will not change the property
12245 and therefore not influence behavior!
12247 This can be t, meaning the tag ORDERED should be used, It can also be a
12248 string to select a different tag for this task."
12249 :group 'org-todo
12250 :type '(choice
12251 (const :tag "No tracking" nil)
12252 (const :tag "Track with ORDERED tag" t)
12253 (string :tag "Use other tag")))
12255 (defun org-toggle-ordered-property ()
12256 "Toggle the ORDERED property of the current entry.
12257 For better visibility, you can track the value of this property with a tag.
12258 See variable `org-track-ordered-property-with-tag'."
12259 (interactive)
12260 (let* ((t1 org-track-ordered-property-with-tag)
12261 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12262 (save-excursion
12263 (org-back-to-heading)
12264 (if (org-entry-get nil "ORDERED")
12265 (progn
12266 (org-delete-property "ORDERED")
12267 (and tag (org-toggle-tag tag 'off))
12268 (message "Subtasks can be completed in arbitrary order"))
12269 (org-entry-put nil "ORDERED" "t")
12270 (and tag (org-toggle-tag tag 'on))
12271 (message "Subtasks must be completed in sequence")))))
12273 (defun org-block-todo-from-checkboxes (change-plist)
12274 "Block turning an entry into a TODO, using checkboxes.
12275 This checks whether the current task should be blocked from state
12276 changes because there are unchecked boxes in this entry."
12277 (if (not org-enforce-todo-checkbox-dependencies)
12278 t ; if locally turned off don't block
12279 (catch 'dont-block
12280 ;; If this is not a todo state change, or if this entry is already DONE,
12281 ;; do not block
12282 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12283 (member (plist-get change-plist :from)
12284 (cons 'done org-done-keywords))
12285 (member (plist-get change-plist :to)
12286 (cons 'todo org-not-done-keywords))
12287 (not (plist-get change-plist :to)))
12288 (throw 'dont-block t))
12289 ;; If this task has checkboxes that are not checked, it's blocked
12290 (save-excursion
12291 (org-back-to-heading t)
12292 (let ((beg (point)) end)
12293 (outline-next-heading)
12294 (setq end (point))
12295 (goto-char beg)
12296 (when (org-list-search-forward
12297 (concat (org-item-beginning-re)
12298 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12299 "\\[[- ]\\]")
12300 end t)
12301 (when (boundp 'org-blocked-by-checkboxes)
12302 (setq org-blocked-by-checkboxes t))
12303 (throw 'dont-block nil))))
12304 t))) ; do not block
12306 (defun org-entry-blocked-p ()
12307 "Non-nil if entry at point is blocked."
12308 (and (not (org-entry-get nil "NOBLOCKING"))
12309 (member (org-entry-get nil "TODO") org-not-done-keywords)
12310 (not (run-hook-with-args-until-failure
12311 'org-blocker-hook
12312 (list :type 'todo-state-change
12313 :position (point)
12314 :from 'todo
12315 :to 'done)))))
12317 (defun org-update-statistics-cookies (all)
12318 "Update the statistics cookie, either from TODO or from checkboxes.
12319 This should be called with the cursor in a line with a statistics
12320 cookie. When called with a \\[universal-argument] prefix, update
12321 all statistics cookies in the buffer."
12322 (interactive "P")
12323 (if all
12324 (progn
12325 (org-update-checkbox-count 'all)
12326 (org-map-entries 'org-update-parent-todo-statistics))
12327 (if (not (org-at-heading-p))
12328 (org-update-checkbox-count)
12329 (let ((pos (point-marker))
12330 end l1 l2)
12331 (ignore-errors (org-back-to-heading t))
12332 (if (not (org-at-heading-p))
12333 (org-update-checkbox-count)
12334 (setq l1 (org-outline-level))
12335 (setq end (save-excursion
12336 (outline-next-heading)
12337 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12338 (point)))
12339 (if (and (save-excursion
12340 (re-search-forward
12341 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12342 (not (save-excursion (re-search-forward
12343 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12344 (org-update-checkbox-count)
12345 (if (and l2 (> l2 l1))
12346 (progn
12347 (goto-char end)
12348 (org-update-parent-todo-statistics))
12349 (goto-char pos)
12350 (beginning-of-line 1)
12351 (while (re-search-forward
12352 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12353 (point-at-eol) t)
12354 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12355 (goto-char pos)
12356 (move-marker pos nil)))))
12358 (defvar org-entry-property-inherited-from) ;; defined below
12359 (defun org-update-parent-todo-statistics ()
12360 "Update any statistics cookie in the parent of the current headline.
12361 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12362 the entire subtree and this will travel up the hierarchy and update
12363 statistics everywhere."
12364 (let* ((prop (save-excursion (org-up-heading-safe)
12365 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12366 (recursive (or (not org-hierarchical-todo-statistics)
12367 (and prop (string-match "\\<recursive\\>" prop))))
12368 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12370 (first t)
12371 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12372 level ltoggle l1 new ndel
12373 (cnt-all 0) (cnt-done 0) is-percent kwd
12374 checkbox-beg cookie-present)
12375 (catch 'exit
12376 (save-excursion
12377 (beginning-of-line 1)
12378 (setq ltoggle (funcall outline-level))
12379 ;; Three situations are to consider:
12381 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12382 ;; to the top-level ancestor on the headline;
12384 ;; 2. If parent has "recursive" property, repeat up to the
12385 ;; headline setting that property, taking inheritance into
12386 ;; account;
12388 ;; 3. Else, move up to direct parent and proceed only once.
12389 (while (and (setq level (org-up-heading-safe))
12390 (or recursive first)
12391 (>= (point) lim))
12392 (setq first nil cookie-present nil)
12393 (unless (and level
12394 (not (string-match
12395 "\\<checkbox\\>"
12396 (downcase (or (org-entry-get nil "COOKIE_DATA")
12397 "")))))
12398 (throw 'exit nil))
12399 (while (re-search-forward box-re (point-at-eol) t)
12400 (setq cnt-all 0 cnt-done 0 cookie-present t)
12401 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12402 (save-match-data
12403 (unless (outline-next-heading) (throw 'exit nil))
12404 (while (and (looking-at org-complex-heading-regexp)
12405 (> (setq l1 (length (match-string 1))) level))
12406 (setq kwd (and (or recursive (= l1 ltoggle))
12407 (match-string 2)))
12408 (if (or (eq org-provide-todo-statistics 'all-headlines)
12409 (and (eq org-provide-todo-statistics t)
12410 (or (member kwd org-done-keywords)))
12411 (and (listp org-provide-todo-statistics)
12412 (stringp (car org-provide-todo-statistics))
12413 (or (member kwd org-provide-todo-statistics)
12414 (member kwd org-done-keywords)))
12415 (and (listp org-provide-todo-statistics)
12416 (listp (car org-provide-todo-statistics))
12417 (or (member kwd (car org-provide-todo-statistics))
12418 (and (member kwd org-done-keywords)
12419 (member kwd (cadr org-provide-todo-statistics))))))
12420 (setq cnt-all (1+ cnt-all))
12421 (and (eq org-provide-todo-statistics t)
12423 (setq cnt-all (1+ cnt-all))))
12424 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12425 (member kwd org-done-keywords))
12426 (and (listp org-provide-todo-statistics)
12427 (listp (car org-provide-todo-statistics))
12428 (member kwd org-done-keywords)
12429 (member kwd (cadr org-provide-todo-statistics)))
12430 (and (listp org-provide-todo-statistics)
12431 (stringp (car org-provide-todo-statistics))
12432 (member kwd org-done-keywords)))
12433 (setq cnt-done (1+ cnt-done)))
12434 (outline-next-heading)))
12435 (setq new
12436 (if is-percent
12437 (format "[%d%%]" (floor (* 100.0 cnt-done)
12438 (max 1 cnt-all)))
12439 (format "[%d/%d]" cnt-done cnt-all))
12440 ndel (- (match-end 0) checkbox-beg))
12441 (goto-char checkbox-beg)
12442 (insert new)
12443 (delete-region (point) (+ (point) ndel))
12444 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12445 (when cookie-present
12446 (run-hook-with-args 'org-after-todo-statistics-hook
12447 cnt-done (- cnt-all cnt-done))))))
12448 (run-hooks 'org-todo-statistics-hook)))
12450 (defvar org-after-todo-statistics-hook nil
12451 "Hook that is called after a TODO statistics cookie has been updated.
12452 Each function is called with two arguments: the number of not-done entries
12453 and the number of done entries.
12455 For example, the following function, when added to this hook, will switch
12456 an entry to DONE when all children are done, and back to TODO when new
12457 entries are set to a TODO status. Note that this hook is only called
12458 when there is a statistics cookie in the headline!
12460 (defun org-summary-todo (n-done n-not-done)
12461 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12462 (let (org-log-done org-log-states) ; turn off logging
12463 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12466 (defvar org-todo-statistics-hook nil
12467 "Hook that is run whenever Org thinks TODO statistics should be updated.
12468 This hook runs even if there is no statistics cookie present, in which case
12469 `org-after-todo-statistics-hook' would not run.")
12471 (defun org-todo-trigger-tag-changes (state)
12472 "Apply the changes defined in `org-todo-state-tags-triggers'."
12473 (let ((l org-todo-state-tags-triggers)
12474 changes)
12475 (when (or (not state) (equal state ""))
12476 (setq changes (append changes (cdr (assoc "" l)))))
12477 (when (and (stringp state) (> (length state) 0))
12478 (setq changes (append changes (cdr (assoc state l)))))
12479 (when (member state org-not-done-keywords)
12480 (setq changes (append changes (cdr (assq 'todo l)))))
12481 (when (member state org-done-keywords)
12482 (setq changes (append changes (cdr (assq 'done l)))))
12483 (dolist (c changes)
12484 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12486 (defun org-local-logging (value)
12487 "Get logging settings from a property VALUE."
12488 ;; Directly set the variables, they are already local.
12489 (setq org-log-done nil
12490 org-log-repeat nil
12491 org-todo-log-states nil)
12492 (dolist (w (split-string value))
12493 (let (a)
12494 (cond
12495 ((setq a (assoc w org-startup-options))
12496 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12497 (set (nth 1 a) (nth 2 a))))
12498 ((setq a (org-extract-log-state-settings w))
12499 (and (member (car a) org-todo-keywords-1)
12500 (push a org-todo-log-states)))))))
12502 (defun org-get-todo-sequence-head (kwd)
12503 "Return the head of the TODO sequence to which KWD belongs.
12504 If KWD is not set, check if there is a text property remembering the
12505 right sequence."
12506 (let (p)
12507 (cond
12508 ((not kwd)
12509 (or (get-text-property (point-at-bol) 'org-todo-head)
12510 (progn
12511 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12512 nil (point-at-eol)))
12513 (get-text-property p 'org-todo-head))))
12514 ((not (member kwd org-todo-keywords-1))
12515 (car org-todo-keywords-1))
12516 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12518 (defun org-fast-todo-selection ()
12519 "Fast TODO keyword selection with single keys.
12520 Returns the new TODO keyword, or nil if no state change should occur."
12521 (let* ((fulltable org-todo-key-alist)
12522 (done-keywords org-done-keywords) ;; needed for the faces.
12523 (maxlen (apply 'max (mapcar
12524 (lambda (x)
12525 (if (stringp (car x)) (string-width (car x)) 0))
12526 fulltable)))
12527 (expert nil)
12528 (fwidth (+ maxlen 3 1 3))
12529 (ncol (/ (- (window-width) 4) fwidth))
12530 tg cnt e c tbl
12531 groups ingroup)
12532 (save-excursion
12533 (save-window-excursion
12534 (if expert
12535 (set-buffer (get-buffer-create " *Org todo*"))
12536 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12537 (erase-buffer)
12538 (setq-local org-done-keywords done-keywords)
12539 (setq tbl fulltable cnt 0)
12540 (while (setq e (pop tbl))
12541 (cond
12542 ((equal e '(:startgroup))
12543 (push '() groups) (setq ingroup t)
12544 (unless (= cnt 0)
12545 (setq cnt 0)
12546 (insert "\n"))
12547 (insert "{ "))
12548 ((equal e '(:endgroup))
12549 (setq ingroup nil cnt 0)
12550 (insert "}\n"))
12551 ((equal e '(:newline))
12552 (unless (= cnt 0)
12553 (setq cnt 0)
12554 (insert "\n")
12555 (setq e (car tbl))
12556 (while (equal (car tbl) '(:newline))
12557 (insert "\n")
12558 (setq tbl (cdr tbl)))))
12560 (setq tg (car e) c (cdr e))
12561 (when ingroup (push tg (car groups)))
12562 (setq tg (org-add-props tg nil 'face
12563 (org-get-todo-face tg)))
12564 (when (and (= cnt 0) (not ingroup)) (insert " "))
12565 (insert "[" c "] " tg (make-string
12566 (- fwidth 4 (length tg)) ?\ ))
12567 (when (= (setq cnt (1+ cnt)) ncol)
12568 (insert "\n")
12569 (when ingroup (insert " "))
12570 (setq cnt 0)))))
12571 (insert "\n")
12572 (goto-char (point-min))
12573 (unless expert (org-fit-window-to-buffer))
12574 (message "[a-z..]:Set [SPC]:clear")
12575 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12576 (cond
12577 ((or (= c ?\C-g)
12578 (and (= c ?q) (not (rassoc c fulltable))))
12579 (setq quit-flag t))
12580 ((= c ?\ ) nil)
12581 ((setq e (rassoc c fulltable) tg (car e))
12583 (t (setq quit-flag t)))))))
12585 (defun org-entry-is-todo-p ()
12586 (member (org-get-todo-state) org-not-done-keywords))
12588 (defun org-entry-is-done-p ()
12589 (member (org-get-todo-state) org-done-keywords))
12591 (defun org-get-todo-state ()
12592 "Return the TODO keyword of the current subtree."
12593 (save-excursion
12594 (org-back-to-heading t)
12595 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12596 (match-end 2)
12597 (match-string 2))))
12599 (defun org-at-date-range-p (&optional inactive-ok)
12600 "Non-nil if point is inside a date range.
12602 When optional argument INACTIVE-OK is non-nil, also consider
12603 inactive time ranges.
12605 When this function returns a non-nil value, match data is set
12606 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12607 on INACTIVE-OK."
12608 (interactive)
12609 (save-excursion
12610 (catch 'exit
12611 (let ((pos (point)))
12612 (skip-chars-backward "^[<\r\n")
12613 (skip-chars-backward "<[")
12614 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12615 (>= (match-end 0) pos)
12616 (throw 'exit t))
12617 (skip-chars-backward "^<[\r\n")
12618 (skip-chars-backward "<[")
12619 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12620 (>= (match-end 0) pos)
12621 (throw 'exit t)))
12622 nil)))
12624 (defun org-get-repeat (&optional timestamp)
12625 "Check if there is a time-stamp with repeater in this entry.
12627 Return the repeater, as a string, or nil. Also return nil when
12628 this function is called before first heading.
12630 When optional argument TIMESTAMP is a string, extract the
12631 repeater from there instead."
12632 (save-match-data
12633 (cond (timestamp
12634 (and (string-match org-repeat-re timestamp)
12635 (match-string-no-properties 1 timestamp)))
12636 ((org-before-first-heading-p) nil)
12638 (save-excursion
12639 (org-back-to-heading t)
12640 (let ((end (org-entry-end-position)))
12641 (catch :repeat
12642 (while (re-search-forward org-repeat-re end t)
12643 (when (save-match-data (org-at-timestamp-p 'agenda))
12644 (throw :repeat (match-string-no-properties 1)))))))))))
12646 (defvar org-last-changed-timestamp)
12647 (defvar org-last-inserted-timestamp)
12648 (defvar org-log-post-message)
12649 (defvar org-log-note-purpose)
12650 (defvar org-log-note-how nil)
12651 (defvar org-log-note-extra)
12652 (defun org-auto-repeat-maybe (done-word)
12653 "Check if the current headline contains a repeated time-stamp.
12655 If yes, set TODO state back to what it was and change the base date
12656 of repeating deadline/scheduled time stamps to new date.
12658 This function is run automatically after each state change to a DONE state."
12659 (let* ((repeat (org-get-repeat))
12660 (aa (assoc org-last-state org-todo-kwd-alist))
12661 (interpret (nth 1 aa))
12662 (head (nth 2 aa))
12663 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12664 (msg "Entry repeats: ")
12665 (org-log-done nil)
12666 (org-todo-log-states nil)
12667 (end (copy-marker (org-entry-end-position))))
12668 (unwind-protect
12669 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12670 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12671 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12672 (and (stringp org-todo-repeat-to-state)
12673 org-todo-repeat-to-state)
12674 (and org-todo-repeat-to-state org-last-state))))
12675 (org-todo (cond
12676 ((and to-state (member to-state org-todo-keywords-1))
12677 to-state)
12678 ((eq interpret 'type) org-last-state)
12679 (head)
12680 (t 'none))))
12681 (org-back-to-heading t)
12682 (org-add-planning-info nil nil 'closed)
12683 ;; When `org-log-repeat' is non-nil or entry contains
12684 ;; a clock, set LAST_REPEAT property.
12685 (when (or org-log-repeat
12686 (catch :clock
12687 (save-excursion
12688 (while (re-search-forward org-clock-line-re end t)
12689 (when (org-at-clock-log-p) (throw :clock t))))))
12690 (org-entry-put nil "LAST_REPEAT" (format-time-string
12691 (org-time-stamp-format t t)
12692 (current-time))))
12693 (when org-log-repeat
12694 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12695 (memq 'org-add-log-note post-command-hook))
12696 ;; We are already setup for some record.
12697 (when (eq org-log-repeat 'note)
12698 ;; Make sure we take a note, not only a time stamp.
12699 (setq org-log-note-how 'note))
12700 ;; Set up for taking a record.
12701 (org-add-log-setup 'state
12702 (or done-word (car org-done-keywords))
12703 org-last-state
12704 org-log-repeat)))
12705 (let ((planning-re (regexp-opt
12706 (list org-scheduled-string org-deadline-string))))
12707 (while (re-search-forward org-ts-regexp end t)
12708 (let* ((ts (match-string 0))
12709 (planning? (org-at-planning-p))
12710 (type (if (not planning?) "Plain:"
12711 (save-excursion
12712 (re-search-backward
12713 planning-re (line-beginning-position) t)
12714 (match-string 0)))))
12715 (cond
12716 ;; Ignore fake time-stamps (e.g., within comments).
12717 ((not (org-at-timestamp-p 'agenda)))
12718 ;; Time-stamps without a repeater are usually
12719 ;; skipped. However, a SCHEDULED time-stamp without
12720 ;; one is removed, as they are no longer relevant.
12721 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12722 ts))
12723 (when (equal type org-scheduled-string)
12724 (org-remove-timestamp-with-keyword type)))
12726 (let ((n (string-to-number (match-string 2 ts)))
12727 (what (match-string 3 ts)))
12728 (when (equal what "w") (setq n (* n 7) what "d"))
12729 (when (and (equal what "h")
12730 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12731 ts)))
12732 (user-error
12733 "Cannot repeat in Repeat in %d hour(s) because no hour \
12734 has been set"
12736 ;; Preparation, see if we need to modify the start
12737 ;; date for the change.
12738 (when (match-end 1)
12739 (let ((time (save-match-data
12740 (org-time-string-to-time ts))))
12741 (cond
12742 ((equal (match-string 1 ts) ".")
12743 ;; Shift starting date to today
12744 (org-timestamp-change
12745 (- (org-today) (time-to-days time))
12746 'day))
12747 ((equal (match-string 1 ts) "+")
12748 (let ((nshiftmax 10)
12749 (nshift 0))
12750 (while (or (= nshift 0)
12751 (not (time-less-p (current-time) time)))
12752 (when (= (cl-incf nshift) nshiftmax)
12753 (or (y-or-n-p
12754 (format "%d repeater intervals were not \
12755 enough to shift date past today. Continue? "
12756 nshift))
12757 (user-error "Abort")))
12758 (org-timestamp-change n (cdr (assoc what whata)))
12759 (org-in-regexp org-ts-regexp3)
12760 (setq ts (match-string 1))
12761 (setq time
12762 (save-match-data
12763 (org-time-string-to-time ts)))))
12764 (org-timestamp-change (- n) (cdr (assoc what whata)))
12765 ;; Rematch, so that we have everything in place
12766 ;; for the real shift.
12767 (org-in-regexp org-ts-regexp3)
12768 (setq ts (match-string 1))
12769 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12770 ts)))))
12771 (save-excursion
12772 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12773 (setq msg
12774 (concat
12775 msg type " " org-last-changed-timestamp " "))))))))
12776 (setq org-log-post-message msg)
12777 (message "%s" msg))
12778 (set-marker end nil))))
12780 (defun org-show-todo-tree (arg)
12781 "Make a compact tree which shows all headlines marked with TODO.
12782 The tree will show the lines where the regexp matches, and all higher
12783 headlines above the match.
12784 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12785 With a numeric prefix N, construct a sparse tree for the Nth element
12786 of `org-todo-keywords-1'."
12787 (interactive "P")
12788 (let ((case-fold-search nil)
12789 (kwd-re
12790 (cond ((null arg) org-not-done-regexp)
12791 ((equal arg '(4))
12792 (let ((kwd
12793 (completing-read "Keyword (or KWD1|KWD2|...): "
12794 (mapcar #'list org-todo-keywords-1))))
12795 (concat "\\("
12796 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12797 "\\)\\>")))
12798 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12799 (regexp-quote (nth (1- (prefix-numeric-value arg))
12800 org-todo-keywords-1)))
12801 (t (user-error "Invalid prefix argument: %s" arg)))))
12802 (message "%d TODO entries found"
12803 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12805 (defun org--deadline-or-schedule (arg type time)
12806 "Insert DEADLINE or SCHEDULE information in current entry.
12807 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12808 `org-schedule' for information about ARG and TIME arguments."
12809 (let* ((deadline? (eq type 'deadline))
12810 (keyword (if deadline? org-deadline-string org-scheduled-string))
12811 (log (if deadline? org-log-redeadline org-log-reschedule))
12812 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12813 (old-date-time (and old-date (org-time-string-to-time old-date)))
12814 ;; Save repeater cookie from either TIME or current scheduled
12815 ;; time stamp. We are going to insert it back at the end of
12816 ;; the process.
12817 (repeater (or (and (org-string-nw-p time)
12818 ;; We use `org-repeat-re' because we need
12819 ;; to tell the difference between a real
12820 ;; repeater and a time delta, e.g. "+2d".
12821 (string-match org-repeat-re time)
12822 (match-string 1 time))
12823 (and (org-string-nw-p old-date)
12824 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12825 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12826 old-date)
12827 (match-string 1 old-date)))))
12828 (pcase arg
12829 (`(4)
12830 (when (and old-date log)
12831 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12832 nil old-date log))
12833 (org-remove-timestamp-with-keyword keyword)
12834 (message (if deadline? "Item no longer has a deadline."
12835 "Item is no longer scheduled.")))
12836 (`(16)
12837 (save-excursion
12838 (org-back-to-heading t)
12839 (let ((regexp (if deadline? org-deadline-time-regexp
12840 org-scheduled-time-regexp)))
12841 (if (not (re-search-forward regexp (line-end-position 2) t))
12842 (user-error (if deadline? "No deadline information to update"
12843 "No scheduled information to update"))
12844 (let* ((rpl0 (match-string 1))
12845 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12846 (msg (if deadline? "Warn starting from" "Delay until")))
12847 (replace-match
12848 (concat keyword
12849 " <" rpl
12850 (format " -%dd"
12851 (abs (- (time-to-days
12852 (save-match-data
12853 (org-read-date
12854 nil t nil msg old-date-time)))
12855 (time-to-days old-date-time))))
12856 ">") t t))))))
12858 (org-add-planning-info type time 'closed)
12859 (when (and old-date
12861 (not (equal old-date org-last-inserted-timestamp)))
12862 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12863 org-last-inserted-timestamp
12864 old-date
12865 log))
12866 (when repeater
12867 (save-excursion
12868 (org-back-to-heading t)
12869 (when (re-search-forward
12870 (concat keyword " " org-last-inserted-timestamp)
12871 (line-end-position 2)
12873 (goto-char (1- (match-end 0)))
12874 (insert " " repeater)
12875 (setq org-last-inserted-timestamp
12876 (concat (substring org-last-inserted-timestamp 0 -1)
12877 " " repeater
12878 (substring org-last-inserted-timestamp -1))))))
12879 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12880 org-last-inserted-timestamp)))))
12882 (defun org-deadline (arg &optional time)
12883 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12884 With one universal prefix argument, remove any deadline from the item.
12885 With two universal prefix arguments, prompt for a warning delay.
12886 With argument TIME, set the deadline at the corresponding date. TIME
12887 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12888 (interactive "P")
12889 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12890 (org-map-entries
12891 (lambda () (org--deadline-or-schedule arg 'deadline time))
12893 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12894 'region-start-level
12895 'region)
12896 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12897 (org--deadline-or-schedule arg 'deadline time)))
12899 (defun org-schedule (arg &optional time)
12900 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12901 With one universal prefix argument, remove any scheduling date from the item.
12902 With two universal prefix arguments, prompt for a delay cookie.
12903 With argument TIME, scheduled at the corresponding date. TIME can
12904 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12905 (interactive "P")
12906 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12907 (org-map-entries
12908 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12910 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12911 'region-start-level
12912 'region)
12913 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12914 (org--deadline-or-schedule arg 'scheduled time)))
12916 (defun org-get-scheduled-time (pom &optional inherit)
12917 "Get the scheduled time as a time tuple, of a format suitable
12918 for calling org-schedule with, or if there is no scheduling,
12919 returns nil."
12920 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12921 (when time
12922 (apply 'encode-time (org-parse-time-string time)))))
12924 (defun org-get-deadline-time (pom &optional inherit)
12925 "Get the deadline as a time tuple, of a format suitable for
12926 calling org-deadline with, or if there is no scheduling, returns
12927 nil."
12928 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12929 (when time
12930 (apply 'encode-time (org-parse-time-string time)))))
12932 (defun org-remove-timestamp-with-keyword (keyword)
12933 "Remove all time stamps with KEYWORD in the current entry."
12934 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12935 beg)
12936 (save-excursion
12937 (org-back-to-heading t)
12938 (setq beg (point))
12939 (outline-next-heading)
12940 (while (re-search-backward re beg t)
12941 (replace-match "")
12942 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12943 (equal (char-before) ?\ ))
12944 (backward-delete-char 1)
12945 (when (string-match "^[ \t]*$" (buffer-substring
12946 (point-at-bol) (point-at-eol)))
12947 (delete-region (point-at-bol)
12948 (min (point-max) (1+ (point-at-eol))))))))))
12950 (defvar org-time-was-given) ; dynamically scoped parameter
12951 (defvar org-end-time-was-given) ; dynamically scoped parameter
12953 (defun org-at-planning-p ()
12954 "Non-nil when point is on a planning info line."
12955 ;; This is as accurate and faster than `org-element-at-point' since
12956 ;; planning info location is fixed in the section.
12957 (org-with-wide-buffer
12958 (beginning-of-line)
12959 (and (looking-at-p org-planning-line-re)
12960 (eq (point)
12961 (ignore-errors
12962 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12963 (org-back-to-heading t)
12964 (org-with-limited-levels (org-back-to-heading t)))
12965 (line-beginning-position 2))))))
12967 (defun org-add-planning-info (what &optional time &rest remove)
12968 "Insert new timestamp with keyword in the planning line.
12969 WHAT indicates what kind of time stamp to add. It is a symbol
12970 among `closed', `deadline', `scheduled' and nil. TIME indicates
12971 the time to use. If none is given, the user is prompted for
12972 a date. REMOVE indicates what kind of entries to remove. An old
12973 WHAT entry will also be removed."
12974 (let (org-time-was-given org-end-time-was-given default-time default-input)
12975 (catch 'exit
12976 (when (and (memq what '(scheduled deadline))
12977 (or (not time)
12978 (and (stringp time)
12979 (string-match "^[-+]+[0-9]" time))))
12980 ;; Try to get a default date/time from existing timestamp
12981 (save-excursion
12982 (org-back-to-heading t)
12983 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12984 (when (re-search-forward (if (eq what 'scheduled)
12985 org-scheduled-time-regexp
12986 org-deadline-time-regexp)
12987 end t)
12988 (setq ts (match-string 1)
12989 default-time (apply 'encode-time (org-parse-time-string ts))
12990 default-input (and ts (org-get-compact-tod ts)))))))
12991 (when what
12992 (setq time
12993 (if (stringp time)
12994 ;; This is a string (relative or absolute), set
12995 ;; proper date.
12996 (apply #'encode-time
12997 (org-read-date-analyze
12998 time default-time (decode-time default-time)))
12999 ;; If necessary, get the time from the user
13000 (or time (org-read-date nil 'to-time nil nil
13001 default-time default-input)))))
13003 (org-with-wide-buffer
13004 (org-back-to-heading t)
13005 (forward-line)
13006 (unless (bolp) (insert "\n"))
13007 (cond ((looking-at-p org-planning-line-re)
13008 ;; Move to current indentation.
13009 (skip-chars-forward " \t")
13010 ;; Check if we have to remove something.
13011 (dolist (type (if what (cons what remove) remove))
13012 (save-excursion
13013 (when (re-search-forward
13014 (cl-case type
13015 (closed org-closed-time-regexp)
13016 (deadline org-deadline-time-regexp)
13017 (scheduled org-scheduled-time-regexp)
13018 (otherwise
13019 (error "Invalid planning type: %s" type)))
13020 (line-end-position) t)
13021 ;; Delete until next keyword or end of line.
13022 (delete-region
13023 (match-beginning 0)
13024 (if (re-search-forward org-keyword-time-not-clock-regexp
13025 (line-end-position)
13027 (match-beginning 0)
13028 (line-end-position))))))
13029 ;; If there is nothing more to add and no more keyword
13030 ;; is left, remove the line completely.
13031 (if (and (looking-at-p "[ \t]*$") (not what))
13032 (delete-region (line-beginning-position)
13033 (line-beginning-position 2))
13034 ;; If we removed last keyword, do not leave trailing
13035 ;; white space at the end of line.
13036 (let ((p (point)))
13037 (save-excursion
13038 (end-of-line)
13039 (unless (= (skip-chars-backward " \t" p) 0)
13040 (delete-region (point) (line-end-position)))))))
13041 ((not what) (throw 'exit nil)) ; Nothing to do.
13042 (t (insert-before-markers "\n")
13043 (backward-char 1)
13044 (when org-adapt-indentation
13045 (indent-to-column (1+ (org-outline-level))))))
13046 (when what
13047 ;; Insert planning keyword.
13048 (insert (cl-case what
13049 (closed org-closed-string)
13050 (deadline org-deadline-string)
13051 (scheduled org-scheduled-string)
13052 (otherwise (error "Invalid planning type: %s" what)))
13053 " ")
13054 ;; Insert associated timestamp.
13055 (let ((ts (org-insert-time-stamp
13056 time
13057 (or org-time-was-given
13058 (and (eq what 'closed) org-log-done-with-time))
13059 (eq what 'closed)
13060 nil nil (list org-end-time-was-given))))
13061 (unless (eolp) (insert " "))
13062 ts))))))
13064 (defvar org-log-note-marker (make-marker)
13065 "Marker pointing at the entry where the note is to be inserted.")
13066 (defvar org-log-note-purpose nil)
13067 (defvar org-log-note-state nil)
13068 (defvar org-log-note-previous-state nil)
13069 (defvar org-log-note-extra nil)
13070 (defvar org-log-note-window-configuration nil)
13071 (defvar org-log-note-return-to (make-marker))
13072 (defvar org-log-note-effective-time nil
13073 "Remembered current time so that dynamically scoped
13074 `org-extend-today-until' affects timestamps in state change log")
13076 (defvar org-log-post-message nil
13077 "Message to be displayed after a log note has been stored.
13078 The auto-repeater uses this.")
13080 (defun org-add-note ()
13081 "Add a note to the current entry.
13082 This is done in the same way as adding a state change note."
13083 (interactive)
13084 (org-add-log-setup 'note))
13086 (defun org-log-beginning (&optional create)
13087 "Return expected start of log notes in current entry.
13088 When optional argument CREATE is non-nil, the function creates
13089 a drawer to store notes, if necessary. Returned position ignores
13090 narrowing."
13091 (org-with-wide-buffer
13092 (let ((drawer (org-log-into-drawer)))
13093 (cond
13094 (drawer
13095 (org-end-of-meta-data)
13096 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13097 (end (if (org-at-heading-p) (point)
13098 (save-excursion (outline-next-heading) (point))))
13099 (case-fold-search t))
13100 (catch 'exit
13101 ;; Try to find existing drawer.
13102 (while (re-search-forward regexp end t)
13103 (let ((element (org-element-at-point)))
13104 (when (eq (org-element-type element) 'drawer)
13105 (let ((cend (org-element-property :contents-end element)))
13106 (when (and (not org-log-states-order-reversed) cend)
13107 (goto-char cend)))
13108 (throw 'exit nil))))
13109 ;; No drawer found. Create one, if permitted.
13110 (when create
13111 (unless (bolp) (insert "\n"))
13112 (let ((beg (point)))
13113 (insert ":" drawer ":\n:END:\n")
13114 (org-indent-region beg (point))
13115 (org-flag-region
13116 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13117 (end-of-line -1)))))
13119 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13120 (skip-chars-forward " \t\n")
13121 (beginning-of-line)
13122 (unless org-log-states-order-reversed
13123 (org-skip-over-state-notes)
13124 (skip-chars-backward " \t\n")
13125 (forward-line)))))
13126 (if (bolp) (point) (line-beginning-position 2))))
13128 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13129 "Set up the post command hook to take a note.
13130 If this is about to TODO state change, the new state is expected in STATE.
13131 HOW is an indicator what kind of note should be created.
13132 EXTRA is additional text that will be inserted into the notes buffer."
13133 (move-marker org-log-note-marker (point))
13134 (setq org-log-note-purpose purpose
13135 org-log-note-state state
13136 org-log-note-previous-state prev-state
13137 org-log-note-how how
13138 org-log-note-extra extra
13139 org-log-note-effective-time (org-current-effective-time))
13140 (add-hook 'post-command-hook 'org-add-log-note 'append))
13142 (defun org-skip-over-state-notes ()
13143 "Skip past the list of State notes in an entry."
13144 (when (ignore-errors (goto-char (org-in-item-p)))
13145 (let* ((struct (org-list-struct))
13146 (prevs (org-list-prevs-alist struct))
13147 (regexp
13148 (concat "[ \t]*- +"
13149 (replace-regexp-in-string
13150 " +" " +"
13151 (org-replace-escapes
13152 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13153 `(("%d" . ,org-ts-regexp-inactive)
13154 ("%D" . ,org-ts-regexp)
13155 ("%s" . "\"\\S-+\"")
13156 ("%S" . "\"\\S-+\"")
13157 ("%t" . ,org-ts-regexp-inactive)
13158 ("%T" . ,org-ts-regexp)
13159 ("%u" . ".*?")
13160 ("%U" . ".*?")))))))
13161 (while (looking-at-p regexp)
13162 (goto-char (or (org-list-get-next-item (point) struct prevs)
13163 (org-list-get-item-end (point) struct)))))))
13165 (defun org-add-log-note (&optional _purpose)
13166 "Pop up a window for taking a note, and add this note later."
13167 (remove-hook 'post-command-hook 'org-add-log-note)
13168 (setq org-log-note-window-configuration (current-window-configuration))
13169 (delete-other-windows)
13170 (move-marker org-log-note-return-to (point))
13171 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13172 (goto-char org-log-note-marker)
13173 (org-switch-to-buffer-other-window "*Org Note*")
13174 (erase-buffer)
13175 (if (memq org-log-note-how '(time state))
13176 (org-store-log-note)
13177 (let ((org-inhibit-startup t)) (org-mode))
13178 (insert (format "# Insert note for %s.
13179 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13180 (cond
13181 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13182 ((eq org-log-note-purpose 'done) "closed todo item")
13183 ((eq org-log-note-purpose 'state)
13184 (format "state change from \"%s\" to \"%s\""
13185 (or org-log-note-previous-state "")
13186 (or org-log-note-state "")))
13187 ((eq org-log-note-purpose 'reschedule)
13188 "rescheduling")
13189 ((eq org-log-note-purpose 'delschedule)
13190 "no longer scheduled")
13191 ((eq org-log-note-purpose 'redeadline)
13192 "changing deadline")
13193 ((eq org-log-note-purpose 'deldeadline)
13194 "removing deadline")
13195 ((eq org-log-note-purpose 'refile)
13196 "refiling")
13197 ((eq org-log-note-purpose 'note)
13198 "this entry")
13199 (t (error "This should not happen")))))
13200 (when org-log-note-extra (insert org-log-note-extra))
13201 (setq-local org-finish-function 'org-store-log-note)
13202 (run-hooks 'org-log-buffer-setup-hook)))
13204 (defvar org-note-abort nil) ; dynamically scoped
13205 (defun org-store-log-note ()
13206 "Finish taking a log note, and insert it to where it belongs."
13207 (let ((txt (prog1 (buffer-string)
13208 (kill-buffer)))
13209 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13210 lines)
13211 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13212 (setq txt (replace-match "" t t txt)))
13213 (when (string-match "\\s-+\\'" txt)
13214 (setq txt (replace-match "" t t txt)))
13215 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13216 (when (org-string-nw-p note)
13217 (setq note
13218 (org-replace-escapes
13219 note
13220 (list (cons "%u" (user-login-name))
13221 (cons "%U" user-full-name)
13222 (cons "%t" (format-time-string
13223 (org-time-stamp-format 'long 'inactive)
13224 org-log-note-effective-time))
13225 (cons "%T" (format-time-string
13226 (org-time-stamp-format 'long nil)
13227 org-log-note-effective-time))
13228 (cons "%d" (format-time-string
13229 (org-time-stamp-format nil 'inactive)
13230 org-log-note-effective-time))
13231 (cons "%D" (format-time-string
13232 (org-time-stamp-format nil nil)
13233 org-log-note-effective-time))
13234 (cons "%s" (cond
13235 ((not org-log-note-state) "")
13236 ((string-match-p org-ts-regexp
13237 org-log-note-state)
13238 (format "\"[%s]\""
13239 (substring org-log-note-state 1 -1)))
13240 (t (format "\"%s\"" org-log-note-state))))
13241 (cons "%S"
13242 (cond
13243 ((not org-log-note-previous-state) "")
13244 ((string-match-p org-ts-regexp
13245 org-log-note-previous-state)
13246 (format "\"[%s]\""
13247 (substring
13248 org-log-note-previous-state 1 -1)))
13249 (t (format "\"%s\""
13250 org-log-note-previous-state)))))))
13251 (when lines (setq note (concat note " \\\\")))
13252 (push note lines))
13253 (when (and lines (not org-note-abort))
13254 (with-current-buffer (marker-buffer org-log-note-marker)
13255 (org-with-wide-buffer
13256 ;; Find location for the new note.
13257 (goto-char org-log-note-marker)
13258 (set-marker org-log-note-marker nil)
13259 ;; Note associated to a clock is to be located right after
13260 ;; the clock. Do not move point.
13261 (unless (eq org-log-note-purpose 'clock-out)
13262 (goto-char (org-log-beginning t)))
13263 ;; Make sure point is at the beginning of an empty line.
13264 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13265 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13266 ;; In an existing list, add a new item at the top level.
13267 ;; Otherwise, indent line like a regular one.
13268 (let ((itemp (org-in-item-p)))
13269 (if itemp
13270 (indent-line-to
13271 (let ((struct (save-excursion
13272 (goto-char itemp) (org-list-struct))))
13273 (org-list-get-ind (org-list-get-top-point struct) struct)))
13274 (org-indent-line)))
13275 (insert (org-list-bullet-string "-") (pop lines))
13276 (let ((ind (org-list-item-body-column (line-beginning-position))))
13277 (dolist (line lines)
13278 (insert "\n")
13279 (indent-line-to ind)
13280 (insert line)))
13281 (message "Note stored")
13282 (org-back-to-heading t))
13283 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13284 ;; from within `org-add-log-note' because `buffer-undo-list'
13285 ;; is then modified outside of `org-with-remote-undo'.
13286 (when (eq this-command 'org-agenda-todo)
13287 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13288 ;; Don't add undo information when called from `org-agenda-todo'.
13289 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13290 (set-window-configuration org-log-note-window-configuration)
13291 (with-current-buffer (marker-buffer org-log-note-return-to)
13292 (goto-char org-log-note-return-to))
13293 (move-marker org-log-note-return-to nil)
13294 (when org-log-post-message (message "%s" org-log-post-message))))
13296 (defun org-remove-empty-drawer-at (pos)
13297 "Remove an empty drawer at position POS.
13298 POS may also be a marker."
13299 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13300 (org-with-wide-buffer
13301 (goto-char pos)
13302 (let ((drawer (org-element-at-point)))
13303 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13304 (not (org-element-property :contents-begin drawer)))
13305 (delete-region (org-element-property :begin drawer)
13306 (progn (goto-char (org-element-property :end drawer))
13307 (skip-chars-backward " \r\t\n")
13308 (forward-line)
13309 (point))))))))
13311 (defvar org-ts-type nil)
13312 (defun org-sparse-tree (&optional arg type)
13313 "Create a sparse tree, prompt for the details.
13314 This command can create sparse trees. You first need to select the type
13315 of match used to create the tree:
13317 t Show all TODO entries.
13318 T Show entries with a specific TODO keyword.
13319 m Show entries selected by a tags/property match.
13320 p Enter a property name and its value (both with completion on existing
13321 names/values) and show entries with that property.
13322 r Show entries matching a regular expression (`/' can be used as well).
13323 b Show deadlines and scheduled items before a date.
13324 a Show deadlines and scheduled items after a date.
13325 d Show deadlines due within `org-deadline-warning-days'.
13326 D Show deadlines and scheduled items between a date range."
13327 (interactive "P")
13328 (setq type (or type org-sparse-tree-default-date-type))
13329 (setq org-ts-type type)
13330 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13331 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13332 \[c]ycle through date types: %s"
13333 (cl-case type
13334 (all "all timestamps")
13335 (scheduled "only scheduled")
13336 (deadline "only deadline")
13337 (active "only active timestamps")
13338 (inactive "only inactive timestamps")
13339 (closed "with a closed time-stamp")
13340 (otherwise "scheduled/deadline")))
13341 (let ((answer (read-char-exclusive)))
13342 (cl-case answer
13344 (org-sparse-tree
13346 (cadr
13347 (memq type '(nil all scheduled deadline active inactive closed)))))
13348 (?d (call-interactively 'org-check-deadlines))
13349 (?b (call-interactively 'org-check-before-date))
13350 (?a (call-interactively 'org-check-after-date))
13351 (?D (call-interactively 'org-check-dates-range))
13352 (?t (call-interactively 'org-show-todo-tree))
13353 (?T (org-show-todo-tree '(4)))
13354 (?m (call-interactively 'org-match-sparse-tree))
13355 ((?p ?P)
13356 (let* ((kwd (completing-read
13357 "Property: " (mapcar #'list (org-buffer-property-keys))))
13358 (value (completing-read
13359 "Value: " (mapcar #'list (org-property-values kwd)))))
13360 (unless (string-match "\\`{.*}\\'" value)
13361 (setq value (concat "\"" value "\"")))
13362 (org-match-sparse-tree arg (concat kwd "=" value))))
13363 ((?r ?R ?/) (call-interactively 'org-occur))
13364 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13366 (defvar-local org-occur-highlights nil
13367 "List of overlays used for occur matches.")
13368 (defvar-local org-occur-parameters nil
13369 "Parameters of the active org-occur calls.
13370 This is a list, each call to org-occur pushes as cons cell,
13371 containing the regular expression and the callback, onto the list.
13372 The list can contain several entries if `org-occur' has been called
13373 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13374 will only contain one set of parameters. When the highlights are
13375 removed (for example with `C-c C-c', or with the next edit (depending
13376 on `org-remove-highlights-with-change'), this variable is emptied
13377 as well.")
13379 (defun org-occur (regexp &optional keep-previous callback)
13380 "Make a compact tree which shows all matches of REGEXP.
13382 The tree will show the lines where the regexp matches, and any other context
13383 defined in `org-show-context-detail', which see.
13385 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13386 done by a previous call to `org-occur' will be kept, to allow stacking of
13387 calls to this command.
13389 Optional argument CALLBACK can be a function of no argument. In this case,
13390 it is called with point at the end of the match, match data being set
13391 accordingly. Current match is shown only if the return value is non-nil.
13392 The function must neither move point nor alter narrowing."
13393 (interactive "sRegexp: \nP")
13394 (when (equal regexp "")
13395 (user-error "Regexp cannot be empty"))
13396 (unless keep-previous
13397 (org-remove-occur-highlights nil nil t))
13398 (push (cons regexp callback) org-occur-parameters)
13399 (let ((cnt 0))
13400 (save-excursion
13401 (goto-char (point-min))
13402 (when (or (not keep-previous) ; do not want to keep
13403 (not org-occur-highlights)) ; no previous matches
13404 ;; hide everything
13405 (org-overview))
13406 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13407 (isearch-no-upper-case-p regexp t)
13408 org-occur-case-fold-search)))
13409 (while (re-search-forward regexp nil t)
13410 (when (or (not callback)
13411 (save-match-data (funcall callback)))
13412 (setq cnt (1+ cnt))
13413 (when org-highlight-sparse-tree-matches
13414 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13415 (org-show-context 'occur-tree)))))
13416 (when org-remove-highlights-with-change
13417 (add-hook 'before-change-functions 'org-remove-occur-highlights
13418 nil 'local))
13419 (unless org-sparse-tree-open-archived-trees
13420 (org-hide-archived-subtrees (point-min) (point-max)))
13421 (run-hooks 'org-occur-hook)
13422 (when (called-interactively-p 'interactive)
13423 (message "%d match(es) for regexp %s" cnt regexp))
13424 cnt))
13426 (defun org-occur-next-match (&optional n _reset)
13427 "Function for `next-error-function' to find sparse tree matches.
13428 N is the number of matches to move, when negative move backwards.
13429 This function always goes back to the starting point when no
13430 match is found."
13431 (let* ((limit (if (< n 0) (point-min) (point-max)))
13432 (search-func (if (< n 0)
13433 'previous-single-char-property-change
13434 'next-single-char-property-change))
13435 (n (abs n))
13436 (pos (point))
13438 (catch 'exit
13439 (while (setq p1 (funcall search-func (point) 'org-type))
13440 (when (equal p1 limit)
13441 (goto-char pos)
13442 (user-error "No more matches"))
13443 (when (equal (get-char-property p1 'org-type) 'org-occur)
13444 (setq n (1- n))
13445 (when (= n 0)
13446 (goto-char p1)
13447 (throw 'exit (point))))
13448 (goto-char p1))
13449 (goto-char p1)
13450 (user-error "No more matches"))))
13452 (defun org-highlight-new-match (beg end)
13453 "Highlight from BEG to END and mark the highlight is an occur headline."
13454 (let ((ov (make-overlay beg end)))
13455 (overlay-put ov 'face 'secondary-selection)
13456 (overlay-put ov 'org-type 'org-occur)
13457 (push ov org-occur-highlights)))
13459 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13460 "Remove the occur highlights from the buffer.
13461 BEG and END are ignored. If NOREMOVE is nil, remove this function
13462 from the `before-change-functions' in the current buffer."
13463 (interactive)
13464 (unless org-inhibit-highlight-removal
13465 (mapc #'delete-overlay org-occur-highlights)
13466 (setq org-occur-highlights nil)
13467 (setq org-occur-parameters nil)
13468 (unless noremove
13469 (remove-hook 'before-change-functions
13470 'org-remove-occur-highlights 'local))))
13472 ;;;; Priorities
13474 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13475 "Regular expression matching the priority indicator.")
13477 (defvar org-remove-priority-next-time nil)
13479 (defun org-priority-up ()
13480 "Increase the priority of the current item."
13481 (interactive)
13482 (org-priority 'up))
13484 (defun org-priority-down ()
13485 "Decrease the priority of the current item."
13486 (interactive)
13487 (org-priority 'down))
13489 (defun org-priority (&optional action _show)
13490 "Change the priority of an item.
13491 ACTION can be `set', `up', `down', or a character."
13492 (interactive "P")
13493 (if (equal action '(4))
13494 (org-show-priority)
13495 (unless org-enable-priority-commands
13496 (user-error "Priority commands are disabled"))
13497 (setq action (or action 'set))
13498 (let (current new news have remove)
13499 (save-excursion
13500 (org-back-to-heading t)
13501 (when (looking-at org-priority-regexp)
13502 (setq current (string-to-char (match-string 2))
13503 have t))
13504 (cond
13505 ((eq action 'remove)
13506 (setq remove t new ?\ ))
13507 ((or (eq action 'set)
13508 (integerp action))
13509 (if (not (eq action 'set))
13510 (setq new action)
13511 (message "Priority %c-%c, SPC to remove: "
13512 org-highest-priority org-lowest-priority)
13513 (save-match-data
13514 (setq new (read-char-exclusive))))
13515 (when (and (= (upcase org-highest-priority) org-highest-priority)
13516 (= (upcase org-lowest-priority) org-lowest-priority))
13517 (setq new (upcase new)))
13518 (cond ((equal new ?\ ) (setq remove t))
13519 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13520 (user-error "Priority must be between `%c' and `%c'"
13521 org-highest-priority org-lowest-priority))))
13522 ((eq action 'up)
13523 (setq new (if have
13524 (1- current) ; normal cycling
13525 ;; last priority was empty
13526 (if (eq last-command this-command)
13527 org-lowest-priority ; wrap around empty to lowest
13528 ;; default
13529 (if org-priority-start-cycle-with-default
13530 org-default-priority
13531 (1- org-default-priority))))))
13532 ((eq action 'down)
13533 (setq new (if have
13534 (1+ current) ; normal cycling
13535 ;; last priority was empty
13536 (if (eq last-command this-command)
13537 org-highest-priority ; wrap around empty to highest
13538 ;; default
13539 (if org-priority-start-cycle-with-default
13540 org-default-priority
13541 (1+ org-default-priority))))))
13542 (t (user-error "Invalid action")))
13543 (when (or (< (upcase new) org-highest-priority)
13544 (> (upcase new) org-lowest-priority))
13545 (if (and (memq action '(up down))
13546 (not have) (not (eq last-command this-command)))
13547 ;; `new' is from default priority
13548 (error
13549 "The default can not be set, see `org-default-priority' why")
13550 ;; normal cycling: `new' is beyond highest/lowest priority
13551 ;; and is wrapped around to the empty priority
13552 (setq remove t)))
13553 (setq news (format "%c" new))
13554 (if have
13555 (if remove
13556 (replace-match "" t t nil 1)
13557 (replace-match news t t nil 2))
13558 (if remove
13559 (user-error "No priority cookie found in line")
13560 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13561 (if (match-end 2)
13562 (progn
13563 (goto-char (match-end 2))
13564 (insert " [#" news "]"))
13565 (goto-char (match-beginning 3))
13566 (insert "[#" news "] "))))
13567 (org-align-tags))
13568 (if remove
13569 (message "Priority removed")
13570 (message "Priority of current item set to %s" news)))))
13572 (defun org-show-priority ()
13573 "Show the priority of the current item.
13574 This priority is composed of the main priority given with the [#A] cookies,
13575 and by additional input from the age of a schedules or deadline entry."
13576 (interactive)
13577 (let ((pri (if (eq major-mode 'org-agenda-mode)
13578 (org-get-at-bol 'priority)
13579 (save-excursion
13580 (save-match-data
13581 (beginning-of-line)
13582 (and (looking-at org-heading-regexp)
13583 (org-get-priority (match-string 0))))))))
13584 (message "Priority is %d" (if pri pri -1000))))
13586 (defun org-get-priority (s)
13587 "Find priority cookie and return priority."
13588 (save-match-data
13589 (if (functionp org-get-priority-function)
13590 (funcall org-get-priority-function)
13591 (if (not (string-match org-priority-regexp s))
13592 (* 1000 (- org-lowest-priority org-default-priority))
13593 (* 1000 (- org-lowest-priority
13594 (string-to-char (match-string 2 s))))))))
13596 ;;;; Tags
13598 (defvar org-agenda-archives-mode)
13599 (defvar org-map-continue-from nil
13600 "Position from where mapping should continue.
13601 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13603 (defvar org-scanner-tags nil
13604 "The current tag list while the tags scanner is running.")
13606 (defvar org-trust-scanner-tags nil
13607 "Should `org-get-tags' use the tags for the scanner.
13608 This is for internal dynamical scoping only.
13609 When this is non-nil, the function `org-get-tags' will return the value
13610 of `org-scanner-tags' instead of building the list by itself. This
13611 can lead to large speed-ups when the tags scanner is used in a file with
13612 many entries, and when the list of tags is retrieved, for example to
13613 obtain a list of properties. Building the tags list for each entry in such
13614 a file becomes an N^2 operation - but with this variable set, it scales
13615 as N.")
13617 (defvar org--matcher-tags-todo-only nil)
13619 (defun org-scan-tags (action matcher todo-only &optional start-level)
13620 "Scan headline tags with inheritance and produce output ACTION.
13622 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13623 or `agenda' to produce an entry list for an agenda view. It can also be
13624 a Lisp form or a function that should be called at each matched headline, in
13625 this case the return value is a list of all return values from these calls.
13627 MATCHER is a function accepting three arguments, returning
13628 a non-nil value whenever a given set of tags qualifies a headline
13629 for inclusion. See `org-make-tags-matcher' for more information.
13630 As a special case, it can also be set to t (respectively nil) in
13631 order to match all (respectively none) headline.
13633 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13634 included in the output.
13636 START-LEVEL can be a string with asterisks, reducing the scope to
13637 headlines matching this string."
13638 (require 'org-agenda)
13639 (let* ((re (concat "^"
13640 (if start-level
13641 ;; Get the correct level to match
13642 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13643 org-outline-regexp)
13644 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13645 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13646 (props (list 'face 'default
13647 'done-face 'org-agenda-done
13648 'undone-face 'default
13649 'mouse-face 'highlight
13650 'org-not-done-regexp org-not-done-regexp
13651 'org-todo-regexp org-todo-regexp
13652 'org-complex-heading-regexp org-complex-heading-regexp
13653 'help-echo
13654 (format "mouse-2 or RET jump to Org file %S"
13655 (abbreviate-file-name
13656 (or (buffer-file-name (buffer-base-buffer))
13657 (buffer-name (buffer-base-buffer)))))))
13658 (org-map-continue-from nil)
13659 lspos tags tags-list
13660 (tags-alist (list (cons 0 org-file-tags)))
13661 (llast 0) rtn rtn1 level category i txt
13662 todo marker entry priority
13663 ts-date ts-date-type ts-date-pair)
13664 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13665 (setq action (list 'lambda nil action)))
13666 (save-excursion
13667 (goto-char (point-min))
13668 (when (eq action 'sparse-tree)
13669 (org-overview)
13670 (org-remove-occur-highlights))
13671 (while (let (case-fold-search)
13672 (re-search-forward re nil t))
13673 (setq org-map-continue-from nil)
13674 (catch :skip
13675 ;; Ignore closing parts of inline tasks.
13676 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13677 (throw :skip t))
13678 (setq todo
13679 ;; TODO: is the 1-2 difference a bug?
13680 (when (match-end 1) (match-string-no-properties 2))
13681 tags (when (match-end 4) (match-string-no-properties 4)))
13682 (goto-char (setq lspos (match-beginning 0)))
13683 (setq level (org-reduced-level (org-outline-level))
13684 category (org-get-category))
13685 (when (eq action 'agenda)
13686 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13687 ts-date (car ts-date-pair)
13688 ts-date-type (cdr ts-date-pair)))
13689 (setq i llast llast level)
13690 ;; remove tag lists from same and sublevels
13691 (while (>= i level)
13692 (when (setq entry (assoc i tags-alist))
13693 (setq tags-alist (delete entry tags-alist)))
13694 (setq i (1- i)))
13695 ;; add the next tags
13696 (when tags
13697 (setq tags (org-split-string tags ":")
13698 tags-alist
13699 (cons (cons level tags) tags-alist)))
13700 ;; compile tags for current headline
13701 (setq tags-list
13702 (if org-use-tag-inheritance
13703 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13704 tags)
13705 org-scanner-tags tags-list)
13706 (when org-use-tag-inheritance
13707 (setcdr (car tags-alist)
13708 (mapcar (lambda (x)
13709 (setq x (copy-sequence x))
13710 (org-add-prop-inherited x))
13711 (cdar tags-alist))))
13712 (when (and tags org-use-tag-inheritance
13713 (or (not (eq t org-use-tag-inheritance))
13714 org-tags-exclude-from-inheritance))
13715 ;; Selective inheritance, remove uninherited ones.
13716 (setcdr (car tags-alist)
13717 (org-remove-uninherited-tags (cdar tags-alist))))
13718 (when (and
13720 ;; eval matcher only when the todo condition is OK
13721 (and (or (not todo-only) (member todo org-todo-keywords-1))
13722 (if (functionp matcher)
13723 (let ((case-fold-search t) (org-trust-scanner-tags t))
13724 (funcall matcher todo tags-list level))
13725 matcher))
13727 ;; Call the skipper, but return t if it does not
13728 ;; skip, so that the `and' form continues evaluating.
13729 (progn
13730 (unless (eq action 'sparse-tree) (org-agenda-skip))
13733 ;; Check if timestamps are deselecting this entry
13734 (or (not todo-only)
13735 (and (member todo org-todo-keywords-1)
13736 (or (not org-agenda-tags-todo-honor-ignore-options)
13737 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13739 ;; select this headline
13740 (cond
13741 ((eq action 'sparse-tree)
13742 (and org-highlight-sparse-tree-matches
13743 (org-get-heading) (match-end 0)
13744 (org-highlight-new-match
13745 (match-beginning 1) (match-end 1)))
13746 (org-show-context 'tags-tree))
13747 ((eq action 'agenda)
13748 (setq txt (org-agenda-format-item
13750 (concat
13751 (if (eq org-tags-match-list-sublevels 'indented)
13752 (make-string (1- level) ?.) "")
13753 (org-get-heading))
13754 (make-string level ?\s)
13755 category
13756 tags-list)
13757 priority (org-get-priority txt))
13758 (goto-char lspos)
13759 (setq marker (org-agenda-new-marker))
13760 (org-add-props txt props
13761 'org-marker marker 'org-hd-marker marker 'org-category category
13762 'todo-state todo
13763 'ts-date ts-date
13764 'priority priority
13765 'type (concat "tagsmatch" ts-date-type))
13766 (push txt rtn))
13767 ((functionp action)
13768 (setq org-map-continue-from nil)
13769 (save-excursion
13770 (setq rtn1 (funcall action))
13771 (push rtn1 rtn)))
13772 (t (user-error "Invalid action")))
13774 ;; if we are to skip sublevels, jump to end of subtree
13775 (unless org-tags-match-list-sublevels
13776 (org-end-of-subtree t)
13777 (backward-char 1))))
13778 ;; Get the correct position from where to continue
13779 (if org-map-continue-from
13780 (goto-char org-map-continue-from)
13781 (and (= (point) lspos) (end-of-line 1)))))
13782 (when (and (eq action 'sparse-tree)
13783 (not org-sparse-tree-open-archived-trees))
13784 (org-hide-archived-subtrees (point-min) (point-max)))
13785 (nreverse rtn)))
13787 (defun org-remove-uninherited-tags (tags)
13788 "Remove all tags that are not inherited from the list TAGS."
13789 (cond
13790 ((eq org-use-tag-inheritance t)
13791 (if org-tags-exclude-from-inheritance
13792 (org-delete-all org-tags-exclude-from-inheritance tags)
13793 tags))
13794 ((not org-use-tag-inheritance) nil)
13795 ((stringp org-use-tag-inheritance)
13796 (delq nil (mapcar
13797 (lambda (x)
13798 (if (and (string-match org-use-tag-inheritance x)
13799 (not (member x org-tags-exclude-from-inheritance)))
13800 x nil))
13801 tags)))
13802 ((listp org-use-tag-inheritance)
13803 (delq nil (mapcar
13804 (lambda (x)
13805 (if (member x org-use-tag-inheritance) x nil))
13806 tags)))))
13808 (defun org-match-sparse-tree (&optional todo-only match)
13809 "Create a sparse tree according to tags string MATCH.
13811 MATCH is a string with match syntax. It can contain a selection
13812 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13813 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13814 those. See the manual for details.
13816 If optional argument TODO-ONLY is non-nil, only select lines that
13817 are also TODO tasks."
13818 (interactive "P")
13819 (org-agenda-prepare-buffers (list (current-buffer)))
13820 (let ((org--matcher-tags-todo-only todo-only))
13821 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13822 org--matcher-tags-todo-only)))
13824 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13826 (defvar org-cached-props nil)
13827 (defun org-cached-entry-get (pom property)
13828 (if (or (eq t org-use-property-inheritance)
13829 (and (stringp org-use-property-inheritance)
13830 (let ((case-fold-search t))
13831 (string-match-p org-use-property-inheritance property)))
13832 (and (listp org-use-property-inheritance)
13833 (member-ignore-case property org-use-property-inheritance)))
13834 ;; Caching is not possible, check it directly.
13835 (org-entry-get pom property 'inherit)
13836 ;; Get all properties, so we can do complicated checks easily.
13837 (cdr (assoc-string property
13838 (or org-cached-props
13839 (setq org-cached-props (org-entry-properties pom)))
13840 t))))
13842 (defun org-global-tags-completion-table (&optional files)
13843 "Return the list of all tags in all agenda buffer/files.
13844 Optional FILES argument is a list of files which can be used
13845 instead of the agenda files."
13846 (save-excursion
13847 (org-uniquify
13848 (delq nil
13849 (apply #'append
13850 (mapcar
13851 (lambda (file)
13852 (set-buffer (find-file-noselect file))
13853 (org--tag-add-to-alist
13854 (org-get-buffer-tags)
13855 (mapcar (lambda (x)
13856 (and (stringp (car-safe x))
13857 (list (car-safe x))))
13858 org-current-tag-alist)))
13859 (if (car-safe files) files
13860 (org-agenda-files))))))))
13862 (defun org-make-tags-matcher (match)
13863 "Create the TAGS/TODO matcher form for the selection string MATCH.
13865 Returns a cons of the selection string MATCH and a function
13866 implementing the matcher.
13868 The matcher is to be called at an Org entry, with point on the
13869 headline, and returns non-nil if the entry matches the selection
13870 string MATCH. It must be called with three arguments: the TODO
13871 keyword at the entry (or nil if none), the list of all tags at
13872 the entry including inherited ones and the reduced level of the
13873 headline. Additionally, the category of the entry, if any, must
13874 be specified as the text property `org-category' on the headline.
13876 This function sets the variable `org--matcher-tags-todo-only' to
13877 a non-nil value if the matcher restricts matching to TODO
13878 entries, otherwise it is not touched.
13880 See also `org-scan-tags'."
13881 (unless match
13882 ;; Get a new match request, with completion against the global
13883 ;; tags table and the local tags in current buffer.
13884 (let ((org-last-tags-completion-table
13885 (org--tag-add-to-alist
13886 (org-get-buffer-tags)
13887 (org-global-tags-completion-table))))
13888 (setq match
13889 (completing-read
13890 "Match: "
13891 'org-tags-completion-function nil nil nil 'org-tags-history))))
13893 (let ((match0 match)
13894 (re (concat
13895 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13896 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13897 "\\([<>=]\\{1,2\\}\\)"
13898 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13899 "\\|" org-tag-re "\\)"))
13900 (start 0)
13901 tagsmatch todomatch tagsmatcher todomatcher)
13903 ;; Expand group tags.
13904 (setq match (org-tags-expand match))
13906 ;; Check if there is a TODO part of this match, which would be the
13907 ;; part after a "/". To make sure that this slash is not part of
13908 ;; a property value to be matched against, we also check that
13909 ;; there is no / after that slash. First, find the last slash.
13910 (let ((s 0))
13911 (while (string-match "/+" match s)
13912 (setq start (match-beginning 0))
13913 (setq s (match-end 0))))
13914 (if (and (string-match "/+" match start)
13915 (not (string-match-p "\"" match start)))
13916 ;; Match contains also a TODO-matching request.
13917 (progn
13918 (setq tagsmatch (substring match 0 (match-beginning 0)))
13919 (setq todomatch (substring match (match-end 0)))
13920 (when (string-prefix-p "!" todomatch)
13921 (setq org--matcher-tags-todo-only t)
13922 (setq todomatch (substring todomatch 1)))
13923 (when (string-match "\\`\\s-*\\'" todomatch)
13924 (setq todomatch nil)))
13925 ;; Only matching tags.
13926 (setq tagsmatch match)
13927 (setq todomatch nil))
13929 ;; Make the tags matcher.
13930 (when (org-string-nw-p tagsmatch)
13931 (let ((orlist nil)
13932 (orterms (org-split-string tagsmatch "|"))
13933 term)
13934 (while (setq term (pop orterms))
13935 (while (and (equal (substring term -1) "\\") orterms)
13936 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13937 (while (string-match re term)
13938 (let* ((rest (substring term (match-end 0)))
13939 (minus (and (match-end 1)
13940 (equal (match-string 1 term) "-")))
13941 (tag (save-match-data
13942 (replace-regexp-in-string
13943 "\\\\-" "-" (match-string 2 term))))
13944 (regexp (eq (string-to-char tag) ?{))
13945 (levelp (match-end 4))
13946 (propp (match-end 5))
13948 (cond
13949 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13950 (levelp
13951 `(,(org-op-to-function (match-string 3 term))
13952 level
13953 ,(string-to-number (match-string 4 term))))
13954 (propp
13955 (let* ((gv (pcase (upcase (match-string 5 term))
13956 ("CATEGORY"
13957 '(get-text-property (point) 'org-category))
13958 ("TODO" 'todo)
13959 (p `(org-cached-entry-get nil ,p))))
13960 (pv (match-string 7 term))
13961 (regexp (eq (string-to-char pv) ?{))
13962 (strp (eq (string-to-char pv) ?\"))
13963 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13964 (po (org-op-to-function (match-string 6 term)
13965 (if timep 'time strp))))
13966 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13967 (when timep (setq pv (org-matcher-time pv)))
13968 (cond ((and regexp (eq po '/=))
13969 `(not (string-match ,pv (or ,gv ""))))
13970 (regexp `(string-match ,pv (or ,gv "")))
13971 (strp `(,po (or ,gv "") ,pv))
13973 `(,po
13974 (string-to-number (or ,gv ""))
13975 ,(string-to-number pv))))))
13976 (t `(member ,tag tags-list)))))
13977 (push (if minus `(not ,mm) mm) tagsmatcher)
13978 (setq term rest)))
13979 (push `(and ,@tagsmatcher) orlist)
13980 (setq tagsmatcher nil))
13981 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13983 ;; Make the TODO matcher.
13984 (when (org-string-nw-p todomatch)
13985 (let ((orlist nil))
13986 (dolist (term (org-split-string todomatch "|"))
13987 (while (string-match re term)
13988 (let* ((minus (and (match-end 1)
13989 (equal (match-string 1 term) "-")))
13990 (kwd (match-string 2 term))
13991 (regexp (eq (string-to-char kwd) ?{))
13992 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13993 `(equal todo ,kwd))))
13994 (push (if minus `(not ,mm) mm) todomatcher))
13995 (setq term (substring term (match-end 0))))
13996 (push (if (> (length todomatcher) 1)
13997 (cons 'and todomatcher)
13998 (car todomatcher))
13999 orlist)
14000 (setq todomatcher nil))
14001 (setq todomatcher (cons 'or orlist))))
14003 ;; Return the string and function of the matcher. If no
14004 ;; tags-specific or todo-specific matcher exists, match
14005 ;; everything.
14006 (let ((matcher (if (and tagsmatcher todomatcher)
14007 `(and ,tagsmatcher ,todomatcher)
14008 (or tagsmatcher todomatcher t))))
14009 (when org--matcher-tags-todo-only
14010 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14011 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14013 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14014 "Expand group tags in MATCH.
14016 This replaces every group tag in MATCH with a regexp tag search.
14017 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14018 will be replaced like this:
14020 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14021 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14022 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14024 Replacing by a regexp preserves the structure of the match.
14025 E.g., this expansion
14027 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14029 will match anything tagged with \"Lab\" and \"Home\", or tagged
14030 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14032 A group tag in MATCH can contain regular expressions of its own.
14033 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14034 will be replaced like this:
14036 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14038 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14039 assumed to be a single group tag, and the function will return
14040 the list of tags in this group.
14042 When DOWNCASE is non-nil, expand downcased TAGS."
14043 (if org-group-tags
14044 (let* ((case-fold-search t)
14045 (stable org-mode-syntax-table)
14046 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14047 (taggroups (if downcased
14048 (mapcar (lambda (tg) (mapcar #'downcase tg))
14049 taggroups)
14050 taggroups))
14051 (taggroups-keys (mapcar #'car taggroups))
14052 (return-match (if downcased (downcase match) match))
14053 (count 0)
14054 (work-already-expanded tags-already-expanded)
14055 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14056 ;; @ and _ are allowed as word-components in tags.
14057 (modify-syntax-entry ?@ "w" stable)
14058 (modify-syntax-entry ?_ "w" stable)
14059 ;; Temporarily replace regexp-expressions in the match-expression.
14060 (while (string-match "{.+?}" return-match)
14061 (cl-incf count)
14062 (push (match-string 0 return-match) regexps-in-match)
14063 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14064 (while (and taggroups-keys
14065 (with-syntax-table stable
14066 (string-match
14067 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14068 (regexp-opt taggroups-keys) "\\>\\)")
14069 return-match)))
14070 (let* ((dir (match-string 1 return-match))
14071 (tag (match-string 2 return-match))
14072 (tag (if downcased (downcase tag) tag)))
14073 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14074 (member tag tags-already-expanded))
14075 (setq tags-in-group (assoc tag taggroups))
14076 (push tag work-already-expanded)
14077 ;; Recursively expand each tag in the group, if the tag hasn't
14078 ;; already been expanded. Restore the match-data after all recursive calls.
14079 (save-match-data
14080 (let (tags-expanded)
14081 (dolist (x (cdr tags-in-group))
14082 (if (and (member x taggroups-keys)
14083 (not (member x work-already-expanded)))
14084 (setq tags-expanded
14085 (delete-dups
14086 (append
14087 (org-tags-expand x t downcased
14088 work-already-expanded)
14089 tags-expanded)))
14090 (setq tags-expanded
14091 (append (list x) tags-expanded)))
14092 (setq work-already-expanded
14093 (delete-dups
14094 (append tags-expanded
14095 work-already-expanded))))
14096 (setq tags-in-group
14097 (delete-dups (cons (car tags-in-group)
14098 tags-expanded)))))
14099 ;; Filter tag-regexps from tags.
14100 (setq regexp-in-group-escaped
14101 (delq nil (mapcar (lambda (x)
14102 (if (stringp x)
14103 (and (equal "{" (substring x 0 1))
14104 (equal "}" (substring x -1))
14107 tags-in-group))
14108 regexp-in-group
14109 (mapcar (lambda (x)
14110 (substring x 1 -1))
14111 regexp-in-group-escaped)
14112 tags-in-group
14113 (delq nil (mapcar (lambda (x)
14114 (if (stringp x)
14115 (and (not (equal "{" (substring x 0 1)))
14116 (not (equal "}" (substring x -1)))
14119 tags-in-group)))
14120 ;; If single-as-list, do no more in the while-loop.
14121 (if (not single-as-list)
14122 (progn
14123 (when regexp-in-group
14124 (setq regexp-in-group
14125 (concat "\\|"
14126 (mapconcat 'identity regexp-in-group
14127 "\\|"))))
14128 (setq tags-in-group
14129 (concat dir
14130 "{\\<"
14131 (regexp-opt tags-in-group)
14132 "\\>"
14133 regexp-in-group
14134 "}"))
14135 (when (stringp tags-in-group)
14136 (org-add-props tags-in-group '(grouptag t)))
14137 (setq return-match
14138 (replace-match tags-in-group t t return-match)))
14139 (setq tags-in-group
14140 (append regexp-in-group-escaped tags-in-group))))
14141 (setq taggroups-keys (delete tag taggroups-keys))))
14142 ;; Add the regular expressions back into the match-expression again.
14143 (while regexps-in-match
14144 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14145 (pop regexps-in-match)
14146 return-match t t))
14147 (cl-decf count))
14148 (if single-as-list
14149 (if tags-in-group tags-in-group (list return-match))
14150 return-match))
14151 (if single-as-list
14152 (list (if downcased (downcase match) match))
14153 match)))
14155 (defun org-op-to-function (op &optional stringp)
14156 "Turn an operator into the appropriate function."
14157 (setq op
14158 (cond
14159 ((equal op "<" ) '(< org-string< org-time<))
14160 ((equal op ">" ) '(> org-string> org-time>))
14161 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14162 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14163 ((member op '("=" "==")) '(= string= org-time=))
14164 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14165 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14167 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14168 (defvar org-tags-overlay (make-overlay 1 1))
14169 (delete-overlay org-tags-overlay)
14171 (defun org-add-prop-inherited (s)
14172 (add-text-properties 0 (length s) '(inherited t) s)
14175 (defun org-toggle-tag (tag &optional onoff)
14176 "Toggle the tag TAG for the current line.
14177 If ONOFF is `on' or `off', don't toggle but set to this state."
14178 (save-excursion
14179 (org-back-to-heading t)
14180 (let ((current
14181 ;; Reverse the tags list so any new tag is appended to the
14182 ;; current list of tags.
14183 (nreverse (org-get-tags)))
14184 res)
14185 (pcase onoff
14186 (`off (setq current (delete tag current)))
14187 ((or `on (guard (not (member tag current))))
14188 (setq res t)
14189 (cl-pushnew tag current :test #'equal))
14190 (_ (setq current (delete tag current))))
14191 (org-set-tags (nreverse current))
14192 res)))
14194 (defun org--align-tags-here (to-col)
14195 "Align tags on the current headline to TO-COL.
14196 Assume point is on a headline."
14197 (when (and (org-match-line org-tag-line-re)
14198 (< (point) (match-beginning 1)))
14199 (let ((pos (point))
14200 (shift (if (>= to-col 0) to-col
14201 (- (abs to-col) (string-width (match-string 1))))))
14202 ;; Delete all blanks before tags.
14203 (goto-char (match-beginning 1))
14204 (skip-chars-backward " \t")
14205 (delete-region (point) (match-beginning 1))
14206 ;; Insert new blanks.
14207 (insert (make-string (max 1 (- shift (current-column))) ?\s))
14208 ;; Preserve initial position, if possible. In any case, stop
14209 ;; before tags.
14210 (when (< pos (point)) (goto-char pos)))))
14212 (defun org-set-tags-command (&optional arg)
14213 "Set the tags for the current visible entry.
14215 When called with `\\[universal-argument]' prefix argument ARG, \
14216 realign all tags
14217 in the current buffer. If a region is active, set tags for
14218 all headlines in the region.
14220 This function is for interactive use only;
14221 in Lisp code use `org-set-tags' instead."
14222 (interactive "P")
14223 (cond
14224 (arg (org-align-tags t))
14225 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14226 ;; Disable `org-loop-over-headlines-in-active-region' for
14227 ;; successive calls.
14228 (let (org-loop-over-headlines-in-active-region)
14229 (org-map-entries
14230 #'org-set-tags-command
14232 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14233 'region-start-level
14234 'region)
14235 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14237 (org-back-to-heading)
14238 (let* ((all-tags (org-get-tags))
14239 (table (setq org-last-tags-completion-table
14240 (org--tag-add-to-alist
14241 (and org-complete-tags-always-offer-all-agenda-tags
14242 (org-global-tags-completion-table
14243 (org-agenda-files)))
14244 (or org-current-tag-alist (org-get-buffer-tags)))))
14245 (current-tags
14246 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14247 all-tags))
14248 (inherited-tags
14249 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14250 all-tags))
14251 (tags
14252 (replace-regexp-in-string
14253 ;; Ignore all forbidden characters in tags.
14254 "[^[:alnum:]_@#%]+" ":"
14255 (if (or (eq t org-use-fast-tag-selection)
14256 (and org-use-fast-tag-selection
14257 (delq nil (mapcar #'cdr table))))
14258 (org-fast-tag-selection
14259 current-tags
14260 inherited-tags
14261 table
14262 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14263 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14264 (org-trim (completing-read
14265 "Tags: "
14266 #'org-tags-completion-function
14267 nil nil (org-make-tag-string current-tags)
14268 'org-tags-history)))))))
14269 (org-set-tags tags)))))
14271 (defun org-align-tags (&optional all)
14272 "Align tags in current entry.
14273 When optional argument ALL is non-nil, align all tags in the
14274 visible part of the buffer."
14275 (save-excursion
14276 (if all (goto-char (point-min)) (org-back-to-heading t))
14277 (catch :single
14278 (while (re-search-forward org-tag-line-re nil t)
14279 (let* ((offset (if (bound-and-true-p org-indent-mode)
14280 (* (1- org-indent-indentation-per-level)
14281 (1- (org-current-level)))
14283 (tags-column (+ org-tags-column
14284 (if (> org-tags-column 0) (- offset) offset))))
14285 (beginning-of-line)
14286 (org--align-tags-here tags-column)
14287 (if all (forward-line) (throw :single nil)))))))
14289 (defun org-set-tags (tags)
14290 "Set the tags of the current entry to TAGS, replacing current tags.
14292 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14293 If TAGS is nil or the empty string, all tags are removed.
14295 This function assumes point is on a headline."
14296 (let ((tags (pcase tags
14297 ((pred listp) tags)
14298 ((pred stringp) (split-string (org-trim tags) ":" t))
14299 (_ (error "Invalid tag specification: %S" tags))))
14300 (change-flag nil))
14301 (when (functionp org-tags-sort-function)
14302 (setq tags (sort tags org-tags-sort-function)))
14303 (org-with-wide-buffer
14304 (unless (equal tags (org-get-tags nil t))
14305 (setq change-flag t)
14306 ;; Delete previous tags and any trailing white space.
14307 (goto-char (if (looking-at org-tag-line-re) (match-beginning 1)
14308 (line-end-position)))
14309 (skip-chars-backward " \t")
14310 (delete-region (point) (line-end-position))
14311 (when tags
14312 (save-excursion (insert " " (org-make-tag-string tags)))
14313 ;; When text is being inserted on an invisible region
14314 ;; boundary, it can be inadvertently sucked into
14315 ;; invisibility.
14316 (unless (org-invisible-p (line-beginning-position))
14317 (org-flag-region (point) (line-end-position) nil 'outline))))
14318 ;; Align tags, if any. Fix tags column if `org-indent-mode' is
14319 ;; on.
14320 (when tags (org-align-tags))
14321 (when change-flag (run-hooks 'org-after-tags-change-hook)))))
14323 (defun org-change-tag-in-region (beg end tag off)
14324 "Add or remove TAG for each entry in the region.
14325 This works in the agenda, and also in an Org buffer."
14326 (interactive
14327 (list (region-beginning) (region-end)
14328 (let ((org-last-tags-completion-table
14329 (if (derived-mode-p 'org-mode)
14330 (org--tag-add-to-alist
14331 (org-get-buffer-tags)
14332 (org-global-tags-completion-table))
14333 (org-global-tags-completion-table))))
14334 (completing-read
14335 "Tag: " 'org-tags-completion-function nil nil nil
14336 'org-tags-history))
14337 (progn
14338 (message "[s]et or [r]emove? ")
14339 (equal (read-char-exclusive) ?r))))
14340 (when (fboundp 'deactivate-mark) (deactivate-mark))
14341 (let ((agendap (equal major-mode 'org-agenda-mode))
14342 l1 l2 m buf pos newhead (cnt 0))
14343 (goto-char end)
14344 (setq l2 (1- (org-current-line)))
14345 (goto-char beg)
14346 (setq l1 (org-current-line))
14347 (cl-loop for l from l1 to l2 do
14348 (org-goto-line l)
14349 (setq m (get-text-property (point) 'org-hd-marker))
14350 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14351 (and agendap m))
14352 (setq buf (if agendap (marker-buffer m) (current-buffer))
14353 pos (if agendap m (point)))
14354 (with-current-buffer buf
14355 (save-excursion
14356 (save-restriction
14357 (goto-char pos)
14358 (setq cnt (1+ cnt))
14359 (org-toggle-tag tag (if off 'off 'on))
14360 (setq newhead (org-get-heading)))))
14361 (and agendap (org-agenda-change-all-lines newhead m))))
14362 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14364 (defun org-tags-completion-function (string _predicate &optional flag)
14365 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14366 (confirm (lambda (x) (stringp (car x)))))
14367 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14368 (setq s1 (match-string 1 string)
14369 s2 (match-string 2 string))
14370 (setq s1 "" s2 string))
14371 (cond
14372 ((eq flag nil)
14373 ;; try completion
14374 (setq rtn (try-completion s2 ctable confirm))
14375 (when (stringp rtn)
14376 (setq rtn
14377 (concat s1 s2 (substring rtn (length s2))
14378 (if (and org-add-colon-after-tag-completion
14379 (assoc rtn ctable))
14380 ":" ""))))
14381 rtn)
14382 ((eq flag t)
14383 ;; all-completions
14384 (all-completions s2 ctable confirm))
14385 ((eq flag 'lambda)
14386 ;; exact match?
14387 (assoc s2 ctable)))))
14389 (defun org-fast-tag-insert (kwd tags face &optional end)
14390 "Insert KDW, and the TAGS, the latter with face FACE.
14391 Also insert END."
14392 (insert (format "%-12s" (concat kwd ":"))
14393 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14394 (or end "")))
14396 (defun org-fast-tag-show-exit (flag)
14397 (save-excursion
14398 (org-goto-line 3)
14399 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14400 (replace-match ""))
14401 (when flag
14402 (end-of-line 1)
14403 (org-move-to-column (- (window-width) 19) t)
14404 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14406 (defun org-set-current-tags-overlay (current prefix)
14407 "Add an overlay to CURRENT tag with PREFIX."
14408 (let ((s (org-make-tag-string current)))
14409 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14410 (org-overlay-display org-tags-overlay (concat prefix s))))
14412 (defvar org-last-tag-selection-key nil)
14413 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14414 "Fast tag selection with single keys.
14415 CURRENT is the current list of tags in the headline, INHERITED is the
14416 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14417 possibly with grouping information. TODO-TABLE is a similar table with
14418 TODO keywords, should these have keys assigned to them.
14419 If the keys are nil, a-z are automatically assigned.
14420 Returns the new tags string, or nil to not change the current settings."
14421 (let* ((fulltable (append table todo-table))
14422 (maxlen (if (null fulltable) 0
14423 (apply #'max
14424 (mapcar (lambda (x)
14425 (if (stringp (car x)) (string-width (car x))
14427 fulltable))))
14428 (buf (current-buffer))
14429 (expert (eq org-fast-tag-selection-single-key 'expert))
14430 (buffer-tags nil)
14431 (fwidth (+ maxlen 3 1 3))
14432 (ncol (/ (- (window-width) 4) fwidth))
14433 (i-face 'org-done)
14434 (c-face 'org-todo)
14435 tg cnt e c char c1 c2 ntable tbl rtn
14436 ov-start ov-end ov-prefix
14437 (exit-after-next org-fast-tag-selection-single-key)
14438 (done-keywords org-done-keywords)
14439 groups ingroup intaggroup)
14440 (save-excursion
14441 (beginning-of-line)
14442 (if (looking-at org-tag-line-re)
14443 (setq ov-start (match-beginning 1)
14444 ov-end (match-end 1)
14445 ov-prefix "")
14446 (setq ov-start (1- (point-at-eol))
14447 ov-end (1+ ov-start))
14448 (skip-chars-forward "^\n\r")
14449 (setq ov-prefix
14450 (concat
14451 (buffer-substring (1- (point)) (point))
14452 (if (> (current-column) org-tags-column)
14454 (make-string (- org-tags-column (current-column)) ?\ ))))))
14455 (move-overlay org-tags-overlay ov-start ov-end)
14456 (save-window-excursion
14457 (if expert
14458 (set-buffer (get-buffer-create " *Org tags*"))
14459 (delete-other-windows)
14460 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14461 (org-switch-to-buffer-other-window " *Org tags*"))
14462 (erase-buffer)
14463 (setq-local org-done-keywords done-keywords)
14464 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14465 (org-fast-tag-insert "Current" current c-face "\n\n")
14466 (org-fast-tag-show-exit exit-after-next)
14467 (org-set-current-tags-overlay current ov-prefix)
14468 (setq tbl fulltable char ?a cnt 0)
14469 (while (setq e (pop tbl))
14470 (cond
14471 ((eq (car e) :startgroup)
14472 (push '() groups) (setq ingroup t)
14473 (unless (zerop cnt)
14474 (setq cnt 0)
14475 (insert "\n"))
14476 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14477 ((eq (car e) :endgroup)
14478 (setq ingroup nil cnt 0)
14479 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14480 ((eq (car e) :startgrouptag)
14481 (setq intaggroup t)
14482 (unless (zerop cnt)
14483 (setq cnt 0)
14484 (insert "\n"))
14485 (insert "[ "))
14486 ((eq (car e) :endgrouptag)
14487 (setq intaggroup nil cnt 0)
14488 (insert "]\n"))
14489 ((equal e '(:newline))
14490 (unless (zerop cnt)
14491 (setq cnt 0)
14492 (insert "\n")
14493 (setq e (car tbl))
14494 (while (equal (car tbl) '(:newline))
14495 (insert "\n")
14496 (setq tbl (cdr tbl)))))
14497 ((equal e '(:grouptags)) (insert " : "))
14499 (setq tg (copy-sequence (car e)) c2 nil)
14500 (if (cdr e)
14501 (setq c (cdr e))
14502 ;; automatically assign a character.
14503 (setq c1 (string-to-char
14504 (downcase (substring
14505 tg (if (= (string-to-char tg) ?@) 1 0)))))
14506 (if (or (rassoc c1 ntable) (rassoc c1 table))
14507 (while (or (rassoc char ntable) (rassoc char table))
14508 (setq char (1+ char)))
14509 (setq c2 c1))
14510 (setq c (or c2 char)))
14511 (when ingroup (push tg (car groups)))
14512 (setq tg (org-add-props tg nil 'face
14513 (cond
14514 ((not (assoc tg table))
14515 (org-get-todo-face tg))
14516 ((member tg current) c-face)
14517 ((member tg inherited) i-face))))
14518 (when (equal (caar tbl) :grouptags)
14519 (org-add-props tg nil 'face 'org-tag-group))
14520 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14521 (insert "[" c "] " tg (make-string
14522 (- fwidth 4 (length tg)) ?\ ))
14523 (push (cons tg c) ntable)
14524 (when (= (cl-incf cnt) ncol)
14525 (insert "\n")
14526 (when (or ingroup intaggroup) (insert " "))
14527 (setq cnt 0)))))
14528 (setq ntable (nreverse ntable))
14529 (insert "\n")
14530 (goto-char (point-min))
14531 (unless expert (org-fit-window-to-buffer))
14532 (setq rtn
14533 (catch 'exit
14534 (while t
14535 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14536 (if (not groups) "no " "")
14537 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14538 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14539 (setq org-last-tag-selection-key c)
14540 (cond
14541 ((= c ?\r) (throw 'exit t))
14542 ((= c ?!)
14543 (setq groups (not groups))
14544 (goto-char (point-min))
14545 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14546 ((= c ?\C-c)
14547 (if (not expert)
14548 (org-fast-tag-show-exit
14549 (setq exit-after-next (not exit-after-next)))
14550 (setq expert nil)
14551 (delete-other-windows)
14552 (set-window-buffer (split-window-vertically) " *Org tags*")
14553 (org-switch-to-buffer-other-window " *Org tags*")
14554 (org-fit-window-to-buffer)))
14555 ((or (= c ?\C-g)
14556 (and (= c ?q) (not (rassoc c ntable))))
14557 (delete-overlay org-tags-overlay)
14558 (setq quit-flag t))
14559 ((= c ?\ )
14560 (setq current nil)
14561 (when exit-after-next (setq exit-after-next 'now)))
14562 ((= c ?\t)
14563 (condition-case nil
14564 (setq tg (completing-read
14565 "Tag: "
14566 (or buffer-tags
14567 (with-current-buffer buf
14568 (setq buffer-tags
14569 (org-get-buffer-tags))))))
14570 (quit (setq tg "")))
14571 (when (string-match "\\S-" tg)
14572 (cl-pushnew (list tg) buffer-tags :test #'equal)
14573 (if (member tg current)
14574 (setq current (delete tg current))
14575 (push tg current)))
14576 (when exit-after-next (setq exit-after-next 'now)))
14577 ((setq e (rassoc c todo-table) tg (car e))
14578 (with-current-buffer buf
14579 (save-excursion (org-todo tg)))
14580 (when exit-after-next (setq exit-after-next 'now)))
14581 ((setq e (rassoc c ntable) tg (car e))
14582 (if (member tg current)
14583 (setq current (delete tg current))
14584 (cl-loop for g in groups do
14585 (when (member tg g)
14586 (dolist (x g) (setq current (delete x current)))))
14587 (push tg current))
14588 (when exit-after-next (setq exit-after-next 'now))))
14590 ;; Create a sorted list
14591 (setq current
14592 (sort current
14593 (lambda (a b)
14594 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14595 (when (eq exit-after-next 'now) (throw 'exit t))
14596 (goto-char (point-min))
14597 (beginning-of-line 2)
14598 (delete-region (point) (point-at-eol))
14599 (org-fast-tag-insert "Current" current c-face)
14600 (org-set-current-tags-overlay current ov-prefix)
14601 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14602 (while (re-search-forward tag-re nil t)
14603 (let ((tag (match-string 1)))
14604 (add-text-properties
14605 (match-beginning 1) (match-end 1)
14606 (list 'face
14607 (cond
14608 ((member tag current) c-face)
14609 ((member tag inherited) i-face)
14610 (t (get-text-property (match-beginning 1) '
14611 face))))))))
14612 (goto-char (point-min)))))
14613 (delete-overlay org-tags-overlay)
14614 (if rtn
14615 (mapconcat 'identity current ":")
14616 nil))))
14618 (defun org-make-tag-string (tags)
14619 "Return string associated to TAGS.
14620 TAGS is a list of strings."
14621 (if (null tags) ""
14622 (format ":%s:" (mapconcat #'identity tags ":"))))
14624 (defun org--get-local-tags ()
14625 "Return list of tags for the current headline.
14626 Assume point is at the beginning of the headline."
14627 (and (looking-at org-tag-line-re)
14628 (split-string (match-string-no-properties 2) ":" t)))
14630 (defun org-get-tags (&optional pos local)
14631 "Get the list of tags specified in the current headline.
14633 When argument POS is non-nil, retrieve tags for headline at POS.
14635 Accoring to `org-use-tags-inheritance', tags may be inherited
14636 from parent headlines, and from the whole document, through
14637 `org-file-tags'. However, when optional argument LOCAL is
14638 non-nil, only return tags really specified in the considered
14639 headline.
14641 Inherited tags have the `inherited' text property."
14642 (if (and org-trust-scanner-tags
14643 (or (not pos) (eq pos (point)))
14644 (not local))
14645 org-scanner-tags
14646 (org-with-point-at (or pos (point))
14647 (unless (org-before-first-heading-p)
14648 (org-back-to-heading t)
14649 (let ((tags (org--get-local-tags)))
14650 (if (or local (not org-use-tag-inheritance)) tags
14651 (while (org-up-heading-safe)
14652 (setq tags (append (mapcar #'org-add-prop-inherited
14653 (org--get-local-tags))
14654 tags)))
14655 (org-remove-uninherited-tags
14656 (delete-dups (append org-file-tags tags)))))))))
14658 (defun org-get-buffer-tags ()
14659 "Get a table of all tags used in the buffer, for completion."
14660 (org-with-point-at 1
14661 (let (tags)
14662 (while (re-search-forward org-tag-line-re nil t)
14663 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14664 tags)))
14665 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14667 ;;;; The mapping API
14669 (defvar org-agenda-skip-comment-trees)
14670 (defvar org-agenda-skip-function)
14671 (defun org-map-entries (func &optional match scope &rest skip)
14672 "Call FUNC at each headline selected by MATCH in SCOPE.
14674 FUNC is a function or a lisp form. The function will be called without
14675 arguments, with the cursor positioned at the beginning of the headline.
14676 The return values of all calls to the function will be collected and
14677 returned as a list.
14679 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14680 does not need to preserve point. After evaluation, the cursor will be
14681 moved to the end of the line (presumably of the headline of the
14682 processed entry) and search continues from there. Under some
14683 circumstances, this may not produce the wanted results. For example,
14684 if you have removed (e.g. archived) the current (sub)tree it could
14685 mean that the next entry will be skipped entirely. In such cases, you
14686 can specify the position from where search should continue by making
14687 FUNC set the variable `org-map-continue-from' to the desired buffer
14688 position.
14690 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14691 Only headlines that are matched by this query will be considered during
14692 the iteration. When MATCH is nil or t, all headlines will be
14693 visited by the iteration.
14695 SCOPE determines the scope of this command. It can be any of:
14697 nil The current buffer, respecting the restriction if any
14698 tree The subtree started with the entry at point
14699 region The entries within the active region, if any
14700 region-start-level
14701 The entries within the active region, but only those at
14702 the same level than the first one.
14703 file The current buffer, without restriction
14704 file-with-archives
14705 The current buffer, and any archives associated with it
14706 agenda All agenda files
14707 agenda-with-archives
14708 All agenda files with any archive files associated with them
14709 \(file1 file2 ...)
14710 If this is a list, all files in the list will be scanned
14712 The remaining args are treated as settings for the skipping facilities of
14713 the scanner. The following items can be given here:
14715 archive skip trees with the archive tag
14716 comment skip trees with the COMMENT keyword
14717 function or Emacs Lisp form:
14718 will be used as value for `org-agenda-skip-function', so
14719 whenever the function returns a position, FUNC will not be
14720 called for that entry and search will continue from the
14721 position returned
14723 If your function needs to retrieve the tags including inherited tags
14724 at the *current* entry, you can use the value of the variable
14725 `org-scanner-tags' which will be much faster than getting the value
14726 with `org-get-tags'. If your function gets properties with
14727 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14728 to t around the call to `org-entry-properties' to get the same speedup.
14729 Note that if your function moves around to retrieve tags and properties at
14730 a *different* entry, you cannot use these techniques."
14731 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14732 (not (org-region-active-p)))
14733 (let* ((org-agenda-archives-mode nil) ; just to make sure
14734 (org-agenda-skip-archived-trees (memq 'archive skip))
14735 (org-agenda-skip-comment-trees (memq 'comment skip))
14736 (org-agenda-skip-function
14737 (car (org-delete-all '(comment archive) skip)))
14738 (org-tags-match-list-sublevels t)
14739 (start-level (eq scope 'region-start-level))
14740 matcher res
14741 org-todo-keywords-for-agenda
14742 org-done-keywords-for-agenda
14743 org-todo-keyword-alist-for-agenda
14744 org-tag-alist-for-agenda
14745 org--matcher-tags-todo-only)
14747 (cond
14748 ((eq match t) (setq matcher t))
14749 ((eq match nil) (setq matcher t))
14750 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14752 (save-excursion
14753 (save-restriction
14754 (cond ((eq scope 'tree)
14755 (org-back-to-heading t)
14756 (org-narrow-to-subtree)
14757 (setq scope nil))
14758 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14759 (org-region-active-p))
14760 ;; If needed, set start-level to a string like "2"
14761 (when start-level
14762 (save-excursion
14763 (goto-char (region-beginning))
14764 (unless (org-at-heading-p) (outline-next-heading))
14765 (setq start-level (org-current-level))))
14766 (narrow-to-region (region-beginning)
14767 (save-excursion
14768 (goto-char (region-end))
14769 (unless (and (bolp) (org-at-heading-p))
14770 (outline-next-heading))
14771 (point)))
14772 (setq scope nil)))
14774 (if (not scope)
14775 (progn
14776 (org-agenda-prepare-buffers
14777 (and buffer-file-name (list buffer-file-name)))
14778 (setq res
14779 (org-scan-tags
14780 func matcher org--matcher-tags-todo-only start-level)))
14781 ;; Get the right scope
14782 (cond
14783 ((and scope (listp scope) (symbolp (car scope)))
14784 (setq scope (eval scope)))
14785 ((eq scope 'agenda)
14786 (setq scope (org-agenda-files t)))
14787 ((eq scope 'agenda-with-archives)
14788 (setq scope (org-agenda-files t))
14789 (setq scope (org-add-archive-files scope)))
14790 ((eq scope 'file)
14791 (setq scope (and buffer-file-name (list buffer-file-name))))
14792 ((eq scope 'file-with-archives)
14793 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14794 (org-agenda-prepare-buffers scope)
14795 (dolist (file scope)
14796 (with-current-buffer (org-find-base-buffer-visiting file)
14797 (org-with-wide-buffer
14798 (goto-char (point-min))
14799 (setq res
14800 (append
14802 (org-scan-tags
14803 func matcher org--matcher-tags-todo-only)))))))))
14804 res)))
14806 ;;; Properties API
14808 (defconst org-special-properties
14809 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14810 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14811 "The special properties valid in Org mode.
14812 These are properties that are not defined in the property drawer,
14813 but in some other way.")
14815 (defconst org-default-properties
14816 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14817 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14818 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14819 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14820 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14821 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14822 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14823 "Some properties that are used by Org mode for various purposes.
14824 Being in this list makes sure that they are offered for completion.")
14826 (defun org--valid-property-p (property)
14827 "Non nil when string PROPERTY is a valid property name."
14828 (not
14829 (or (equal property "")
14830 (string-match-p "\\s-" property))))
14832 (defun org--update-property-plist (key val props)
14833 "Associate KEY to VAL in alist PROPS.
14834 Modifications are made by side-effect. Return new alist."
14835 (let* ((appending (string= (substring key -1) "+"))
14836 (key (if appending (substring key 0 -1) key))
14837 (old (assoc-string key props t)))
14838 (if (not old) (cons (cons key val) props)
14839 (setcdr old (if appending (concat (cdr old) " " val) val))
14840 props)))
14842 (defun org-get-property-block (&optional beg force)
14843 "Return the (beg . end) range of the body of the property drawer.
14844 BEG is the beginning of the current subtree, or of the part
14845 before the first headline. If it is not given, it will be found.
14846 If the drawer does not exist, create it if FORCE is non-nil, or
14847 return nil."
14848 (org-with-wide-buffer
14849 (when beg (goto-char beg))
14850 (unless (org-before-first-heading-p)
14851 (let ((beg (cond (beg)
14852 ((or (not (featurep 'org-inlinetask))
14853 (org-inlinetask-in-task-p))
14854 (org-back-to-heading t))
14855 (t (org-with-limited-levels (org-back-to-heading t))))))
14856 (forward-line)
14857 (when (looking-at-p org-planning-line-re) (forward-line))
14858 (cond ((looking-at org-property-drawer-re)
14859 (forward-line)
14860 (cons (point) (progn (goto-char (match-end 0))
14861 (line-beginning-position))))
14862 (force
14863 (goto-char beg)
14864 (org-insert-property-drawer)
14865 (let ((pos (save-excursion (search-forward ":END:")
14866 (line-beginning-position))))
14867 (cons pos pos))))))))
14869 (defun org-at-property-p ()
14870 "Non-nil when point is inside a property drawer.
14871 See `org-property-re' for match data, if applicable."
14872 (save-excursion
14873 (beginning-of-line)
14874 (and (looking-at org-property-re)
14875 (let ((property-drawer (save-match-data (org-get-property-block))))
14876 (and property-drawer
14877 (>= (point) (car property-drawer))
14878 (< (point) (cdr property-drawer)))))))
14880 (defun org-property-action ()
14881 "Do an action on properties."
14882 (interactive)
14883 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14884 (let ((c (read-char-exclusive)))
14885 (cl-case c
14886 (?s (call-interactively #'org-set-property))
14887 (?d (call-interactively #'org-delete-property))
14888 (?D (call-interactively #'org-delete-property-globally))
14889 (?c (call-interactively #'org-compute-property-at-point))
14890 (otherwise (user-error "No such property action %c" c)))))
14892 (defun org-inc-effort ()
14893 "Increment the value of the effort property in the current entry."
14894 (interactive)
14895 (org-set-effort t))
14897 (defvar org-clock-effort) ; Defined in org-clock.el.
14898 (defvar org-clock-current-task) ; Defined in org-clock.el.
14899 (defun org-set-effort (&optional increment value)
14900 "Set the effort property of the current entry.
14901 If INCREMENT is non-nil, set the property to the next allowed
14902 value. Otherwise, if optional argument VALUE is provided, use
14903 it. Eventually, prompt for the new value if none of the previous
14904 variables is set."
14905 (interactive "P")
14906 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14907 (current (org-entry-get nil org-effort-property))
14908 (value
14909 (cond
14910 (increment
14911 (unless allowed (user-error "Allowed effort values are not set"))
14912 (or (cl-caadr (member (list current) allowed))
14913 (user-error "Unknown value %S among allowed values" current)))
14914 (value
14915 (if (stringp value) value
14916 (error "Invalid effort value: %S" value)))
14918 (let ((must-match
14919 (and allowed
14920 (not (get-text-property 0 'org-unrestricted
14921 (caar allowed))))))
14922 (completing-read "Effort: " allowed nil must-match))))))
14923 (unless (equal current value)
14924 (org-entry-put nil org-effort-property value))
14925 (org-refresh-property '((effort . identity)
14926 (effort-minutes . org-duration-to-minutes))
14927 value)
14928 (when (equal (org-get-heading t t t t)
14929 (bound-and-true-p org-clock-current-task))
14930 (setq org-clock-effort (org-get-at-bol 'effort))
14931 (org-clock-update-mode-line))
14932 (message "%s is now %s" org-effort-property value)))
14934 (defun org-entry-properties (&optional pom which)
14935 "Get all properties of the current entry.
14937 When POM is a buffer position, get all properties from the entry
14938 there instead.
14940 This includes the TODO keyword, the tags, time strings for
14941 deadline, scheduled, and clocking, and any additional properties
14942 defined in the entry.
14944 If WHICH is nil or `all', get all properties. If WHICH is
14945 `special' or `standard', only get that subclass. If WHICH is
14946 a string, only get that property.
14948 Return value is an alist. Keys are properties, as upcased
14949 strings."
14950 (org-with-point-at pom
14951 (when (and (derived-mode-p 'org-mode)
14952 (ignore-errors (org-back-to-heading t)))
14953 (catch 'exit
14954 (let* ((beg (point))
14955 (specific (and (stringp which) (upcase which)))
14956 (which (cond ((not specific) which)
14957 ((member specific org-special-properties) 'special)
14958 (t 'standard)))
14959 props)
14960 ;; Get the special properties, like TODO and TAGS.
14961 (when (memq which '(nil all special))
14962 (when (or (not specific) (string= specific "CLOCKSUM"))
14963 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
14964 (when clocksum
14965 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
14966 props)))
14967 (when specific (throw 'exit props)))
14968 (when (or (not specific) (string= specific "CLOCKSUM_T"))
14969 (let ((clocksumt (get-text-property (point)
14970 :org-clock-minutes-today)))
14971 (when clocksumt
14972 (push (cons "CLOCKSUM_T"
14973 (org-duration-from-minutes clocksumt))
14974 props)))
14975 (when specific (throw 'exit props)))
14976 (when (or (not specific) (string= specific "ITEM"))
14977 (let ((case-fold-search nil))
14978 (when (looking-at org-complex-heading-regexp)
14979 (push (cons "ITEM"
14980 (let ((title (match-string-no-properties 4)))
14981 (if (org-string-nw-p title)
14982 (org-remove-tabs title)
14983 "")))
14984 props)))
14985 (when specific (throw 'exit props)))
14986 (when (or (not specific) (string= specific "TODO"))
14987 (let ((case-fold-search nil))
14988 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14989 (push (cons "TODO" (match-string-no-properties 2)) props)))
14990 (when specific (throw 'exit props)))
14991 (when (or (not specific) (string= specific "PRIORITY"))
14992 (push (cons "PRIORITY"
14993 (if (looking-at org-priority-regexp)
14994 (match-string-no-properties 2)
14995 (char-to-string org-default-priority)))
14996 props)
14997 (when specific (throw 'exit props)))
14998 (when (or (not specific) (string= specific "FILE"))
14999 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15000 props)
15001 (when specific (throw 'exit props)))
15002 (when (or (not specific) (string= specific "TAGS"))
15003 (let ((tags (org-get-tags nil t)))
15004 (when tags
15005 (push (cons "TAGS" (org-make-tag-string tags))
15006 props)))
15007 (when specific (throw 'exit props)))
15008 (when (or (not specific) (string= specific "ALLTAGS"))
15009 (let ((tags (org-get-tags)))
15010 (when tags
15011 (push (cons "ALLTAGS" (org-make-tag-string tags))
15012 props)))
15013 (when specific (throw 'exit props)))
15014 (when (or (not specific) (string= specific "BLOCKED"))
15015 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15016 (when specific (throw 'exit props)))
15017 (when (or (not specific)
15018 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15019 (forward-line)
15020 (when (looking-at-p org-planning-line-re)
15021 (end-of-line)
15022 (let ((bol (line-beginning-position))
15023 ;; Backward compatibility: time keywords used to
15024 ;; be configurable (before 8.3). Make sure we
15025 ;; get the correct keyword.
15026 (key-assoc `(("CLOSED" . ,org-closed-string)
15027 ("DEADLINE" . ,org-deadline-string)
15028 ("SCHEDULED" . ,org-scheduled-string))))
15029 (dolist (pair (if specific (list (assoc specific key-assoc))
15030 key-assoc))
15031 (save-excursion
15032 (when (search-backward (cdr pair) bol t)
15033 (goto-char (match-end 0))
15034 (skip-chars-forward " \t")
15035 (and (looking-at org-ts-regexp-both)
15036 (push (cons (car pair)
15037 (match-string-no-properties 0))
15038 props)))))))
15039 (when specific (throw 'exit props)))
15040 (when (or (not specific)
15041 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15042 (let ((find-ts
15043 (lambda (end ts)
15044 ;; Fix next time-stamp before END. TS is the
15045 ;; list of time-stamps found so far.
15046 (let ((ts ts)
15047 (regexp (cond
15048 ((string= specific "TIMESTAMP")
15049 org-ts-regexp)
15050 ((string= specific "TIMESTAMP_IA")
15051 org-ts-regexp-inactive)
15052 ((assoc "TIMESTAMP_IA" ts)
15053 org-ts-regexp)
15054 ((assoc "TIMESTAMP" ts)
15055 org-ts-regexp-inactive)
15056 (t org-ts-regexp-both))))
15057 (catch 'next
15058 (while (re-search-forward regexp end t)
15059 (backward-char)
15060 (let ((object (org-element-context)))
15061 ;; Accept to match timestamps in node
15062 ;; properties, too.
15063 (when (memq (org-element-type object)
15064 '(node-property timestamp))
15065 (let ((type
15066 (org-element-property :type object)))
15067 (cond
15068 ((and (memq type '(active active-range))
15069 (not (equal specific "TIMESTAMP_IA")))
15070 (unless (assoc "TIMESTAMP" ts)
15071 (push (cons "TIMESTAMP"
15072 (org-element-property
15073 :raw-value object))
15075 (when specific (throw 'exit ts))))
15076 ((and (memq type '(inactive inactive-range))
15077 (not (string= specific "TIMESTAMP")))
15078 (unless (assoc "TIMESTAMP_IA" ts)
15079 (push (cons "TIMESTAMP_IA"
15080 (org-element-property
15081 :raw-value object))
15083 (when specific (throw 'exit ts))))))
15084 ;; Both timestamp types are found,
15085 ;; move to next part.
15086 (when (= (length ts) 2) (throw 'next ts)))))
15087 ts)))))
15088 (goto-char beg)
15089 ;; First look for timestamps within headline.
15090 (let ((ts (funcall find-ts (line-end-position) nil)))
15091 (if (= (length ts) 2) (setq props (nconc ts props))
15092 ;; Then find timestamps in the section, skipping
15093 ;; planning line.
15094 (let ((end (save-excursion (outline-next-heading))))
15095 (forward-line)
15096 (when (looking-at-p org-planning-line-re) (forward-line))
15097 (setq props (nconc (funcall find-ts end ts) props))))))))
15098 ;; Get the standard properties, like :PROP:.
15099 (when (memq which '(nil all standard))
15100 ;; If we are looking after a specific property, delegate
15101 ;; to `org-entry-get', which is faster. However, make an
15102 ;; exception for "CATEGORY", since it can be also set
15103 ;; through keywords (i.e. #+CATEGORY).
15104 (if (and specific (not (equal specific "CATEGORY")))
15105 (let ((value (org-entry-get beg specific nil t)))
15106 (throw 'exit (and value (list (cons specific value)))))
15107 (let ((range (org-get-property-block beg)))
15108 (when range
15109 (let ((end (cdr range)) seen-base)
15110 (goto-char (car range))
15111 ;; Unlike to `org--update-property-plist', we
15112 ;; handle the case where base values is found
15113 ;; after its extension. We also forbid standard
15114 ;; properties to be named as special properties.
15115 (while (re-search-forward org-property-re end t)
15116 (let* ((key (upcase (match-string-no-properties 2)))
15117 (extendp (string-match-p "\\+\\'" key))
15118 (key-base (if extendp (substring key 0 -1) key))
15119 (value (match-string-no-properties 3)))
15120 (cond
15121 ((member-ignore-case key-base org-special-properties))
15122 (extendp
15123 (setq props
15124 (org--update-property-plist key value props)))
15125 ((member key seen-base))
15126 (t (push key seen-base)
15127 (let ((p (assoc-string key props t)))
15128 (if p (setcdr p (concat value " " (cdr p)))
15129 (push (cons key value) props))))))))))))
15130 (unless (assoc "CATEGORY" props)
15131 (push (cons "CATEGORY" (org-get-category beg)) props)
15132 (when (string= specific "CATEGORY") (throw 'exit props)))
15133 ;; Return value.
15134 props)))))
15136 (defun org--property-local-values (property literal-nil)
15137 "Return value for PROPERTY in current entry.
15138 Value is a list whose car is the base value for PROPERTY and cdr
15139 a list of accumulated values. Return nil if neither is found in
15140 the entry. Also return nil when PROPERTY is set to \"nil\",
15141 unless LITERAL-NIL is non-nil."
15142 (let ((range (org-get-property-block)))
15143 (when range
15144 (goto-char (car range))
15145 (let* ((case-fold-search t)
15146 (end (cdr range))
15147 (value
15148 ;; Base value.
15149 (save-excursion
15150 (let ((v (and (re-search-forward
15151 (org-re-property property nil t) end t)
15152 (match-string-no-properties 3))))
15153 (list (if literal-nil v (org-not-nil v)))))))
15154 ;; Find additional values.
15155 (let* ((property+ (org-re-property (concat property "+") nil t)))
15156 (while (re-search-forward property+ end t)
15157 (push (match-string-no-properties 3) value)))
15158 ;; Return final values.
15159 (and (not (equal value '(nil))) (nreverse value))))))
15161 (defun org--property-global-value (property literal-nil)
15162 "Return value for PROPERTY in current buffer.
15163 Return value is a string. Return nil if property is not set
15164 globally. Also return nil when PROPERTY is set to \"nil\",
15165 unless LITERAL-NIL is non-nil."
15166 (let ((global
15167 (cdr (or (assoc-string property org-file-properties t)
15168 (assoc-string property org-global-properties t)
15169 (assoc-string property org-global-properties-fixed t)))))
15170 (if literal-nil global (org-not-nil global))))
15172 (defun org-entry-get (pom property &optional inherit literal-nil)
15173 "Get value of PROPERTY for entry or content at point-or-marker POM.
15175 If INHERIT is non-nil and the entry does not have the property,
15176 then also check higher levels of the hierarchy. If INHERIT is
15177 the symbol `selective', use inheritance only if the setting in
15178 `org-use-property-inheritance' selects PROPERTY for inheritance.
15180 If the property is present but empty, the return value is the
15181 empty string. If the property is not present at all, nil is
15182 returned. In any other case, return the value as a string.
15183 Search is case-insensitive.
15185 If LITERAL-NIL is set, return the string value \"nil\" as
15186 a string, do not interpret it as the list atom nil. This is used
15187 for inheritance when a \"nil\" value can supersede a non-nil
15188 value higher up the hierarchy."
15189 (org-with-point-at pom
15190 (cond
15191 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15192 ;; We need a special property. Use `org-entry-properties' to
15193 ;; retrieve it, but specify the wanted property.
15194 (cdr (assoc-string property (org-entry-properties nil property))))
15195 ((and inherit
15196 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15197 (org-entry-get-with-inheritance property literal-nil))
15199 (let* ((local (org--property-local-values property literal-nil))
15200 (value (and local (mapconcat #'identity (delq nil local) " "))))
15201 (if literal-nil value (org-not-nil value)))))))
15203 (defun org-property-or-variable-value (var &optional inherit)
15204 "Check if there is a property fixing the value of VAR.
15205 If yes, return this value. If not, return the current value of the variable."
15206 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15207 (if (and prop (stringp prop) (string-match "\\S-" prop))
15208 (read prop)
15209 (symbol-value var))))
15211 (defun org-entry-delete (pom property)
15212 "Delete PROPERTY from entry at point-or-marker POM.
15213 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15214 non-nil when a property was removed."
15215 (org-with-point-at pom
15216 (pcase (org-get-property-block)
15217 (`(,begin . ,origin)
15218 (let* ((end (copy-marker origin))
15219 (re (org-re-property
15220 (concat (regexp-quote property) "\\+?") t t)))
15221 (goto-char begin)
15222 (while (re-search-forward re end t)
15223 (delete-region (match-beginning 0) (line-beginning-position 2)))
15224 ;; If drawer is empty, remove it altogether.
15225 (when (= begin end)
15226 (delete-region (line-beginning-position 0)
15227 (line-beginning-position 2)))
15228 ;; Return non-nil if some property was removed.
15229 (prog1 (/= end origin) (set-marker end nil))))
15230 (_ nil))))
15232 ;; Multi-values properties are properties that contain multiple values
15233 ;; These values are assumed to be single words, separated by whitespace.
15234 (defun org-entry-add-to-multivalued-property (pom property value)
15235 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15236 (let* ((old (org-entry-get pom property))
15237 (values (and old (split-string old))))
15238 (setq value (org-entry-protect-space value))
15239 (unless (member value values)
15240 (setq values (append values (list value)))
15241 (org-entry-put pom property (mapconcat #'identity values " ")))))
15243 (defun org-entry-remove-from-multivalued-property (pom property value)
15244 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15245 (let* ((old (org-entry-get pom property))
15246 (values (and old (split-string old))))
15247 (setq value (org-entry-protect-space value))
15248 (when (member value values)
15249 (setq values (delete value values))
15250 (org-entry-put pom property (mapconcat #'identity values " ")))))
15252 (defun org-entry-member-in-multivalued-property (pom property value)
15253 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15254 (let* ((old (org-entry-get pom property))
15255 (values (and old (split-string old))))
15256 (setq value (org-entry-protect-space value))
15257 (member value values)))
15259 (defun org-entry-get-multivalued-property (pom property)
15260 "Return a list of values in a multivalued property."
15261 (let* ((value (org-entry-get pom property))
15262 (values (and value (split-string value))))
15263 (mapcar #'org-entry-restore-space values)))
15265 (defun org-entry-put-multivalued-property (pom property &rest values)
15266 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15267 VALUES should be a list of strings. Spaces will be protected."
15268 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15269 (let* ((value (org-entry-get pom property))
15270 (values (and value (split-string value))))
15271 (mapcar #'org-entry-restore-space values)))
15273 (defun org-entry-protect-space (s)
15274 "Protect spaces and newline in string S."
15275 (while (string-match " " s)
15276 (setq s (replace-match "%20" t t s)))
15277 (while (string-match "\n" s)
15278 (setq s (replace-match "%0A" t t s)))
15281 (defun org-entry-restore-space (s)
15282 "Restore spaces and newline in string S."
15283 (while (string-match "%20" s)
15284 (setq s (replace-match " " t t s)))
15285 (while (string-match "%0A" s)
15286 (setq s (replace-match "\n" t t s)))
15289 (defvar org-entry-property-inherited-from (make-marker)
15290 "Marker pointing to the entry from where a property was inherited.
15291 Each call to `org-entry-get-with-inheritance' will set this marker to the
15292 location of the entry where the inheritance search matched. If there was
15293 no match, the marker will point nowhere.
15294 Note that also `org-entry-get' calls this function, if the INHERIT flag
15295 is set.")
15297 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15298 "Get PROPERTY of entry or content at point, search higher levels if needed.
15299 The search will stop at the first ancestor which has the property defined.
15300 If the value found is \"nil\", return nil to show that the property
15301 should be considered as undefined (this is the meaning of nil here).
15302 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15303 (move-marker org-entry-property-inherited-from nil)
15304 (org-with-wide-buffer
15305 (let (value)
15306 (catch 'exit
15307 (while t
15308 (let ((v (org--property-local-values property literal-nil)))
15309 (when v
15310 (setq value
15311 (concat (mapconcat #'identity (delq nil v) " ")
15312 (and value " ")
15313 value)))
15314 (cond
15315 ((car v)
15316 (org-back-to-heading t)
15317 (move-marker org-entry-property-inherited-from (point))
15318 (throw 'exit nil))
15319 ((org-up-heading-safe))
15321 (let ((global (org--property-global-value property literal-nil)))
15322 (cond ((not global))
15323 (value (setq value (concat global " " value)))
15324 (t (setq value global))))
15325 (throw 'exit nil))))))
15326 (if literal-nil value (org-not-nil value)))))
15328 (defvar org-property-changed-functions nil
15329 "Hook called when the value of a property has changed.
15330 Each hook function should accept two arguments, the name of the property
15331 and the new value.")
15333 (defun org-entry-put (pom property value)
15334 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15336 If the value is nil, it is converted to the empty string. If it
15337 is not a string, an error is raised. Also raise an error on
15338 invalid property names.
15340 PROPERTY can be any regular property (see
15341 `org-special-properties'). It can also be \"TODO\",
15342 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15344 For the last two properties, VALUE may have any of the special
15345 values \"earlier\" and \"later\". The function then increases or
15346 decreases scheduled or deadline date by one day."
15347 (cond ((null value) (setq value ""))
15348 ((not (stringp value)) (error "Properties values should be strings"))
15349 ((not (org--valid-property-p property))
15350 (user-error "Invalid property name: \"%s\"" property)))
15351 (org-with-point-at pom
15352 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15353 (org-back-to-heading t)
15354 (org-with-limited-levels (org-back-to-heading t)))
15355 (let ((beg (point)))
15356 (cond
15357 ((equal property "TODO")
15358 (cond ((not (org-string-nw-p value)) (setq value 'none))
15359 ((not (member value org-todo-keywords-1))
15360 (user-error "\"%s\" is not a valid TODO state" value)))
15361 (org-todo value)
15362 (org-align-tags))
15363 ((equal property "PRIORITY")
15364 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15365 (org-align-tags))
15366 ((equal property "SCHEDULED")
15367 (forward-line)
15368 (if (and (looking-at-p org-planning-line-re)
15369 (re-search-forward
15370 org-scheduled-time-regexp (line-end-position) t))
15371 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15372 ((string= value "later") (org-timestamp-change 1 'day))
15373 ((string= value "") (org-schedule '(4)))
15374 (t (org-schedule nil value)))
15375 (if (member value '("earlier" "later" ""))
15376 (call-interactively #'org-schedule)
15377 (org-schedule nil value))))
15378 ((equal property "DEADLINE")
15379 (forward-line)
15380 (if (and (looking-at-p org-planning-line-re)
15381 (re-search-forward
15382 org-deadline-time-regexp (line-end-position) t))
15383 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15384 ((string= value "later") (org-timestamp-change 1 'day))
15385 ((string= value "") (org-deadline '(4)))
15386 (t (org-deadline nil value)))
15387 (if (member value '("earlier" "later" ""))
15388 (call-interactively #'org-deadline)
15389 (org-deadline nil value))))
15390 ((member property org-special-properties)
15391 (error "The %s property cannot be set with `org-entry-put'" property))
15393 (let* ((range (org-get-property-block beg 'force))
15394 (end (cdr range))
15395 (case-fold-search t))
15396 (goto-char (car range))
15397 (if (re-search-forward (org-re-property property nil t) end t)
15398 (progn (delete-region (match-beginning 0) (match-end 0))
15399 (goto-char (match-beginning 0)))
15400 (goto-char end)
15401 (insert "\n")
15402 (backward-char))
15403 (insert ":" property ":")
15404 (when value (insert " " value))
15405 (org-indent-line)))))
15406 (run-hook-with-args 'org-property-changed-functions property value)))
15408 (defun org-buffer-property-keys (&optional specials defaults columns)
15409 "Get all property keys in the current buffer.
15411 When SPECIALS is non-nil, also list the special properties that
15412 reflect things like tags and TODO state.
15414 When DEFAULTS is non-nil, also include properties that has
15415 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15416 DESCRIPTION, LOCATION, and LOGGING and others.
15418 When COLUMNS in non-nil, also include property names given in
15419 COLUMN formats in the current buffer."
15420 (let ((case-fold-search t)
15421 (props (append
15422 (and specials org-special-properties)
15423 (and defaults (cons org-effort-property org-default-properties))
15424 nil)))
15425 (org-with-wide-buffer
15426 (goto-char (point-min))
15427 (while (re-search-forward org-property-start-re nil t)
15428 (catch :skip
15429 (let ((range (org-get-property-block)))
15430 (unless range (throw :skip nil))
15431 (goto-char (car range))
15432 (let ((begin (car range))
15433 (end (cdr range)))
15434 ;; Make sure that found property block is not located
15435 ;; before current point, as it would generate an infloop.
15436 ;; It can happen, for example, in the following
15437 ;; situation:
15439 ;; * Headline
15440 ;; :PROPERTIES:
15441 ;; ...
15442 ;; :END:
15443 ;; *************** Inlinetask
15444 ;; #+BEGIN_EXAMPLE
15445 ;; :PROPERTIES:
15446 ;; #+END_EXAMPLE
15448 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15449 (while (< (point) end)
15450 (let ((p (progn (looking-at org-property-re)
15451 (match-string-no-properties 2))))
15452 ;; Only add true property name, not extension symbol.
15453 (push (if (not (string-match-p "\\+\\'" p)) p
15454 (substring p 0 -1))
15455 props))
15456 (forward-line))))
15457 (outline-next-heading)))
15458 (when columns
15459 (goto-char (point-min))
15460 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15461 (let ((element (org-element-at-point)))
15462 (when (memq (org-element-type element) '(keyword node-property))
15463 (let ((value (org-element-property :value element))
15464 (start 0))
15465 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15466 \\(?:{[^}]+}\\)?"
15467 value start)
15468 (setq start (match-end 0))
15469 (let ((p (match-string-no-properties 1 value)))
15470 (unless (member-ignore-case p org-special-properties)
15471 (push p props))))))))))
15472 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15474 (defun org-property-values (key)
15475 "List all non-nil values of property KEY in current buffer."
15476 (org-with-wide-buffer
15477 (goto-char (point-min))
15478 (let ((case-fold-search t)
15479 (re (org-re-property key))
15480 values)
15481 (while (re-search-forward re nil t)
15482 (push (org-entry-get (point) key) values))
15483 (delete-dups values))))
15485 (defun org-insert-property-drawer ()
15486 "Insert a property drawer into the current entry."
15487 (org-with-wide-buffer
15488 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15489 (org-back-to-heading t)
15490 (org-with-limited-levels (org-back-to-heading t)))
15491 (forward-line)
15492 (when (looking-at-p org-planning-line-re) (forward-line))
15493 (unless (looking-at-p org-property-drawer-re)
15494 ;; Make sure we start editing a line from current entry, not from
15495 ;; next one. It prevents extending text properties or overlays
15496 ;; belonging to the latter.
15497 (when (bolp) (backward-char))
15498 (let ((begin (1+ (point)))
15499 (inhibit-read-only t))
15500 (insert "\n:PROPERTIES:\n:END:")
15501 (when (eobp) (insert "\n"))
15502 (org-indent-region begin (point))))))
15504 (defun org-insert-drawer (&optional arg drawer)
15505 "Insert a drawer at point.
15507 When optional argument ARG is non-nil, insert a property drawer.
15509 Optional argument DRAWER, when non-nil, is a string representing
15510 drawer's name. Otherwise, the user is prompted for a name.
15512 If a region is active, insert the drawer around that region
15513 instead.
15515 Point is left between drawer's boundaries."
15516 (interactive "P")
15517 (let* ((drawer (if arg "PROPERTIES"
15518 (or drawer (read-from-minibuffer "Drawer: ")))))
15519 (cond
15520 ;; With C-u, fall back on `org-insert-property-drawer'
15521 (arg (org-insert-property-drawer))
15522 ;; Check validity of suggested drawer's name.
15523 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15524 (user-error "Invalid drawer name"))
15525 ;; With an active region, insert a drawer at point.
15526 ((not (org-region-active-p))
15527 (progn
15528 (unless (bolp) (insert "\n"))
15529 (insert (format ":%s:\n\n:END:\n" drawer))
15530 (forward-line -2)))
15531 ;; Otherwise, insert the drawer at point
15533 (let ((rbeg (region-beginning))
15534 (rend (copy-marker (region-end))))
15535 (unwind-protect
15536 (progn
15537 (goto-char rbeg)
15538 (beginning-of-line)
15539 (when (save-excursion
15540 (re-search-forward org-outline-regexp-bol rend t))
15541 (user-error "Drawers cannot contain headlines"))
15542 ;; Position point at the beginning of the first
15543 ;; non-blank line in region. Insert drawer's opening
15544 ;; there, then indent it.
15545 (org-skip-whitespace)
15546 (beginning-of-line)
15547 (insert ":" drawer ":\n")
15548 (forward-line -1)
15549 (indent-for-tab-command)
15550 ;; Move point to the beginning of the first blank line
15551 ;; after the last non-blank line in region. Insert
15552 ;; drawer's closing, then indent it.
15553 (goto-char rend)
15554 (skip-chars-backward " \r\t\n")
15555 (insert "\n:END:")
15556 (deactivate-mark t)
15557 (indent-for-tab-command)
15558 (unless (eolp) (insert "\n")))
15559 ;; Clear marker, whatever the outcome of insertion is.
15560 (set-marker rend nil)))))))
15562 (defvar org-property-set-functions-alist nil
15563 "Property set function alist.
15564 Each entry should have the following format:
15566 (PROPERTY . READ-FUNCTION)
15568 The read function will be called with the same argument as
15569 `org-completing-read'.")
15571 (defun org-set-property-function (property)
15572 "Get the function that should be used to set PROPERTY.
15573 This is computed according to `org-property-set-functions-alist'."
15574 (or (cdr (assoc property org-property-set-functions-alist))
15575 'org-completing-read))
15577 (defun org-read-property-value (property)
15578 "Read PROPERTY value from user."
15579 (let* ((completion-ignore-case t)
15580 (allowed (org-property-get-allowed-values nil property 'table))
15581 (cur (org-entry-get nil property))
15582 (prompt (concat property " value"
15583 (if (and cur (string-match "\\S-" cur))
15584 (concat " [" cur "]") "") ": "))
15585 (set-function (org-set-property-function property))
15586 (val (if allowed
15587 (funcall set-function prompt allowed nil
15588 (not (get-text-property 0 'org-unrestricted
15589 (caar allowed))))
15590 (funcall set-function prompt
15591 (mapcar 'list (org-property-values property))
15592 nil nil "" nil cur))))
15593 (org-trim val)))
15595 (defvar org-last-set-property nil)
15596 (defvar org-last-set-property-value nil)
15597 (defun org-read-property-name ()
15598 "Read a property name."
15599 (let ((completion-ignore-case t)
15600 (default-prop (or (and (org-at-property-p)
15601 (match-string-no-properties 2))
15602 org-last-set-property)))
15603 (org-completing-read
15604 (concat "Property"
15605 (if default-prop (concat " [" default-prop "]") "")
15606 ": ")
15607 (mapcar #'list (org-buffer-property-keys nil t t))
15608 nil nil nil nil default-prop)))
15610 (defun org-set-property-and-value (use-last)
15611 "Allow to set [PROPERTY]: [value] direction from prompt.
15612 When use-default, don't even ask, just use the last
15613 \"[PROPERTY]: [value]\" string from the history."
15614 (interactive "P")
15615 (let* ((completion-ignore-case t)
15616 (pv (or (and use-last org-last-set-property-value)
15617 (org-completing-read
15618 "Enter a \"[Property]: [value]\" pair: "
15619 nil nil nil nil nil
15620 org-last-set-property-value)))
15621 prop val)
15622 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15623 (setq prop (match-string 1 pv)
15624 val (match-string 2 pv))
15625 (org-set-property prop val))))
15627 (defun org-set-property (property value)
15628 "In the current entry, set PROPERTY to VALUE.
15630 When called interactively, this will prompt for a property name, offering
15631 completion on existing and default properties. And then it will prompt
15632 for a value, offering completion either on allowed values (via an inherited
15633 xxx_ALL property) or on existing values in other instances of this property
15634 in the current file.
15636 Throw an error when trying to set a property with an invalid name."
15637 (interactive (list nil nil))
15638 (let ((property (or property (org-read-property-name))))
15639 ;; `org-entry-put' also makes the following check, but this one
15640 ;; avoids polluting `org-last-set-property' and
15641 ;; `org-last-set-property-value' needlessly.
15642 (unless (org--valid-property-p property)
15643 (user-error "Invalid property name: \"%s\"" property))
15644 (let ((value (or value (org-read-property-value property)))
15645 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15646 (setq org-last-set-property property)
15647 (setq org-last-set-property-value (concat property ": " value))
15648 ;; Possibly postprocess the inserted value:
15649 (when fn (setq value (funcall fn value)))
15650 (unless (equal (org-entry-get nil property) value)
15651 (org-entry-put nil property value)))))
15653 (defun org-find-property (property &optional value)
15654 "Find first entry in buffer that sets PROPERTY.
15656 When optional argument VALUE is non-nil, only consider an entry
15657 if it contains PROPERTY set to this value. If PROPERTY should be
15658 explicitly set to nil, use string \"nil\" for VALUE.
15660 Return position where the entry begins, or nil if there is no
15661 such entry. If narrowing is in effect, only search the visible
15662 part of the buffer."
15663 (save-excursion
15664 (goto-char (point-min))
15665 (let ((case-fold-search t)
15666 (re (org-re-property property nil (not value) value)))
15667 (catch 'exit
15668 (while (re-search-forward re nil t)
15669 (when (if value (org-at-property-p)
15670 (org-entry-get (point) property nil t))
15671 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15673 (defun org-delete-property (property)
15674 "In the current entry, delete PROPERTY."
15675 (interactive
15676 (let* ((completion-ignore-case t)
15677 (cat (org-entry-get (point) "CATEGORY"))
15678 (props0 (org-entry-properties nil 'standard))
15679 (props (if cat props0
15680 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15681 (prop (if (< 1 (length props))
15682 (completing-read "Property: " props nil t)
15683 (caar props))))
15684 (list prop)))
15685 (if (not property)
15686 (message "No property to delete in this entry")
15687 (org-entry-delete nil property)
15688 (message "Property \"%s\" deleted" property)))
15690 (defun org-delete-property-globally (property)
15691 "Remove PROPERTY globally, from all entries.
15692 This function ignores narrowing, if any."
15693 (interactive
15694 (let* ((completion-ignore-case t)
15695 (prop (completing-read
15696 "Globally remove property: "
15697 (mapcar #'list (org-buffer-property-keys)))))
15698 (list prop)))
15699 (org-with-wide-buffer
15700 (goto-char (point-min))
15701 (let ((count 0)
15702 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15703 (while (re-search-forward re nil t)
15704 (when (org-entry-delete (point) property) (cl-incf count)))
15705 (message "Property \"%s\" removed from %d entries" property count))))
15707 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15709 (defun org-compute-property-at-point ()
15710 "Compute the property at point.
15711 This looks for an enclosing column format, extracts the operator and
15712 then applies it to the property in the column format's scope."
15713 (interactive)
15714 (unless (org-at-property-p)
15715 (user-error "Not at a property"))
15716 (let ((prop (match-string-no-properties 2)))
15717 (org-columns-get-format-and-top-level)
15718 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15719 (user-error "No operator defined for property %s" prop))
15720 (org-columns-compute prop)))
15722 (defvar org-property-allowed-value-functions nil
15723 "Hook for functions supplying allowed values for a specific property.
15724 The functions must take a single argument, the name of the property, and
15725 return a flat list of allowed values. If \":ETC\" is one of
15726 the values, this means that these values are intended as defaults for
15727 completion, but that other values should be allowed too.
15728 The functions must return nil if they are not responsible for this
15729 property.")
15731 (defun org-property-get-allowed-values (pom property &optional table)
15732 "Get allowed values for the property PROPERTY.
15733 When TABLE is non-nil, return an alist that can directly be used for
15734 completion."
15735 (let (vals)
15736 (cond
15737 ((equal property "TODO")
15738 (setq vals (org-with-point-at pom
15739 (append org-todo-keywords-1 '("")))))
15740 ((equal property "PRIORITY")
15741 (let ((n org-lowest-priority))
15742 (while (>= n org-highest-priority)
15743 (push (char-to-string n) vals)
15744 (setq n (1- n)))))
15745 ((equal property "CATEGORY"))
15746 ((member property org-special-properties))
15747 ((setq vals (run-hook-with-args-until-success
15748 'org-property-allowed-value-functions property)))
15750 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15751 (when (and vals (string-match "\\S-" vals))
15752 (setq vals (car (read-from-string (concat "(" vals ")"))))
15753 (setq vals (mapcar (lambda (x)
15754 (cond ((stringp x) x)
15755 ((numberp x) (number-to-string x))
15756 ((symbolp x) (symbol-name x))
15757 (t "???")))
15758 vals)))))
15759 (when (member ":ETC" vals)
15760 (setq vals (remove ":ETC" vals))
15761 (org-add-props (car vals) '(org-unrestricted t)))
15762 (if table (mapcar 'list vals) vals)))
15764 (defun org-property-previous-allowed-value (&optional _previous)
15765 "Switch to the next allowed value for this property."
15766 (interactive)
15767 (org-property-next-allowed-value t))
15769 (defun org-property-next-allowed-value (&optional previous)
15770 "Switch to the next allowed value for this property."
15771 (interactive)
15772 (unless (org-at-property-p)
15773 (user-error "Not at a property"))
15774 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15775 (key (match-string 2))
15776 (value (match-string 3))
15777 (allowed (or (org-property-get-allowed-values (point) key)
15778 (and (member value '("[ ]" "[-]" "[X]"))
15779 '("[ ]" "[X]"))))
15780 (heading (save-match-data (nth 4 (org-heading-components))))
15781 nval)
15782 (unless allowed
15783 (user-error "Allowed values for this property have not been defined"))
15784 (when previous (setq allowed (reverse allowed)))
15785 (when (member value allowed)
15786 (setq nval (car (cdr (member value allowed)))))
15787 (setq nval (or nval (car allowed)))
15788 (when (equal nval value)
15789 (user-error "Only one allowed value for this property"))
15790 (org-at-property-p)
15791 (replace-match (concat " :" key ": " nval) t t)
15792 (org-indent-line)
15793 (beginning-of-line 1)
15794 (skip-chars-forward " \t")
15795 (when (equal prop org-effort-property)
15796 (org-refresh-property
15797 '((effort . identity)
15798 (effort-minutes . org-duration-to-minutes))
15799 nval)
15800 (when (string= org-clock-current-task heading)
15801 (setq org-clock-effort nval)
15802 (org-clock-update-mode-line)))
15803 (run-hook-with-args 'org-property-changed-functions key nval)))
15805 (defun org-find-olp (path &optional this-buffer)
15806 "Return a marker pointing to the entry at outline path OLP.
15807 If anything goes wrong, throw an error.
15808 You can wrap this call to catch the error like this:
15810 (condition-case msg
15811 (org-mobile-locate-entry (match-string 4))
15812 (error (nth 1 msg)))
15814 The return value will then be either a string with the error message,
15815 or a marker if everything is OK.
15817 If THIS-BUFFER is set, the outline path does not contain a file,
15818 only headings."
15819 (let* ((file (if this-buffer buffer-file-name (pop path)))
15820 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15821 (level 1)
15822 (lmin 1)
15823 (lmax 1)
15824 end found flevel)
15825 (unless buffer (error "File not found :%s" file))
15826 (with-current-buffer buffer
15827 (unless (derived-mode-p 'org-mode)
15828 (error "Buffer %s needs to be in Org mode" buffer))
15829 (org-with-wide-buffer
15830 (goto-char (point-min))
15831 (dolist (heading path)
15832 (let ((re (format org-complex-heading-regexp-format
15833 (regexp-quote heading)))
15834 (cnt 0))
15835 (while (re-search-forward re end t)
15836 (setq level (- (match-end 1) (match-beginning 1)))
15837 (when (and (>= level lmin) (<= level lmax))
15838 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15839 (when (= cnt 0)
15840 (error "Heading not found on level %d: %s" lmax heading))
15841 (when (> cnt 1)
15842 (error "Heading not unique on level %d: %s" lmax heading))
15843 (goto-char found)
15844 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15845 (setq end (save-excursion (org-end-of-subtree t t)))))
15846 (when (org-at-heading-p)
15847 (point-marker))))))
15849 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15850 "Find node HEADING in BUFFER.
15851 Return a marker to the heading if it was found, or nil if not.
15852 If POS-ONLY is set, return just the position instead of a marker.
15854 The heading text must match exact, but it may have a TODO keyword,
15855 a priority cookie and tags in the standard locations."
15856 (with-current-buffer (or buffer (current-buffer))
15857 (org-with-wide-buffer
15858 (goto-char (point-min))
15859 (let (case-fold-search)
15860 (when (re-search-forward
15861 (format org-complex-heading-regexp-format
15862 (regexp-quote heading)) nil t)
15863 (if pos-only
15864 (match-beginning 0)
15865 (move-marker (make-marker) (match-beginning 0))))))))
15867 (defun org-find-exact-heading-in-directory (heading &optional dir)
15868 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15869 When the target headline is found, return a marker to this location."
15870 (let ((files (directory-files (or dir default-directory)
15871 t "\\`[^.#].*\\.org\\'"))
15872 visiting m buffer)
15873 (catch 'found
15874 (dolist (file files)
15875 (message "trying %s" file)
15876 (setq visiting (org-find-base-buffer-visiting file))
15877 (setq buffer (or visiting (find-file-noselect file)))
15878 (setq m (org-find-exact-headline-in-buffer
15879 heading buffer))
15880 (when (and (not m) (not visiting)) (kill-buffer buffer))
15881 (and m (throw 'found m))))))
15883 (defun org-find-entry-with-id (ident)
15884 "Locate the entry that contains the ID property with exact value IDENT.
15885 IDENT can be a string, a symbol or a number, this function will search for
15886 the string representation of it.
15887 Return the position where this entry starts, or nil if there is no such entry."
15888 (interactive "sID: ")
15889 (let ((id (cond
15890 ((stringp ident) ident)
15891 ((symbolp ident) (symbol-name ident))
15892 ((numberp ident) (number-to-string ident))
15893 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15894 (org-with-wide-buffer (org-find-property "ID" id))))
15896 ;;;; Timestamps
15898 (defvar org-last-changed-timestamp nil)
15899 (defvar org-last-inserted-timestamp nil
15900 "The last time stamp inserted with `org-insert-time-stamp'.")
15902 (defun org-time-stamp (arg &optional inactive)
15903 "Prompt for a date/time and insert a time stamp.
15905 If the user specifies a time like HH:MM or if this command is
15906 called with at least one prefix argument, the time stamp contains
15907 the date and the time. Otherwise, only the date is included.
15909 All parts of a date not specified by the user are filled in from
15910 the timestamp at point, if any, or the current date/time
15911 otherwise.
15913 If there is already a timestamp at the cursor, it is replaced.
15915 With two universal prefix arguments, insert an active timestamp
15916 with the current time without prompting the user.
15918 When called from lisp, the timestamp is inactive if INACTIVE is
15919 non-nil."
15920 (interactive "P")
15921 (let* ((ts (cond
15922 ((org-at-date-range-p t)
15923 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15924 ((org-at-timestamp-p 'lax) (match-string 0))))
15925 ;; Default time is either the timestamp at point or today.
15926 ;; When entering a range, only the range start is considered.
15927 (default-time (if (not ts) (current-time)
15928 (apply #'encode-time (org-parse-time-string ts))))
15929 (default-input (and ts (org-get-compact-tod ts)))
15930 (repeater (and ts
15931 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15932 (match-string 0 ts)))
15933 org-time-was-given
15934 org-end-time-was-given
15935 (time
15936 (and (if (equal arg '(16)) (current-time)
15937 ;; Preserve `this-command' and `last-command'.
15938 (let ((this-command this-command)
15939 (last-command last-command))
15940 (org-read-date
15941 arg 'totime nil nil default-time default-input
15942 inactive))))))
15943 (cond
15944 ((and ts
15945 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15946 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15947 (insert "--")
15948 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15950 ;; Make sure we're on a timestamp. When in the middle of a date
15951 ;; range, move arbitrarily to range end.
15952 (unless (org-at-timestamp-p 'lax)
15953 (skip-chars-forward "-")
15954 (org-at-timestamp-p 'lax))
15955 (replace-match "")
15956 (setq org-last-changed-timestamp
15957 (org-insert-time-stamp
15958 time (or org-time-was-given arg)
15959 inactive nil nil (list org-end-time-was-given)))
15960 (when repeater
15961 (backward-char)
15962 (insert " " repeater)
15963 (setq org-last-changed-timestamp
15964 (concat (substring org-last-inserted-timestamp 0 -1)
15965 " " repeater ">")))
15966 (message "Timestamp updated"))
15967 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
15968 (t (org-insert-time-stamp
15969 time (or org-time-was-given arg) inactive nil nil
15970 (list org-end-time-was-given))))))
15972 ;; FIXME: can we use this for something else, like computing time differences?
15973 (defun org-get-compact-tod (s)
15974 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15975 (let* ((t1 (match-string 1 s))
15976 (h1 (string-to-number (match-string 2 s)))
15977 (m1 (string-to-number (match-string 3 s)))
15978 (t2 (and (match-end 4) (match-string 5 s)))
15979 (h2 (and t2 (string-to-number (match-string 6 s))))
15980 (m2 (and t2 (string-to-number (match-string 7 s))))
15981 dh dm)
15982 (if (not t2)
15984 (setq dh (- h2 h1) dm (- m2 m1))
15985 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15986 (concat t1 "+" (number-to-string dh)
15987 (and (/= 0 dm) (format ":%02d" dm)))))))
15989 (defun org-time-stamp-inactive (&optional arg)
15990 "Insert an inactive time stamp.
15992 An inactive time stamp is enclosed in square brackets instead of angle
15993 brackets. It is inactive in the sense that it does not trigger agenda entries,
15994 does not link to the calendar and cannot be changed with the S-cursor keys.
15995 So these are more for recording a certain time/date.
15997 If the user specifies a time like HH:MM or if this command is called with
15998 at least one prefix argument, the time stamp contains the date and the time.
15999 Otherwise, only the date is included.
16001 When called with two universal prefix arguments, insert an active time stamp
16002 with the current time without prompting the user."
16003 (interactive "P")
16004 (org-time-stamp arg 'inactive))
16006 (defvar org-date-ovl (make-overlay 1 1))
16007 (overlay-put org-date-ovl 'face 'org-date-selected)
16008 (delete-overlay org-date-ovl)
16010 (defvar org-ans1) ; dynamically scoped parameter
16011 (defvar org-ans2) ; dynamically scoped parameter
16013 (defvar org-plain-time-of-day-regexp) ; defined below
16015 (defvar org-overriding-default-time nil) ; dynamically scoped
16016 (defvar org-read-date-overlay nil)
16017 (defvar org-dcst nil) ; dynamically scoped
16018 (defvar org-read-date-history nil)
16019 (defvar org-read-date-final-answer nil)
16020 (defvar org-read-date-analyze-futurep nil)
16021 (defvar org-read-date-analyze-forced-year nil)
16022 (defvar org-read-date-inactive)
16024 (defvar org-read-date-minibuffer-local-map
16025 (let* ((map (make-sparse-keymap)))
16026 (set-keymap-parent map minibuffer-local-map)
16027 (org-defkey map (kbd ".")
16028 (lambda () (interactive)
16029 ;; Are we at the beginning of the prompt?
16030 (if (looking-back "^[^:]+: "
16031 (let ((inhibit-field-text-motion t))
16032 (line-beginning-position)))
16033 (org-eval-in-calendar '(calendar-goto-today))
16034 (insert "."))))
16035 (org-defkey map (kbd "C-.")
16036 (lambda () (interactive)
16037 (org-eval-in-calendar '(calendar-goto-today))))
16038 (org-defkey map (kbd "M-S-<left>")
16039 (lambda () (interactive)
16040 (org-eval-in-calendar '(calendar-backward-month 1))))
16041 (org-defkey map (kbd "ESC S-<left>")
16042 (lambda () (interactive)
16043 (org-eval-in-calendar '(calendar-backward-month 1))))
16044 (org-defkey map (kbd "M-S-<right>")
16045 (lambda () (interactive)
16046 (org-eval-in-calendar '(calendar-forward-month 1))))
16047 (org-defkey map (kbd "ESC S-<right>")
16048 (lambda () (interactive)
16049 (org-eval-in-calendar '(calendar-forward-month 1))))
16050 (org-defkey map (kbd "M-S-<up>")
16051 (lambda () (interactive)
16052 (org-eval-in-calendar '(calendar-backward-year 1))))
16053 (org-defkey map (kbd "ESC S-<up>")
16054 (lambda () (interactive)
16055 (org-eval-in-calendar '(calendar-backward-year 1))))
16056 (org-defkey map (kbd "M-S-<down>")
16057 (lambda () (interactive)
16058 (org-eval-in-calendar '(calendar-forward-year 1))))
16059 (org-defkey map (kbd "ESC S-<down>")
16060 (lambda () (interactive)
16061 (org-eval-in-calendar '(calendar-forward-year 1))))
16062 (org-defkey map (kbd "S-<up>")
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(calendar-backward-week 1))))
16065 (org-defkey map (kbd "S-<down>")
16066 (lambda () (interactive)
16067 (org-eval-in-calendar '(calendar-forward-week 1))))
16068 (org-defkey map (kbd "S-<left>")
16069 (lambda () (interactive)
16070 (org-eval-in-calendar '(calendar-backward-day 1))))
16071 (org-defkey map (kbd "S-<right>")
16072 (lambda () (interactive)
16073 (org-eval-in-calendar '(calendar-forward-day 1))))
16074 (org-defkey map (kbd "!")
16075 (lambda () (interactive)
16076 (org-eval-in-calendar '(diary-view-entries))
16077 (message "")))
16078 (org-defkey map (kbd ">")
16079 (lambda () (interactive)
16080 (org-eval-in-calendar '(calendar-scroll-left 1))))
16081 (org-defkey map (kbd "<")
16082 (lambda () (interactive)
16083 (org-eval-in-calendar '(calendar-scroll-right 1))))
16084 (org-defkey map (kbd "C-v")
16085 (lambda () (interactive)
16086 (org-eval-in-calendar
16087 '(calendar-scroll-left-three-months 1))))
16088 (org-defkey map (kbd "M-v")
16089 (lambda () (interactive)
16090 (org-eval-in-calendar
16091 '(calendar-scroll-right-three-months 1))))
16092 map)
16093 "Keymap for minibuffer commands when using `org-read-date'.")
16095 (defvar org-def)
16096 (defvar org-defdecode)
16097 (defvar org-with-time)
16099 (defvar calendar-setup) ; Dynamically scoped.
16100 (defun org-read-date (&optional with-time to-time from-string prompt
16101 default-time default-input inactive)
16102 "Read a date, possibly a time, and make things smooth for the user.
16103 The prompt will suggest to enter an ISO date, but you can also enter anything
16104 which will at least partially be understood by `parse-time-string'.
16105 Unrecognized parts of the date will default to the current day, month, year,
16106 hour and minute. If this command is called to replace a timestamp at point,
16107 or to enter the second timestamp of a range, the default time is taken
16108 from the existing stamp. Furthermore, the command prefers the future,
16109 so if you are giving a date where the year is not given, and the day-month
16110 combination is already past in the current year, it will assume you
16111 mean next year. For details, see the manual. A few examples:
16113 3-2-5 --> 2003-02-05
16114 feb 15 --> currentyear-02-15
16115 2/15 --> currentyear-02-15
16116 sep 12 9 --> 2009-09-12
16117 12:45 --> today 12:45
16118 22 sept 0:34 --> currentyear-09-22 0:34
16119 12 --> currentyear-currentmonth-12
16120 Fri --> nearest Friday after today
16121 -Tue --> last Tuesday
16122 etc.
16124 Furthermore you can specify a relative date by giving, as the *first* thing
16125 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16126 change in days weeks, months, years.
16127 With a single plus or minus, the date is relative to today. With a double
16128 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16129 +4d --> four days from today
16130 +4 --> same as above
16131 +2w --> two weeks from today
16132 ++5 --> five days from default date
16134 The function understands only English month and weekday abbreviations.
16136 While prompting, a calendar is popped up - you can also select the
16137 date with the mouse (button 1). The calendar shows a period of three
16138 months. To scroll it to other months, use the keys `>' and `<'.
16139 If you don't like the calendar, turn it off with
16140 (setq org-read-date-popup-calendar nil)
16142 With optional argument TO-TIME, the date will immediately be converted
16143 to an internal time.
16144 With an optional argument WITH-TIME, the prompt will suggest to
16145 also insert a time. Note that when WITH-TIME is not set, you can
16146 still enter a time, and this function will inform the calling routine
16147 about this change. The calling routine may then choose to change the
16148 format used to insert the time stamp into the buffer to include the time.
16149 With optional argument FROM-STRING, read from this string instead from
16150 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16151 the time/date that is used for everything that is not specified by the
16152 user."
16153 (require 'parse-time)
16154 (let* ((org-with-time with-time)
16155 (org-time-stamp-rounding-minutes
16156 (if (equal org-with-time '(16))
16157 '(0 0)
16158 org-time-stamp-rounding-minutes))
16159 (org-dcst org-display-custom-times)
16160 (ct (org-current-time))
16161 (org-def (or org-overriding-default-time default-time ct))
16162 (org-defdecode (decode-time org-def))
16163 (cur-frame (selected-frame))
16164 (mouse-autoselect-window nil) ; Don't let the mouse jump
16165 (calendar-setup
16166 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16167 (calendar-move-hook nil)
16168 (calendar-view-diary-initially-flag nil)
16169 (calendar-view-holidays-initially-flag nil)
16170 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16171 ;; Rationalize `org-def' and `org-defdecode', if required.
16172 (when (< (nth 2 org-defdecode) org-extend-today-until)
16173 (setf (nth 2 org-defdecode) -1)
16174 (setf (nth 1 org-defdecode) 59)
16175 (setq org-def (apply #'encode-time org-defdecode))
16176 (setq org-defdecode (decode-time org-def)))
16177 (let* ((timestr (format-time-string
16178 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16179 org-def))
16180 (prompt (concat (if prompt (concat prompt " ") "")
16181 (format "Date+time [%s]: " timestr))))
16182 (cond
16183 (from-string (setq ans from-string))
16184 (org-read-date-popup-calendar
16185 (save-excursion
16186 (save-window-excursion
16187 (calendar)
16188 (when (eq calendar-setup 'calendar-only)
16189 (setq cal-frame
16190 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16191 (select-frame cal-frame))
16192 (org-eval-in-calendar '(setq cursor-type nil) t)
16193 (unwind-protect
16194 (progn
16195 (calendar-forward-day (- (time-to-days org-def)
16196 (calendar-absolute-from-gregorian
16197 (calendar-current-date))))
16198 (org-eval-in-calendar nil t)
16199 (let* ((old-map (current-local-map))
16200 (map (copy-keymap calendar-mode-map))
16201 (minibuffer-local-map
16202 (copy-keymap org-read-date-minibuffer-local-map)))
16203 (org-defkey map (kbd "RET") 'org-calendar-select)
16204 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16205 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16206 (unwind-protect
16207 (progn
16208 (use-local-map map)
16209 (setq org-read-date-inactive inactive)
16210 (add-hook 'post-command-hook 'org-read-date-display)
16211 (setq org-ans0
16212 (read-string prompt
16213 default-input
16214 'org-read-date-history
16215 nil))
16216 ;; org-ans0: from prompt
16217 ;; org-ans1: from mouse click
16218 ;; org-ans2: from calendar motion
16219 (setq ans
16220 (concat org-ans0 " " (or org-ans1 org-ans2))))
16221 (remove-hook 'post-command-hook 'org-read-date-display)
16222 (use-local-map old-map)
16223 (when org-read-date-overlay
16224 (delete-overlay org-read-date-overlay)
16225 (setq org-read-date-overlay nil)))))
16226 (bury-buffer "*Calendar*")
16227 (when cal-frame
16228 (delete-frame cal-frame)
16229 (select-frame-set-input-focus cur-frame))))))
16231 (t ; Naked prompt only
16232 (unwind-protect
16233 (setq ans (read-string prompt default-input
16234 'org-read-date-history timestr))
16235 (when org-read-date-overlay
16236 (delete-overlay org-read-date-overlay)
16237 (setq org-read-date-overlay nil))))))
16239 (setq final (org-read-date-analyze ans org-def org-defdecode))
16241 (when org-read-date-analyze-forced-year
16242 (message "Year was forced into %s"
16243 (if org-read-date-force-compatible-dates
16244 "compatible range (1970-2037)"
16245 "range representable on this machine"))
16246 (ding))
16248 ;; One round trip to get rid of 34th of August and stuff like that....
16249 (setq final (decode-time (apply 'encode-time final)))
16251 (setq org-read-date-final-answer ans)
16253 (if to-time
16254 (apply 'encode-time final)
16255 (if (and (boundp 'org-time-was-given) org-time-was-given)
16256 (format "%04d-%02d-%02d %02d:%02d"
16257 (nth 5 final) (nth 4 final) (nth 3 final)
16258 (nth 2 final) (nth 1 final))
16259 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16261 (defun org-read-date-display ()
16262 "Display the current date prompt interpretation in the minibuffer."
16263 (when org-read-date-display-live
16264 (when org-read-date-overlay
16265 (delete-overlay org-read-date-overlay))
16266 (when (minibufferp (current-buffer))
16267 (save-excursion
16268 (end-of-line 1)
16269 (while (not (equal (buffer-substring
16270 (max (point-min) (- (point) 4)) (point))
16271 " "))
16272 (insert " ")))
16273 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16274 " " (or org-ans1 org-ans2)))
16275 (org-end-time-was-given nil)
16276 (f (org-read-date-analyze ans org-def org-defdecode))
16277 (fmts (if org-dcst
16278 org-time-stamp-custom-formats
16279 org-time-stamp-formats))
16280 (fmt (if (or org-with-time
16281 (and (boundp 'org-time-was-given) org-time-was-given))
16282 (cdr fmts)
16283 (car fmts)))
16284 (txt (format-time-string fmt (apply 'encode-time f)))
16285 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16286 (txt (concat "=> " txt)))
16287 (when (and org-end-time-was-given
16288 (string-match org-plain-time-of-day-regexp txt))
16289 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16290 org-end-time-was-given
16291 (substring txt (match-end 0)))))
16292 (when org-read-date-analyze-futurep
16293 (setq txt (concat txt " (=>F)")))
16294 (setq org-read-date-overlay
16295 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16296 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16298 (defun org-read-date-analyze (ans def defdecode)
16299 "Analyze the combined answer of the date prompt."
16300 ;; FIXME: cleanup and comment
16301 ;; Pass `current-time' result to `decode-time' (instead of calling
16302 ;; without arguments) so that only `current-time' has to be
16303 ;; overridden in tests.
16304 (let ((org-def def)
16305 (org-defdecode defdecode)
16306 (nowdecode (decode-time (current-time)))
16307 delta deltan deltaw deltadef year month day
16308 hour minute second wday pm h2 m2 tl wday1
16309 iso-year iso-weekday iso-week iso-date futurep kill-year)
16310 (setq org-read-date-analyze-futurep nil
16311 org-read-date-analyze-forced-year nil)
16312 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16313 (setq ans "+0"))
16315 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16316 (setq ans (replace-match "" t t ans)
16317 deltan (car delta)
16318 deltaw (nth 1 delta)
16319 deltadef (nth 2 delta)))
16321 ;; Check if there is an iso week date in there. If yes, store the
16322 ;; info and postpone interpreting it until the rest of the parsing
16323 ;; is done.
16324 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16325 (setq iso-year (when (match-end 1)
16326 (org-small-year-to-year
16327 (string-to-number (match-string 1 ans))))
16328 iso-weekday (when (match-end 3)
16329 (string-to-number (match-string 3 ans)))
16330 iso-week (string-to-number (match-string 2 ans)))
16331 (setq ans (replace-match "" t t ans)))
16333 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16334 (when (string-match
16335 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16336 (setq year (if (match-end 2)
16337 (string-to-number (match-string 2 ans))
16338 (progn (setq kill-year t)
16339 (string-to-number (format-time-string "%Y"))))
16340 month (string-to-number (match-string 3 ans))
16341 day (string-to-number (match-string 4 ans)))
16342 (setq year (org-small-year-to-year year))
16343 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16344 t nil ans)))
16346 ;; Help matching dotted european dates
16347 (when (string-match
16348 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16349 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16350 (setq kill-year t)
16351 (string-to-number (format-time-string "%Y")))
16352 day (string-to-number (match-string 1 ans))
16353 month (string-to-number (match-string 2 ans))
16354 ans (replace-match (format "%04d-%02d-%02d" year month day)
16355 t nil ans)))
16357 ;; Help matching american dates, like 5/30 or 5/30/7
16358 (when (string-match
16359 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16360 (setq year (if (match-end 4)
16361 (string-to-number (match-string 4 ans))
16362 (progn (setq kill-year t)
16363 (string-to-number (format-time-string "%Y"))))
16364 month (string-to-number (match-string 1 ans))
16365 day (string-to-number (match-string 2 ans)))
16366 (setq year (org-small-year-to-year year))
16367 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16368 t nil ans)))
16369 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16370 ;; If there is a time with am/pm, and *no* time without it, we convert
16371 ;; so that matching will be successful.
16372 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16373 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16374 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16375 (setq hour (string-to-number (match-string 1 ans))
16376 minute (if (match-end 3)
16377 (string-to-number (match-string 3 ans))
16379 pm (equal ?p
16380 (string-to-char (downcase (match-string 4 ans)))))
16381 (if (and (= hour 12) (not pm))
16382 (setq hour 0)
16383 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16384 (setq ans (replace-match (format "%02d:%02d" hour minute)
16385 t t ans))))
16387 ;; Check if a time range is given as a duration
16388 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16389 (setq hour (string-to-number (match-string 1 ans))
16390 h2 (+ hour (string-to-number (match-string 3 ans)))
16391 minute (string-to-number (match-string 2 ans))
16392 m2 (+ minute (if (match-end 5) (string-to-number
16393 (match-string 5 ans))0)))
16394 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16395 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16396 t t ans)))
16398 ;; Check if there is a time range
16399 (when (boundp 'org-end-time-was-given)
16400 (setq org-time-was-given nil)
16401 (when (and (string-match org-plain-time-of-day-regexp ans)
16402 (match-end 8))
16403 (setq org-end-time-was-given (match-string 8 ans))
16404 (setq ans (concat (substring ans 0 (match-beginning 7))
16405 (substring ans (match-end 7))))))
16407 (setq tl (parse-time-string ans)
16408 day (or (nth 3 tl) (nth 3 org-defdecode))
16409 month
16410 (cond ((nth 4 tl))
16411 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16412 ;; Day was specified. Make sure DAY+MONTH
16413 ;; combination happens in the future.
16414 ((nth 3 tl)
16415 (setq futurep t)
16416 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16417 (nth 4 nowdecode)))
16418 (t (nth 4 org-defdecode)))
16419 year
16420 (cond ((and (not kill-year) (nth 5 tl)))
16421 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16422 ;; Month was guessed in the future and is at least
16423 ;; equal to NOWDECODE's. Fix year accordingly.
16424 (futurep
16425 (if (or (> month (nth 4 nowdecode))
16426 (>= day (nth 3 nowdecode)))
16427 (nth 5 nowdecode)
16428 (1+ (nth 5 nowdecode))))
16429 ;; Month was specified. Make sure MONTH+YEAR
16430 ;; combination happens in the future.
16431 ((nth 4 tl)
16432 (setq futurep t)
16433 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16434 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16435 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16436 (t (nth 5 nowdecode))))
16437 (t (nth 5 org-defdecode)))
16438 hour (or (nth 2 tl) (nth 2 org-defdecode))
16439 minute (or (nth 1 tl) (nth 1 org-defdecode))
16440 second (or (nth 0 tl) 0)
16441 wday (nth 6 tl))
16443 (when (and (eq org-read-date-prefer-future 'time)
16444 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16445 (equal day (nth 3 nowdecode))
16446 (equal month (nth 4 nowdecode))
16447 (equal year (nth 5 nowdecode))
16448 (nth 2 tl)
16449 (or (< (nth 2 tl) (nth 2 nowdecode))
16450 (and (= (nth 2 tl) (nth 2 nowdecode))
16451 (nth 1 tl)
16452 (< (nth 1 tl) (nth 1 nowdecode)))))
16453 (setq day (1+ day)
16454 futurep t))
16456 ;; Special date definitions below
16457 (cond
16458 (iso-week
16459 ;; There was an iso week
16460 (require 'cal-iso)
16461 (setq futurep nil)
16462 (setq year (or iso-year year)
16463 day (or iso-weekday wday 1)
16464 wday nil ; to make sure that the trigger below does not match
16465 iso-date (calendar-gregorian-from-absolute
16466 (calendar-iso-to-absolute
16467 (list iso-week day year))))
16468 ; FIXME: Should we also push ISO weeks into the future?
16469 ; (when (and org-read-date-prefer-future
16470 ; (not iso-year)
16471 ; (< (calendar-absolute-from-gregorian iso-date)
16472 ; (time-to-days (current-time))))
16473 ; (setq year (1+ year)
16474 ; iso-date (calendar-gregorian-from-absolute
16475 ; (calendar-iso-to-absolute
16476 ; (list iso-week day year)))))
16477 (setq month (car iso-date)
16478 year (nth 2 iso-date)
16479 day (nth 1 iso-date)))
16480 (deltan
16481 (setq futurep nil)
16482 (unless deltadef
16483 ;; Pass `current-time' result to `decode-time' (instead of
16484 ;; calling without arguments) so that only `current-time' has
16485 ;; to be overridden in tests.
16486 (let ((now (decode-time (current-time))))
16487 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16488 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16489 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16490 ((equal deltaw "m") (setq month (+ month deltan)))
16491 ((equal deltaw "y") (setq year (+ year deltan)))))
16492 ((and wday (not (nth 3 tl)))
16493 ;; Weekday was given, but no day, so pick that day in the week
16494 ;; on or after the derived date.
16495 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16496 (unless (equal wday wday1)
16497 (setq day (+ day (% (- wday wday1 -7) 7))))))
16498 (when (and (boundp 'org-time-was-given)
16499 (nth 2 tl))
16500 (setq org-time-was-given t))
16501 (when (< year 100) (setq year (+ 2000 year)))
16502 ;; Check of the date is representable
16503 (if org-read-date-force-compatible-dates
16504 (progn
16505 (when (< year 1970)
16506 (setq year 1970 org-read-date-analyze-forced-year t))
16507 (when (> year 2037)
16508 (setq year 2037 org-read-date-analyze-forced-year t)))
16509 (condition-case nil
16510 (ignore (encode-time second minute hour day month year))
16511 (error
16512 (setq year (nth 5 org-defdecode))
16513 (setq org-read-date-analyze-forced-year t))))
16514 (setq org-read-date-analyze-futurep futurep)
16515 (list second minute hour day month year)))
16517 (defvar parse-time-weekdays)
16518 (defun org-read-date-get-relative (s today default)
16519 "Check string S for special relative date string.
16520 TODAY and DEFAULT are internal times, for today and for a default.
16521 Return shift list (N what def-flag)
16522 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16523 N is the number of WHATs to shift.
16524 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16525 the DEFAULT date rather than TODAY."
16526 (require 'parse-time)
16527 (when (and
16528 (string-match
16529 (concat
16530 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16531 "\\([0-9]+\\)?"
16532 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16533 "\\([ \t]\\|$\\)") s)
16534 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16535 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16536 (string-to-char (substring (match-string 1 s) -1))
16537 ?+))
16538 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16539 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16540 (what (if (match-end 3) (match-string 3 s) "d"))
16541 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16542 (date (if rel default today))
16543 (wday (nth 6 (decode-time date)))
16544 delta)
16545 (if wday1
16546 (progn
16547 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16548 (when (= delta 0) (setq delta 7))
16549 (when (= dir ?-)
16550 (setq delta (- delta 7))
16551 (when (= delta 0) (setq delta -7)))
16552 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16553 (list delta "d" rel))
16554 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16556 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16557 "Turn a user-specified date into the internal representation.
16558 The internal representation needed by the calendar is (month day year).
16559 This is a wrapper to handle the brain-dead convention in calendar that
16560 user function argument order change dependent on argument order."
16561 (pcase calendar-date-style
16562 (`american (list arg1 arg2 arg3))
16563 (`european (list arg2 arg1 arg3))
16564 (`iso (list arg2 arg3 arg1))))
16566 (defun org-eval-in-calendar (form &optional keepdate)
16567 "Eval FORM in the calendar window and return to current window.
16568 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16569 (let ((sf (selected-frame))
16570 (sw (selected-window)))
16571 (select-window (get-buffer-window "*Calendar*" t))
16572 (eval form)
16573 (when (and (not keepdate) (calendar-cursor-to-date))
16574 (let* ((date (calendar-cursor-to-date))
16575 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16576 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16577 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16578 (select-window sw)
16579 (select-frame-set-input-focus sf)))
16581 (defun org-calendar-select ()
16582 "Return to `org-read-date' with the date currently selected.
16583 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16584 (interactive)
16585 (when (calendar-cursor-to-date)
16586 (let* ((date (calendar-cursor-to-date))
16587 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16588 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16589 (when (active-minibuffer-window) (exit-minibuffer))))
16591 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16592 "Insert a date stamp for the date given by the internal TIME.
16593 See `format-time-string' for the format of TIME.
16594 WITH-HM means use the stamp format that includes the time of the day.
16595 INACTIVE means use square brackets instead of angular ones, so that the
16596 stamp will not contribute to the agenda.
16597 PRE and POST are optional strings to be inserted before and after the
16598 stamp.
16599 The command returns the inserted time stamp."
16600 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16601 stamp)
16602 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16603 (insert-before-markers (or pre ""))
16604 (when (listp extra)
16605 (setq extra (car extra))
16606 (if (and (stringp extra)
16607 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16608 (setq extra (format "-%02d:%02d"
16609 (string-to-number (match-string 1 extra))
16610 (string-to-number (match-string 2 extra))))
16611 (setq extra nil)))
16612 (when extra
16613 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16614 (insert-before-markers (setq stamp (format-time-string fmt time)))
16615 (insert-before-markers (or post ""))
16616 (setq org-last-inserted-timestamp stamp)))
16618 (defun org-toggle-time-stamp-overlays ()
16619 "Toggle the use of custom time stamp formats."
16620 (interactive)
16621 (setq org-display-custom-times (not org-display-custom-times))
16622 (unless org-display-custom-times
16623 (let ((p (point-min)) (bmp (buffer-modified-p)))
16624 (while (setq p (next-single-property-change p 'display))
16625 (when (and (get-text-property p 'display)
16626 (eq (get-text-property p 'face) 'org-date))
16627 (remove-text-properties
16628 p (setq p (next-single-property-change p 'display))
16629 '(display t))))
16630 (set-buffer-modified-p bmp)))
16631 (org-restart-font-lock)
16632 (setq org-table-may-need-update t)
16633 (if org-display-custom-times
16634 (message "Time stamps are overlaid with custom format")
16635 (message "Time stamp overlays removed")))
16637 (defun org-display-custom-time (beg end)
16638 "Overlay modified time stamp format over timestamp between BEG and END."
16639 (let* ((ts (buffer-substring beg end))
16640 t1 with-hm tf time str (off 0))
16641 (save-match-data
16642 (setq t1 (org-parse-time-string ts t))
16643 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16644 (setq off (- (match-end 0) (match-beginning 0)))))
16645 (setq end (- end off))
16646 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16647 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16648 time (org-fix-decoded-time t1)
16649 str (org-add-props
16650 (format-time-string
16651 (substring tf 1 -1) (apply 'encode-time time))
16652 nil 'mouse-face 'highlight))
16653 (put-text-property beg end 'display str)))
16655 (defun org-fix-decoded-time (time)
16656 "Set 0 instead of nil for the first 6 elements of time.
16657 Don't touch the rest."
16658 (let ((n 0))
16659 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16661 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16662 "Difference between TIMESTAMP-STRING and now in days.
16663 If SECONDS is non-nil, return the difference in seconds."
16664 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16665 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16666 (funcall fdiff (current-time)))))
16668 (defun org-deadline-close-p (timestamp-string &optional ndays)
16669 "Is the time in TIMESTAMP-STRING close to the current date?"
16670 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16671 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16672 (not (org-entry-is-done-p))))
16674 (defun org-get-wdays (ts &optional delay zero-delay)
16675 "Get the deadline lead time appropriate for timestring TS.
16676 When DELAY is non-nil, get the delay time for scheduled items
16677 instead of the deadline lead time. When ZERO-DELAY is non-nil
16678 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16679 don't try to find the delay cookie in the scheduled timestamp."
16680 (let ((tv (if delay org-scheduled-delay-days
16681 org-deadline-warning-days)))
16682 (cond
16683 ((or (and delay (< tv 0))
16684 (and delay zero-delay (<= tv 0))
16685 (and (not delay) (<= tv 0)))
16686 ;; Enforce this value no matter what
16687 (- tv))
16688 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16689 ;; lead time is specified.
16690 (floor (* (string-to-number (match-string 1 ts))
16691 (cdr (assoc (match-string 2 ts)
16692 '(("d" . 1) ("w" . 7)
16693 ("m" . 30.4) ("y" . 365.25)
16694 ("h" . 0.041667)))))))
16695 ;; go for the default.
16696 (t tv))))
16698 (defun org-calendar-select-mouse (ev)
16699 "Return to `org-read-date' with the date currently selected.
16700 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16701 (interactive "e")
16702 (mouse-set-point ev)
16703 (when (calendar-cursor-to-date)
16704 (let* ((date (calendar-cursor-to-date))
16705 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16706 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16707 (when (active-minibuffer-window) (exit-minibuffer))))
16709 (defun org-check-deadlines (ndays)
16710 "Check if there are any deadlines due or past due.
16711 A deadline is considered due if it happens within `org-deadline-warning-days'
16712 days from today's date. If the deadline appears in an entry marked DONE,
16713 it is not shown. A numeric prefix argument NDAYS can be used to test that
16714 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16715 are shown."
16716 (interactive "P")
16717 (let* ((org-warn-days
16718 (cond
16719 ((equal ndays '(4)) 100000)
16720 (ndays (prefix-numeric-value ndays))
16721 (t (abs org-deadline-warning-days))))
16722 (case-fold-search nil)
16723 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16724 (callback
16725 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16726 (message "%d deadlines past-due or due within %d days"
16727 (org-occur regexp nil callback)
16728 org-warn-days)))
16730 (defsubst org-re-timestamp (type)
16731 "Return a regexp for timestamp TYPE.
16732 Allowed values for TYPE are:
16734 all: all timestamps
16735 active: only active timestamps (<...>)
16736 inactive: only inactive timestamps ([...])
16737 scheduled: only scheduled timestamps
16738 deadline: only deadline timestamps
16739 closed: only closed time-stamps
16741 When TYPE is nil, fall back on returning a regexp that matches
16742 both scheduled and deadline timestamps."
16743 (cl-case type
16744 (all org-ts-regexp-both)
16745 (active org-ts-regexp)
16746 (inactive org-ts-regexp-inactive)
16747 (scheduled org-scheduled-time-regexp)
16748 (deadline org-deadline-time-regexp)
16749 (closed org-closed-time-regexp)
16750 (otherwise
16751 (concat "\\<"
16752 (regexp-opt (list org-deadline-string org-scheduled-string))
16753 " *<\\([^>]+\\)>"))))
16755 (defun org-check-before-date (d)
16756 "Check if there are deadlines or scheduled entries before date D."
16757 (interactive (list (org-read-date)))
16758 (let* ((case-fold-search nil)
16759 (regexp (org-re-timestamp org-ts-type))
16760 (ts-type org-ts-type)
16761 (callback
16762 (lambda ()
16763 (let ((match (match-string 1)))
16764 (and (if (memq ts-type '(active inactive all))
16765 (eq (org-element-type (save-excursion
16766 (backward-char)
16767 (org-element-context)))
16768 'timestamp)
16769 (org-at-planning-p))
16770 (time-less-p
16771 (org-time-string-to-time match)
16772 (org-time-string-to-time d)))))))
16773 (message "%d entries before %s"
16774 (org-occur regexp nil callback)
16775 d)))
16777 (defun org-check-after-date (d)
16778 "Check if there are deadlines or scheduled entries after date D."
16779 (interactive (list (org-read-date)))
16780 (let* ((case-fold-search nil)
16781 (regexp (org-re-timestamp org-ts-type))
16782 (ts-type org-ts-type)
16783 (callback
16784 (lambda ()
16785 (let ((match (match-string 1)))
16786 (and (if (memq ts-type '(active inactive all))
16787 (eq (org-element-type (save-excursion
16788 (backward-char)
16789 (org-element-context)))
16790 'timestamp)
16791 (org-at-planning-p))
16792 (not (time-less-p
16793 (org-time-string-to-time match)
16794 (org-time-string-to-time d))))))))
16795 (message "%d entries after %s"
16796 (org-occur regexp nil callback)
16797 d)))
16799 (defun org-check-dates-range (start-date end-date)
16800 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16801 (interactive (list (org-read-date nil nil nil "Range starts")
16802 (org-read-date nil nil nil "Range end")))
16803 (let ((case-fold-search nil)
16804 (regexp (org-re-timestamp org-ts-type))
16805 (callback
16806 (let ((type org-ts-type))
16807 (lambda ()
16808 (let ((match (match-string 1)))
16809 (and
16810 (if (memq type '(active inactive all))
16811 (eq (org-element-type (save-excursion
16812 (backward-char)
16813 (org-element-context)))
16814 'timestamp)
16815 (org-at-planning-p))
16816 (not (time-less-p
16817 (org-time-string-to-time match)
16818 (org-time-string-to-time start-date)))
16819 (time-less-p
16820 (org-time-string-to-time match)
16821 (org-time-string-to-time end-date))))))))
16822 (message "%d entries between %s and %s"
16823 (org-occur regexp nil callback) start-date end-date)))
16825 (defun org-evaluate-time-range (&optional to-buffer)
16826 "Evaluate a time range by computing the difference between start and end.
16827 Normally the result is just printed in the echo area, but with prefix arg
16828 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16829 If the time range is actually in a table, the result is inserted into the
16830 next column.
16831 For time difference computation, a year is assumed to be exactly 365
16832 days in order to avoid rounding problems."
16833 (interactive "P")
16835 (org-clock-update-time-maybe)
16836 (save-excursion
16837 (unless (org-at-date-range-p t)
16838 (goto-char (point-at-bol))
16839 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16840 (unless (org-at-date-range-p t)
16841 (user-error "Not at a time-stamp range, and none found in current line")))
16842 (let* ((ts1 (match-string 1))
16843 (ts2 (match-string 2))
16844 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16845 (match-end (match-end 0))
16846 (time1 (org-time-string-to-time ts1))
16847 (time2 (org-time-string-to-time ts2))
16848 (t1 (float-time time1))
16849 (t2 (float-time time2))
16850 (diff (abs (- t2 t1)))
16851 (negative (< (- t2 t1) 0))
16852 ;; (ys (floor (* 365 24 60 60)))
16853 (ds (* 24 60 60))
16854 (hs (* 60 60))
16855 (fy "%dy %dd %02d:%02d")
16856 (fy1 "%dy %dd")
16857 (fd "%dd %02d:%02d")
16858 (fd1 "%dd")
16859 (fh "%02d:%02d")
16860 y d h m align)
16861 (if havetime
16862 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16864 d (floor (/ diff ds)) diff (mod diff ds)
16865 h (floor (/ diff hs)) diff (mod diff hs)
16866 m (floor (/ diff 60)))
16867 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16869 d (floor (+ (/ diff ds) 0.5))
16870 h 0 m 0))
16871 (if (not to-buffer)
16872 (message "%s" (org-make-tdiff-string y d h m))
16873 (if (org-at-table-p)
16874 (progn
16875 (goto-char match-end)
16876 (setq align t)
16877 (and (looking-at " *|") (goto-char (match-end 0))))
16878 (goto-char match-end))
16879 (when (looking-at
16880 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16881 (replace-match ""))
16882 (when negative (insert " -"))
16883 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16884 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16885 (insert " " (format fh h m))))
16886 (when align (org-table-align))
16887 (message "Time difference inserted")))))
16889 (defun org-make-tdiff-string (y d h m)
16890 (let ((fmt "")
16891 (l nil))
16892 (when (> y 0)
16893 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16894 (push y l))
16895 (when (> d 0)
16896 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16897 (push d l))
16898 (when (> h 0)
16899 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16900 (push h l))
16901 (when (> m 0)
16902 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16903 (push m l))
16904 (apply 'format fmt (nreverse l))))
16906 (defun org-time-string-to-time (s)
16907 "Convert timestamp string S into internal time."
16908 (apply #'encode-time (org-parse-time-string s)))
16910 (defun org-time-string-to-seconds (s)
16911 "Convert a timestamp string S into a number of seconds."
16912 (float-time (org-time-string-to-time s)))
16914 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16916 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16917 "Convert time stamp S to an absolute day number.
16919 If DAYNR in non-nil, and there is a specifier for a cyclic time
16920 stamp, get the closest date to DAYNR. If PREFER is
16921 `past' (respectively `future') return a date past (respectively
16922 after) or equal to DAYNR.
16924 POS is the location of time stamp S, as a buffer position in
16925 BUFFER.
16927 Diary sexp timestamps are matched against DAYNR, when non-nil.
16928 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16929 signaled."
16930 (cond
16931 ((string-match "\\`%%\\((.*)\\)" s)
16932 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16933 ;; only able to match individual dates. If it fails, raise an
16934 ;; error.
16935 (if (and daynr
16936 (org-diary-sexp-entry
16937 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16938 daynr
16939 (signal 'org-diary-sexp-no-match (list s))))
16940 (daynr (org-closest-date s daynr prefer))
16941 (t (time-to-days
16942 (condition-case errdata
16943 (apply #'encode-time (org-parse-time-string s))
16944 (error (error "Bad timestamp `%s'%s\nError was: %s"
16946 (if (not (and buffer pos)) ""
16947 (format-message " at %d in buffer `%s'" pos buffer))
16948 (cdr errdata))))))))
16950 (defun org-days-to-iso-week (days)
16951 "Return the iso week number."
16952 (require 'cal-iso)
16953 (car (calendar-iso-from-absolute days)))
16955 (defun org-small-year-to-year (year)
16956 "Convert 2-digit years into 4-digit years.
16957 YEAR is expanded into one of the 30 next years, if possible, or
16958 into a past one. Any year larger than 99 is returned unchanged."
16959 (if (>= year 100) year
16960 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16961 (century (/ current 100))
16962 (offset (- year (% current 100))))
16963 (cond ((> offset 30) (+ (* (1- century) 100) year))
16964 ((> offset -70) (+ (* century 100) year))
16965 (t (+ (* (1+ century) 100) year))))))
16967 (defun org-time-from-absolute (d)
16968 "Return the time corresponding to date D.
16969 D may be an absolute day number, or a calendar-type list (month day year)."
16970 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16971 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16973 (defvar org-agenda-current-date)
16974 (defun org-calendar-holiday ()
16975 "List of holidays, for Diary display in Org mode."
16976 (require 'holidays)
16977 (let ((hl (calendar-check-holidays org-agenda-current-date)))
16978 (and hl (mapconcat #'identity hl "; "))))
16980 (defun org-diary-sexp-entry (sexp entry d)
16981 "Process a SEXP diary ENTRY for date D."
16982 (require 'diary-lib)
16983 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
16984 ;; dynamically.
16985 (let* ((sexp `(let ((entry ,entry)
16986 (date ',d))
16987 ,(car (read-from-string sexp))))
16988 (result (if calendar-debug-sexp (eval sexp)
16989 (condition-case nil
16990 (eval sexp)
16991 (error
16992 (beep)
16993 (message "Bad sexp at line %d in %s: %s"
16994 (org-current-line)
16995 (buffer-file-name) sexp)
16996 (sleep-for 2))))))
16997 (cond ((stringp result) (split-string result "; "))
16998 ((and (consp result)
16999 (not (consp (cdr result)))
17000 (stringp (cdr result))) (cdr result))
17001 ((and (consp result)
17002 (stringp (car result))) result)
17003 (result entry))))
17005 (defun org-diary-to-ical-string (frombuf)
17006 "Get iCalendar entries from diary entries in buffer FROMBUF.
17007 This uses the icalendar.el library."
17008 (let* ((tmpdir temporary-file-directory)
17009 (tmpfile (make-temp-name
17010 (expand-file-name "orgics" tmpdir)))
17011 buf rtn b e)
17012 (with-current-buffer frombuf
17013 (icalendar-export-region (point-min) (point-max) tmpfile)
17014 (setq buf (find-buffer-visiting tmpfile))
17015 (set-buffer buf)
17016 (goto-char (point-min))
17017 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17018 (setq b (match-beginning 0)))
17019 (goto-char (point-max))
17020 (when (re-search-backward "^END:VEVENT" nil t)
17021 (setq e (match-end 0)))
17022 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17023 (kill-buffer buf)
17024 (delete-file tmpfile)
17025 rtn))
17027 (defun org-closest-date (start current prefer)
17028 "Return closest date to CURRENT starting from START.
17030 CURRENT and START are both time stamps.
17032 When PREFER is `past', return a date that is either CURRENT or
17033 past. When PREFER is `future', return a date that is either
17034 CURRENT or future.
17036 Only time stamps with a repeater are modified. Any other time
17037 stamp stay unchanged. In any case, return value is an absolute
17038 day number."
17039 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17040 ;; No repeater. Do not shift time stamp.
17041 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17042 (let ((value (string-to-number (match-string 1 start)))
17043 (type (match-string 2 start)))
17044 (if (= 0 value)
17045 ;; Repeater with a 0-value is considered as void.
17046 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17047 (let* ((base (org-date-to-gregorian start))
17048 (target (org-date-to-gregorian current))
17049 (sday (calendar-absolute-from-gregorian base))
17050 (cday (calendar-absolute-from-gregorian target))
17051 n1 n2)
17052 ;; If START is already past CURRENT, just return START.
17053 (if (<= cday sday) sday
17054 ;; Compute closest date before (N1) and closest date past
17055 ;; (N2) CURRENT.
17056 (pcase type
17057 ("h"
17058 (let ((missing-hours
17059 (mod (+ (- (* 24 (- cday sday))
17060 (nth 2 (org-parse-time-string start)))
17061 org-extend-today-until)
17062 value)))
17063 (setf n1 (if (= missing-hours 0) cday
17064 (- cday (1+ (/ missing-hours 24)))))
17065 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17066 ((or "d" "w")
17067 (let ((value (if (equal type "w") (* 7 value) value)))
17068 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17069 (setf n2 (+ n1 value))))
17070 ("m"
17071 (let* ((add-months
17072 (lambda (d n)
17073 ;; Add N months to gregorian date D, i.e.,
17074 ;; a list (MONTH DAY YEAR). Return a valid
17075 ;; gregorian date.
17076 (let ((m (+ (nth 0 d) n)))
17077 (list (mod m 12)
17078 (nth 1 d)
17079 (+ (/ m 12) (nth 2 d))))))
17080 (months ; Complete months to TARGET.
17081 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17082 (- (nth 0 target) (nth 0 base))
17083 ;; If START's day is greater than
17084 ;; TARGET's, remove incomplete month.
17085 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17086 value)
17087 value))
17088 (before (funcall add-months base months)))
17089 (setf n1 (calendar-absolute-from-gregorian before))
17090 (setf n2
17091 (calendar-absolute-from-gregorian
17092 (funcall add-months before value)))))
17094 (let* ((d (nth 1 base))
17095 (m (nth 0 base))
17096 (y (nth 2 base))
17097 (years ; Complete years to TARGET.
17098 (* (/ (- (nth 2 target)
17100 ;; If START's month and day are
17101 ;; greater than TARGET's, remove
17102 ;; incomplete year.
17103 (if (or (> (nth 0 target) m)
17104 (and (= (nth 0 target) m)
17105 (> (nth 1 target) d)))
17108 value)
17109 value))
17110 (before (list m d (+ y years))))
17111 (setf n1 (calendar-absolute-from-gregorian before))
17112 (setf n2 (calendar-absolute-from-gregorian
17113 (list m d (+ (nth 2 before) value)))))))
17114 ;; Handle PREFER parameter, if any.
17115 (cond
17116 ((eq prefer 'past) (if (= cday n2) n2 n1))
17117 ((eq prefer 'future) (if (= cday n1) n1 n2))
17118 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17120 (defun org-date-to-gregorian (d)
17121 "Turn any specification of date D into a Gregorian date for the calendar."
17122 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17123 ((and (listp d) (= (length d) 3)) d)
17124 ((stringp d)
17125 (let ((d (org-parse-time-string d)))
17126 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17127 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17129 (defun org-parse-time-string (s &optional nodefault)
17130 "Parse the standard Org time string.
17132 This should be a lot faster than the normal `parse-time-string'.
17134 If time is not given, defaults to 0:00. However, with optional
17135 NODEFAULT, hour and minute fields will be nil if not given."
17136 (cond ((string-match org-ts-regexp0 s)
17137 (list 0
17138 (when (or (match-beginning 8) (not nodefault))
17139 (string-to-number (or (match-string 8 s) "0")))
17140 (when (or (match-beginning 7) (not nodefault))
17141 (string-to-number (or (match-string 7 s) "0")))
17142 (string-to-number (match-string 4 s))
17143 (string-to-number (match-string 3 s))
17144 (string-to-number (match-string 2 s))
17145 nil nil nil))
17146 ((string-match "^<[^>]+>$" s)
17147 ;; FIXME: `decode-time' needs to be called with ZONE as its
17148 ;; second argument. However, this requires at least Emacs
17149 ;; 25.1. We can do it when we switch to this version as our
17150 ;; minimal requirement.
17151 (decode-time (seconds-to-time (org-matcher-time s))))
17152 (t (error "Not a standard Org time string: %s" s))))
17154 (defun org-timestamp-up (&optional arg)
17155 "Increase the date item at the cursor by one.
17156 If the cursor is on the year, change the year. If it is on the month,
17157 the day or the time, change that. If the cursor is on the enclosing
17158 bracket, change the timestamp type.
17159 With prefix ARG, change by that many units."
17160 (interactive "p")
17161 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17163 (defun org-timestamp-down (&optional arg)
17164 "Decrease the date item at the cursor by one.
17165 If the cursor is on the year, change the year. If it is on the month,
17166 the day or the time, change that. If the cursor is on the enclosing
17167 bracket, change the timestamp type.
17168 With prefix ARG, change by that many units."
17169 (interactive "p")
17170 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17172 (defun org-timestamp-up-day (&optional arg)
17173 "Increase the date in the time stamp by one day.
17174 With prefix ARG, change that many days."
17175 (interactive "p")
17176 (if (and (not (org-at-timestamp-p 'lax))
17177 (org-at-heading-p))
17178 (org-todo 'up)
17179 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17181 (defun org-timestamp-down-day (&optional arg)
17182 "Decrease the date in the time stamp by one day.
17183 With prefix ARG, change that many days."
17184 (interactive "p")
17185 (if (and (not (org-at-timestamp-p 'lax))
17186 (org-at-heading-p))
17187 (org-todo 'down)
17188 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17190 (defun org-at-timestamp-p (&optional extended)
17191 "Non-nil if point is inside a timestamp.
17193 By default, the function only consider syntactically valid active
17194 timestamps. However, the caller may have a broader definition
17195 for timestamps. As a consequence, optional argument EXTENDED can
17196 be set to the following values
17198 `inactive'
17200 Include also syntactically valid inactive timestamps.
17202 `agenda'
17204 Include timestamps allowed in Agenda, i.e., those in
17205 properties drawers, planning lines and clock lines.
17207 `lax'
17209 Ignore context. The function matches any part of the
17210 document looking like a timestamp. This includes comments,
17211 example blocks...
17213 For backward-compatibility with Org 9.0, every other non-nil
17214 value is equivalent to `inactive'.
17216 When at a timestamp, return the position of the point as a symbol
17217 among `bracket', `after', `year', `month', `hour', `minute',
17218 `day' or a number of character from the last know part of the
17219 time stamp.
17221 When matching, the match groups are the following:
17222 group 1: year
17223 group 2: month
17224 group 3: day number
17225 group 4: day name
17226 group 5: hours, if any
17227 group 6: minutes, if any"
17228 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17229 (pos (point))
17230 (match?
17231 (let ((boundaries (org-in-regexp regexp)))
17232 (save-match-data
17233 (cond ((null boundaries) nil)
17234 ((eq extended 'lax) t)
17236 (or (and (eq extended 'agenda)
17237 (or (org-at-planning-p)
17238 (org-at-property-p)
17239 (and (bound-and-true-p
17240 org-agenda-include-inactive-timestamps)
17241 (org-at-clock-log-p))))
17242 (eq 'timestamp
17243 (save-excursion
17244 (when (= pos (cdr boundaries)) (forward-char -1))
17245 (org-element-type (org-element-context)))))))))))
17246 (cond
17247 ((not match?) nil)
17248 ((= pos (match-beginning 0)) 'bracket)
17249 ;; Distinguish location right before the closing bracket from
17250 ;; right after it.
17251 ((= pos (1- (match-end 0))) 'bracket)
17252 ((= pos (match-end 0)) 'after)
17253 ((org-pos-in-match-range pos 2) 'year)
17254 ((org-pos-in-match-range pos 3) 'month)
17255 ((org-pos-in-match-range pos 7) 'hour)
17256 ((org-pos-in-match-range pos 8) 'minute)
17257 ((or (org-pos-in-match-range pos 4)
17258 (org-pos-in-match-range pos 5)) 'day)
17259 ((and (> pos (or (match-end 8) (match-end 5)))
17260 (< pos (match-end 0)))
17261 (- pos (or (match-end 8) (match-end 5))))
17262 (t 'day))))
17264 (defun org-toggle-timestamp-type ()
17265 "Toggle the type (<active> or [inactive]) of a time stamp."
17266 (interactive)
17267 (when (org-at-timestamp-p 'lax)
17268 (let ((beg (match-beginning 0)) (end (match-end 0))
17269 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17270 (save-excursion
17271 (goto-char beg)
17272 (while (re-search-forward "[][<>]" end t)
17273 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17274 t t)))
17275 (message "Timestamp is now %sactive"
17276 (if (equal (char-after beg) ?<) "" "in")))))
17278 (defun org-at-clock-log-p ()
17279 "Non-nil if point is on a clock log line."
17280 (and (org-match-line org-clock-line-re)
17281 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17283 (defvar org-clock-history) ; defined in org-clock.el
17284 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17285 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17286 "Change the date in the time stamp at point.
17287 The date will be changed by N times WHAT. WHAT can be `day', `month',
17288 `year', `minute', `second'. If WHAT is not given, the cursor position
17289 in the timestamp determines what will be changed.
17290 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17291 (let ((origin (point))
17292 (timestamp? (org-at-timestamp-p 'lax))
17293 origin-cat
17294 with-hm inactive
17295 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17296 extra rem
17297 ts time time0 fixnext clrgx)
17298 (unless timestamp? (user-error "Not at a timestamp"))
17299 (if (and (not what) (eq timestamp? 'bracket))
17300 (org-toggle-timestamp-type)
17301 ;; Point isn't on brackets. Remember the part of the time-stamp
17302 ;; the point was in. Indeed, size of time-stamps may change,
17303 ;; but point must be kept in the same category nonetheless.
17304 (setq origin-cat timestamp?)
17305 (when (and (not what) (not (eq timestamp? 'day))
17306 org-display-custom-times
17307 (get-text-property (point) 'display)
17308 (not (get-text-property (1- (point)) 'display)))
17309 (setq timestamp? 'day))
17310 (setq timestamp? (or what timestamp?)
17311 inactive (= (char-after (match-beginning 0)) ?\[)
17312 ts (match-string 0))
17313 (replace-match "")
17314 (when (string-match
17315 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17317 (setq extra (match-string 1 ts))
17318 (when suppress-tmp-delay
17319 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17320 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17321 (setq with-hm t))
17322 (setq time0 (org-parse-time-string ts))
17323 (when (and updown
17324 (eq timestamp? 'minute)
17325 (not current-prefix-arg))
17326 ;; This looks like s-up and s-down. Change by one rounding step.
17327 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17328 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17329 (setcar (cdr time0) (+ (nth 1 time0)
17330 (if (> n 0) (- rem) (- dm rem))))))
17331 (setq time
17332 (apply #'encode-time
17333 (or (car time0) 0)
17334 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17335 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17336 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17337 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17338 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17339 (nthcdr 6 time0)))
17340 (when (and (memq timestamp? '(hour minute))
17341 extra
17342 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17343 (setq extra (org-modify-ts-extra
17344 extra
17345 (if (eq timestamp? 'hour) 2 5)
17346 n dm)))
17347 (when (integerp timestamp?)
17348 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17349 (when (eq what 'calendar)
17350 (let ((cal-date (org-get-date-from-calendar)))
17351 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17352 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17353 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17354 (setcar time0 (or (car time0) 0))
17355 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17356 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17357 (setq time (apply 'encode-time time0))))
17358 ;; Insert the new time-stamp, and ensure point stays in the same
17359 ;; category as before (i.e. not after the last position in that
17360 ;; category).
17361 (let ((pos (point)))
17362 ;; Stay before inserted string. `save-excursion' is of no use.
17363 (setq org-last-changed-timestamp
17364 (org-insert-time-stamp time with-hm inactive nil nil extra))
17365 (goto-char pos))
17366 (save-match-data
17367 (looking-at org-ts-regexp3)
17368 (goto-char
17369 (pcase origin-cat
17370 ;; `day' category ends before `hour' if any, or at the end
17371 ;; of the day name.
17372 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17373 (`hour (min (match-end 7) origin))
17374 (`minute (min (1- (match-end 8)) origin))
17375 ((pred integerp) (min (1- (match-end 0)) origin))
17376 ;; Point was right after the time-stamp. However, the
17377 ;; time-stamp length might have changed, so refer to
17378 ;; (match-end 0) instead.
17379 (`after (match-end 0))
17380 ;; `year' and `month' have both fixed size: point couldn't
17381 ;; have moved into another part.
17382 (_ origin))))
17383 ;; Update clock if on a CLOCK line.
17384 (org-clock-update-time-maybe)
17385 ;; Maybe adjust the closest clock in `org-clock-history'
17386 (when org-clock-adjust-closest
17387 (if (not (and (org-at-clock-log-p)
17388 (< 1 (length (delq nil (mapcar 'marker-position
17389 org-clock-history))))))
17390 (message "No clock to adjust")
17391 (cond ((save-excursion ; fix previous clock?
17392 (re-search-backward org-ts-regexp0 nil t)
17393 (looking-back (concat org-clock-string " \\[")
17394 (line-beginning-position)))
17395 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17396 ((save-excursion ; fix next clock?
17397 (re-search-backward org-ts-regexp0 nil t)
17398 (looking-at (concat org-ts-regexp0 "\\] =>")))
17399 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17400 (save-window-excursion
17401 ;; Find closest clock to point, adjust the previous/next one in history
17402 (let* ((p (save-excursion (org-back-to-heading t)))
17403 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17404 (clfixnth
17405 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17406 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17407 (if (not clfixpos)
17408 (message "No clock to adjust")
17409 (save-excursion
17410 (org-goto-marker-or-bmk clfixpos)
17411 (org-show-subtree)
17412 (when (re-search-forward clrgx nil t)
17413 (goto-char (match-beginning 1))
17414 (let (org-clock-adjust-closest)
17415 (org-timestamp-change n timestamp? updown))
17416 (message "Clock adjusted in %s for heading: %s"
17417 (file-name-nondirectory (buffer-file-name))
17418 (org-get-heading t t)))))))))
17419 ;; Try to recenter the calendar window, if any.
17420 (when (and org-calendar-follow-timestamp-change
17421 (get-buffer-window "*Calendar*" t)
17422 (memq timestamp? '(day month year)))
17423 (org-recenter-calendar (time-to-days time))))))
17425 (defun org-modify-ts-extra (s pos n dm)
17426 "Change the different parts of the lead-time and repeat fields in timestamp."
17427 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17428 ng h m new rem)
17429 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17430 (cond
17431 ((or (org-pos-in-match-range pos 2)
17432 (org-pos-in-match-range pos 3))
17433 (setq m (string-to-number (match-string 3 s))
17434 h (string-to-number (match-string 2 s)))
17435 (if (org-pos-in-match-range pos 2)
17436 (setq h (+ h n))
17437 (setq n (* dm (with-no-warnings (signum n))))
17438 (unless (= 0 (setq rem (% m dm)))
17439 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17440 (setq m (+ m n)))
17441 (when (< m 0) (setq m (+ m 60) h (1- h)))
17442 (when (> m 59) (setq m (- m 60) h (1+ h)))
17443 (setq h (mod h 24))
17444 (setq ng 1 new (format "-%02d:%02d" h m)))
17445 ((org-pos-in-match-range pos 6)
17446 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17447 ((org-pos-in-match-range pos 5)
17448 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17450 ((org-pos-in-match-range pos 9)
17451 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17452 ((org-pos-in-match-range pos 8)
17453 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17455 (when ng
17456 (setq s (concat
17457 (substring s 0 (match-beginning ng))
17459 (substring s (match-end ng))))))
17462 (defun org-recenter-calendar (d)
17463 "If the calendar is visible, recenter it to date D."
17464 (let ((cwin (get-buffer-window "*Calendar*" t)))
17465 (when cwin
17466 (let ((calendar-move-hook nil))
17467 (with-selected-window cwin
17468 (calendar-goto-date
17469 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17471 (defun org-goto-calendar (&optional arg)
17472 "Go to the Emacs calendar at the current date.
17473 If there is a time stamp in the current line, go to that date.
17474 A prefix ARG can be used to force the current date."
17475 (interactive "P")
17476 (let ((calendar-move-hook nil)
17477 (calendar-view-holidays-initially-flag nil)
17478 (calendar-view-diary-initially-flag nil)
17479 diff)
17480 (when (or (org-at-timestamp-p 'lax)
17481 (org-match-line (concat ".*" org-ts-regexp)))
17482 (let ((d1 (time-to-days (current-time)))
17483 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17484 (setq diff (- d2 d1))))
17485 (calendar)
17486 (calendar-goto-today)
17487 (when (and diff (not arg)) (calendar-forward-day diff))))
17489 (defun org-get-date-from-calendar ()
17490 "Return a list (month day year) of date at point in calendar."
17491 (with-current-buffer "*Calendar*"
17492 (save-match-data
17493 (calendar-cursor-to-date))))
17495 (defun org-date-from-calendar ()
17496 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17497 If there is already a time stamp at the cursor position, update it."
17498 (interactive)
17499 (if (org-at-timestamp-p 'lax)
17500 (org-timestamp-change 0 'calendar)
17501 (let ((cal-date (org-get-date-from-calendar)))
17502 (org-insert-time-stamp
17503 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17505 (defcustom org-effort-durations
17506 `(("min" . 1)
17507 ("h" . 60)
17508 ("d" . ,(* 60 8))
17509 ("w" . ,(* 60 8 5))
17510 ("m" . ,(* 60 8 5 4))
17511 ("y" . ,(* 60 8 5 40)))
17512 "Conversion factor to minutes for an effort modifier.
17514 Each entry has the form (MODIFIER . MINUTES).
17516 In an effort string, a number followed by MODIFIER is multiplied
17517 by the specified number of MINUTES to obtain an effort in
17518 minutes.
17520 For example, if the value of this variable is ((\"hours\" . 60)), then an
17521 effort string \"2hours\" is equivalent to 120 minutes."
17522 :group 'org-agenda
17523 :version "26.1"
17524 :package-version '(Org . "8.3")
17525 :type '(alist :key-type (string :tag "Modifier")
17526 :value-type (number :tag "Minutes")))
17528 (defcustom org-image-actual-width t
17529 "Should we use the actual width of images when inlining them?
17531 When set to t, always use the image width.
17533 When set to a number, use imagemagick (when available) to set
17534 the image's width to this value.
17536 When set to a number in a list, try to get the width from any
17537 #+ATTR.* keyword if it matches a width specification like
17539 #+ATTR_HTML: :width 300px
17541 and fall back on that number if none is found.
17543 When set to nil, try to get the width from an #+ATTR.* keyword
17544 and fall back on the original width if none is found.
17546 This requires Emacs >= 24.1, build with imagemagick support."
17547 :group 'org-appearance
17548 :version "24.4"
17549 :package-version '(Org . "8.0")
17550 :type '(choice
17551 (const :tag "Use the image width" t)
17552 (integer :tag "Use a number of pixels")
17553 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17554 (const :tag "Use #+ATTR* or don't resize" nil)))
17556 (defcustom org-agenda-inhibit-startup nil
17557 "Inhibit startup when preparing agenda buffers.
17558 When this variable is t, the initialization of the Org agenda
17559 buffers is inhibited: e.g. the visibility state is not set, the
17560 tables are not re-aligned, etc."
17561 :type 'boolean
17562 :version "24.3"
17563 :group 'org-agenda)
17565 (defcustom org-agenda-ignore-properties nil
17566 "Avoid updating text properties when building the agenda.
17567 Properties are used to prepare buffers for effort estimates,
17568 appointments, statistics and subtree-local categories.
17569 If you don't use these in the agenda, you can add them to this
17570 list and agenda building will be a bit faster.
17571 The value is a list, with zero or more of the symbols `effort', `appt',
17572 `stats' or `category'."
17573 :type '(set :greedy t
17574 (const effort)
17575 (const appt)
17576 (const stats)
17577 (const category))
17578 :version "26.1"
17579 :package-version '(Org . "8.3")
17580 :group 'org-agenda)
17582 ;;;; Files
17584 (defun org-save-all-org-buffers ()
17585 "Save all Org buffers without user confirmation."
17586 (interactive)
17587 (message "Saving all Org buffers...")
17588 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17589 (when (featurep 'org-id) (org-id-locations-save))
17590 (message "Saving all Org buffers... done"))
17592 (defun org-revert-all-org-buffers ()
17593 "Revert all Org buffers.
17594 Prompt for confirmation when there are unsaved changes.
17595 Be sure you know what you are doing before letting this function
17596 overwrite your changes.
17598 This function is useful in a setup where one tracks Org files
17599 with a version control system, to revert on one machine after pulling
17600 changes from another. I believe the procedure must be like this:
17602 1. M-x org-save-all-org-buffers
17603 2. Pull changes from the other machine, resolve conflicts
17604 3. M-x org-revert-all-org-buffers"
17605 (interactive)
17606 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17607 (user-error "Abort"))
17608 (save-excursion
17609 (save-window-excursion
17610 (dolist (b (buffer-list))
17611 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17612 (with-current-buffer b buffer-file-name))
17613 (pop-to-buffer-same-window b)
17614 (revert-buffer t 'no-confirm)))
17615 (when (and (featurep 'org-id) org-id-track-globally)
17616 (org-id-locations-load)))))
17618 ;;;; Agenda files
17620 ;;;###autoload
17621 (defun org-switchb (&optional arg)
17622 "Switch between Org buffers.
17624 With `\\[universal-argument]' prefix, restrict available buffers to files.
17626 With `\\[universal-argument] \\[universal-argument]' \
17627 prefix, restrict available buffers to agenda files."
17628 (interactive "P")
17629 (let ((blist (org-buffer-list
17630 (cond ((equal arg '(4)) 'files)
17631 ((equal arg '(16)) 'agenda)))))
17632 (pop-to-buffer-same-window
17633 (completing-read "Org buffer: "
17634 (mapcar #'list (mapcar #'buffer-name blist))
17635 nil t))))
17637 (defun org-buffer-list (&optional predicate exclude-tmp)
17638 "Return a list of Org buffers.
17639 PREDICATE can be `export', `files' or `agenda'.
17641 export restrict the list to Export buffers.
17642 files restrict the list to buffers visiting Org files.
17643 agenda restrict the list to buffers visiting agenda files.
17645 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17646 (let* ((bfn nil)
17647 (agenda-files (and (eq predicate 'agenda)
17648 (mapcar 'file-truename (org-agenda-files t))))
17649 (filter
17650 (cond
17651 ((eq predicate 'files)
17652 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17653 ((eq predicate 'export)
17654 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17655 ((eq predicate 'agenda)
17656 (lambda (b)
17657 (with-current-buffer b
17658 (and (derived-mode-p 'org-mode)
17659 (setq bfn (buffer-file-name b))
17660 (member (file-truename bfn) agenda-files)))))
17661 (t (lambda (b) (with-current-buffer b
17662 (or (derived-mode-p 'org-mode)
17663 (string-match "\\*Org .*Export"
17664 (buffer-name b)))))))))
17665 (delq nil
17666 (mapcar
17667 (lambda(b)
17668 (if (and (funcall filter b)
17669 (or (not exclude-tmp)
17670 (not (string-match "tmp" (buffer-name b)))))
17672 nil))
17673 (buffer-list)))))
17675 (defun org-agenda-files (&optional unrestricted archives)
17676 "Get the list of agenda files.
17677 Optional UNRESTRICTED means return the full list even if a restriction
17678 is currently in place.
17679 When ARCHIVES is t, include all archive files that are really being
17680 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17681 `org-agenda-archives-mode' is t."
17682 (let ((files
17683 (cond
17684 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17685 ((stringp org-agenda-files) (org-read-agenda-file-list))
17686 ((listp org-agenda-files) org-agenda-files)
17687 (t (error "Invalid value of `org-agenda-files'")))))
17688 (setq files (apply 'append
17689 (mapcar (lambda (f)
17690 (if (file-directory-p f)
17691 (directory-files
17692 f t org-agenda-file-regexp)
17693 (list f)))
17694 files)))
17695 (when org-agenda-skip-unavailable-files
17696 (setq files (delq nil
17697 (mapcar (function
17698 (lambda (file)
17699 (and (file-readable-p file) file)))
17700 files))))
17701 (when (or (eq archives t)
17702 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17703 (setq files (org-add-archive-files files)))
17704 files))
17706 (defun org-agenda-file-p (&optional file)
17707 "Return non-nil, if FILE is an agenda file.
17708 If FILE is omitted, use the file associated with the current
17709 buffer."
17710 (let ((fname (or file (buffer-file-name))))
17711 (and fname
17712 (member (file-truename fname)
17713 (mapcar #'file-truename (org-agenda-files t))))))
17715 (defun org-edit-agenda-file-list ()
17716 "Edit the list of agenda files.
17717 Depending on setup, this either uses customize to edit the variable
17718 `org-agenda-files', or it visits the file that is holding the list. In the
17719 latter case, the buffer is set up in a way that saving it automatically kills
17720 the buffer and restores the previous window configuration."
17721 (interactive)
17722 (if (stringp org-agenda-files)
17723 (let ((cw (current-window-configuration)))
17724 (find-file org-agenda-files)
17725 (setq-local org-window-configuration cw)
17726 (add-hook 'after-save-hook
17727 (lambda ()
17728 (set-window-configuration
17729 (prog1 org-window-configuration
17730 (kill-buffer (current-buffer))))
17731 (org-install-agenda-files-menu)
17732 (message "New agenda file list installed"))
17733 nil 'local)
17734 (message "%s" (substitute-command-keys
17735 "Edit list and finish with \\[save-buffer]")))
17736 (customize-variable 'org-agenda-files)))
17738 (defun org-store-new-agenda-file-list (list)
17739 "Set new value for the agenda file list and save it correctly."
17740 (if (stringp org-agenda-files)
17741 (let ((fe (org-read-agenda-file-list t)) b u)
17742 (while (setq b (find-buffer-visiting org-agenda-files))
17743 (kill-buffer b))
17744 (with-temp-file org-agenda-files
17745 (insert
17746 (mapconcat
17747 (lambda (f) ;; Keep un-expanded entries.
17748 (if (setq u (assoc f fe))
17749 (cdr u)
17751 list "\n")
17752 "\n")))
17753 (let ((org-mode-hook nil) (org-inhibit-startup t)
17754 (org-insert-mode-line-in-empty-file nil))
17755 (setq org-agenda-files list)
17756 (customize-save-variable 'org-agenda-files org-agenda-files))))
17758 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17759 "Read the list of agenda files from a file.
17760 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17761 filenames, used by `org-store-new-agenda-file-list' to write back
17762 un-expanded file names."
17763 (when (file-directory-p org-agenda-files)
17764 (error "`org-agenda-files' cannot be a single directory"))
17765 (when (stringp org-agenda-files)
17766 (with-temp-buffer
17767 (insert-file-contents org-agenda-files)
17768 (mapcar
17769 (lambda (f)
17770 (let ((e (expand-file-name (substitute-in-file-name f)
17771 org-directory)))
17772 (if pair-with-expansion
17773 (cons e f)
17774 e)))
17775 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17777 ;;;###autoload
17778 (defun org-cycle-agenda-files ()
17779 "Cycle through the files in `org-agenda-files'.
17780 If the current buffer visits an agenda file, find the next one in the list.
17781 If the current buffer does not, find the first agenda file."
17782 (interactive)
17783 (let* ((fs (or (org-agenda-files t)
17784 (user-error "No agenda files")))
17785 (files (copy-sequence fs))
17786 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17787 file)
17788 (when tcf
17789 (while (and (setq file (pop files))
17790 (not (equal (file-truename file) tcf)))))
17791 (find-file (car (or files fs)))
17792 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17794 (defun org-agenda-file-to-front (&optional to-end)
17795 "Move/add the current file to the top of the agenda file list.
17796 If the file is not present in the list, it is added to the front. If it is
17797 present, it is moved there. With optional argument TO-END, add/move to the
17798 end of the list."
17799 (interactive "P")
17800 (let ((org-agenda-skip-unavailable-files nil)
17801 (file-alist (mapcar (lambda (x)
17802 (cons (file-truename x) x))
17803 (org-agenda-files t)))
17804 (ctf (file-truename
17805 (or buffer-file-name
17806 (user-error "Please save the current buffer to a file"))))
17807 x had)
17808 (setq x (assoc ctf file-alist) had x)
17810 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17811 (if to-end
17812 (setq file-alist (append (delq x file-alist) (list x)))
17813 (setq file-alist (cons x (delq x file-alist))))
17814 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17815 (org-install-agenda-files-menu)
17816 (message "File %s to %s of agenda file list"
17817 (if had "moved" "added") (if to-end "end" "front"))))
17819 (defun org-remove-file (&optional file)
17820 "Remove current file from the list of files in variable `org-agenda-files'.
17821 These are the files which are being checked for agenda entries.
17822 Optional argument FILE means use this file instead of the current."
17823 (interactive)
17824 (let* ((org-agenda-skip-unavailable-files nil)
17825 (file (or file buffer-file-name
17826 (user-error "Current buffer does not visit a file")))
17827 (true-file (file-truename file))
17828 (afile (abbreviate-file-name file))
17829 (files (delq nil (mapcar
17830 (lambda (x)
17831 (unless (equal true-file
17832 (file-truename x))
17834 (org-agenda-files t)))))
17835 (if (not (= (length files) (length (org-agenda-files t))))
17836 (progn
17837 (org-store-new-agenda-file-list files)
17838 (org-install-agenda-files-menu)
17839 (message "Removed from Org Agenda list: %s" afile))
17840 (message "File was not in list: %s (not removed)" afile))))
17842 (defun org-file-menu-entry (file)
17843 (vector file (list 'find-file file) t))
17845 (defun org-check-agenda-file (file)
17846 "Make sure FILE exists. If not, ask user what to do."
17847 (unless (file-exists-p file)
17848 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17849 (abbreviate-file-name file))
17850 (let ((r (downcase (read-char-exclusive))))
17851 (cond
17852 ((equal r ?r)
17853 (org-remove-file file)
17854 (throw 'nextfile t))
17855 (t (user-error "Abort"))))))
17857 (defun org-get-agenda-file-buffer (file)
17858 "Get an agenda buffer visiting FILE.
17859 If the buffer needs to be created, add it to the list of buffers
17860 which might be released later."
17861 (let ((buf (org-find-base-buffer-visiting file)))
17862 (if buf
17863 buf ; just return it
17864 ;; Make a new buffer and remember it
17865 (setq buf (find-file-noselect file))
17866 (when buf (push buf org-agenda-new-buffers))
17867 buf)))
17869 (defun org-release-buffers (blist)
17870 "Release all buffers in list, asking the user for confirmation when needed.
17871 When a buffer is unmodified, it is just killed. When modified, it is saved
17872 \(if the user agrees) and then killed."
17873 (let (file)
17874 (dolist (buf blist)
17875 (setq file (buffer-file-name buf))
17876 (when (and (buffer-modified-p buf)
17877 file
17878 (y-or-n-p (format "Save file %s? " file)))
17879 (with-current-buffer buf (save-buffer)))
17880 (kill-buffer buf))))
17882 (defun org-agenda-prepare-buffers (files)
17883 "Create buffers for all agenda files, protect archived trees and comments."
17884 (interactive)
17885 (let ((pa '(:org-archived t))
17886 (pc '(:org-comment t))
17887 (pall '(:org-archived t :org-comment t))
17888 (inhibit-read-only t)
17889 (org-inhibit-startup org-agenda-inhibit-startup)
17890 (rea (org-make-tag-string (list org-archive-tag)))
17891 re pos)
17892 (setq org-tag-alist-for-agenda nil
17893 org-tag-groups-alist-for-agenda nil)
17894 (save-excursion
17895 (save-restriction
17896 (dolist (file files)
17897 (catch 'nextfile
17898 (if (bufferp file)
17899 (set-buffer file)
17900 (org-check-agenda-file file)
17901 (set-buffer (org-get-agenda-file-buffer file)))
17902 (widen)
17903 (org-set-regexps-and-options 'tags-only)
17904 (setq pos (point))
17905 (or (memq 'category org-agenda-ignore-properties)
17906 (org-refresh-category-properties))
17907 (or (memq 'stats org-agenda-ignore-properties)
17908 (org-refresh-stats-properties))
17909 (or (memq 'effort org-agenda-ignore-properties)
17910 (org-refresh-effort-properties))
17911 (or (memq 'appt org-agenda-ignore-properties)
17912 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17913 (setq org-todo-keywords-for-agenda
17914 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17915 (setq org-done-keywords-for-agenda
17916 (append org-done-keywords-for-agenda org-done-keywords))
17917 (setq org-todo-keyword-alist-for-agenda
17918 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17919 (setq org-tag-alist-for-agenda
17920 (org--tag-add-to-alist
17921 org-tag-alist-for-agenda
17922 org-current-tag-alist))
17923 ;; Merge current file's tag groups into global
17924 ;; `org-tag-groups-alist-for-agenda'.
17925 (when org-group-tags
17926 (dolist (alist org-tag-groups-alist)
17927 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17928 (if old
17929 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17930 (push alist org-tag-groups-alist-for-agenda)))))
17931 (org-with-silent-modifications
17932 (save-excursion
17933 (remove-text-properties (point-min) (point-max) pall)
17934 (when org-agenda-skip-archived-trees
17935 (goto-char (point-min))
17936 (while (re-search-forward rea nil t)
17937 (when (org-at-heading-p t)
17938 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17939 (goto-char (point-min))
17940 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17941 (while (re-search-forward re nil t)
17942 (when (save-match-data (org-in-commented-heading-p t))
17943 (add-text-properties
17944 (match-beginning 0) (org-end-of-subtree t) pc)))))
17945 (goto-char pos)))))
17946 (setq org-todo-keywords-for-agenda
17947 (org-uniquify org-todo-keywords-for-agenda))
17948 (setq org-todo-keyword-alist-for-agenda
17949 (org-uniquify org-todo-keyword-alist-for-agenda))))
17952 ;;;; CDLaTeX minor mode
17954 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17955 "Keymap for the minor `org-cdlatex-mode'.")
17957 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17958 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17959 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17960 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17961 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
17963 (defvar org-cdlatex-texmathp-advice-is-done nil
17964 "Flag remembering if we have applied the advice to texmathp already.")
17966 (define-minor-mode org-cdlatex-mode
17967 "Toggle the minor `org-cdlatex-mode'.
17968 This mode supports entering LaTeX environment and math in LaTeX fragments
17969 in Org mode.
17970 \\{org-cdlatex-mode-map}"
17971 nil " OCDL" nil
17972 (when org-cdlatex-mode
17973 (require 'cdlatex)
17974 (run-hooks 'cdlatex-mode-hook)
17975 (cdlatex-compute-tables))
17976 (unless org-cdlatex-texmathp-advice-is-done
17977 (setq org-cdlatex-texmathp-advice-is-done t)
17978 (defadvice texmathp (around org-math-always-on activate)
17979 "Always return t in Org buffers.
17980 This is because we want to insert math symbols without dollars even outside
17981 the LaTeX math segments. If Org mode thinks that point is actually inside
17982 an embedded LaTeX fragment, let `texmathp' do its job.
17983 `\\[org-cdlatex-mode-map]'"
17984 (interactive)
17985 (let (p)
17986 (cond
17987 ((not (derived-mode-p 'org-mode)) ad-do-it)
17988 ((eq this-command 'cdlatex-math-symbol)
17989 (setq ad-return-value t
17990 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17992 (let ((p (org-inside-LaTeX-fragment-p)))
17993 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17994 (setq ad-return-value t
17995 texmathp-why '("Org mode embedded math" . 0))
17996 (when p ad-do-it)))))))))
17998 (defun turn-on-org-cdlatex ()
17999 "Unconditionally turn on `org-cdlatex-mode'."
18000 (org-cdlatex-mode 1))
18002 (defun org-try-cdlatex-tab ()
18003 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18004 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18005 - inside a LaTeX fragment, or
18006 - after the first word in a line, where an abbreviation expansion could
18007 insert a LaTeX environment."
18008 (when org-cdlatex-mode
18009 (cond
18010 ;; Before any word on the line: No expansion possible.
18011 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18012 ;; Just after first word on the line: Expand it. Make sure it
18013 ;; cannot happen on headlines, though.
18014 ((save-excursion
18015 (skip-chars-backward "a-zA-Z0-9*")
18016 (skip-chars-backward " \t")
18017 (and (bolp) (not (org-at-heading-p))))
18018 (cdlatex-tab) t)
18019 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18021 (defun org-cdlatex-underscore-caret (&optional _arg)
18022 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18023 Revert to the normal definition outside of these fragments."
18024 (interactive "P")
18025 (if (org-inside-LaTeX-fragment-p)
18026 (call-interactively 'cdlatex-sub-superscript)
18027 (let (org-cdlatex-mode)
18028 (call-interactively (key-binding (vector last-input-event))))))
18030 (defun org-cdlatex-math-modify (&optional _arg)
18031 "Execute `cdlatex-math-modify' in LaTeX fragments.
18032 Revert to the normal definition outside of these fragments."
18033 (interactive "P")
18034 (if (org-inside-LaTeX-fragment-p)
18035 (call-interactively 'cdlatex-math-modify)
18036 (let (org-cdlatex-mode)
18037 (call-interactively (key-binding (vector last-input-event))))))
18039 (defun org-cdlatex-environment-indent (&optional environment item)
18040 "Execute `cdlatex-environment' and indent the inserted environment.
18042 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18044 The inserted environment is indented to current indentation
18045 unless point is at the beginning of the line, in which the
18046 environment remains unintended."
18047 (interactive)
18048 ;; cdlatex-environment always return nil. Therefore, capture output
18049 ;; first and determine if an environment was selected.
18050 (let* ((beg (point-marker))
18051 (end (copy-marker (point) t))
18052 (inserted (progn
18053 (ignore-errors (cdlatex-environment environment item))
18054 (< beg end)))
18055 ;; Figure out how many lines to move forward after the
18056 ;; environment has been inserted.
18057 (lines (when inserted
18058 (save-excursion
18059 (- (cl-loop while (< beg (point))
18060 with x = 0
18061 do (forward-line -1)
18062 (cl-incf x)
18063 finally return x)
18064 (if (progn (goto-char beg)
18065 (and (progn (skip-chars-forward " \t") (eolp))
18066 (progn (skip-chars-backward " \t") (bolp))))
18067 1 0)))))
18068 (env (org-trim (delete-and-extract-region beg end))))
18069 (when inserted
18070 ;; Get indentation of next line unless at column 0.
18071 (let ((ind (if (bolp) 0
18072 (save-excursion
18073 (org-return-indent)
18074 (prog1 (org-get-indentation)
18075 (when (progn (skip-chars-forward " \t") (eolp))
18076 (delete-region beg (point)))))))
18077 (bol (progn (skip-chars-backward " \t") (bolp))))
18078 ;; Insert a newline before environment unless at column zero
18079 ;; to "escape" the current line. Insert a newline if
18080 ;; something is one the same line as \end{ENVIRONMENT}.
18081 (insert
18082 (concat (unless bol "\n") env
18083 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18084 (unless (zerop ind)
18085 (save-excursion
18086 (goto-char beg)
18087 (while (< (point) end)
18088 (unless (eolp) (indent-line-to ind))
18089 (forward-line))))
18090 (goto-char beg)
18091 (forward-line lines)
18092 (indent-line-to ind)))
18093 (set-marker beg nil)
18094 (set-marker end nil)))
18097 ;;;; LaTeX fragments
18099 (defun org-inside-LaTeX-fragment-p ()
18100 "Test if point is inside a LaTeX fragment.
18101 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18102 sequence appearing also before point.
18103 Even though the matchers for math are configurable, this function assumes
18104 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18105 delimiters are skipped when they have been removed by customization.
18106 The return value is nil, or a cons cell with the delimiter and the
18107 position of this delimiter.
18109 This function does a reasonably good job, but can locally be fooled by
18110 for example currency specifications. For example it will assume being in
18111 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18112 fragments that are properly closed, but during editing, we have to live
18113 with the uncertainty caused by missing closing delimiters. This function
18114 looks only before point, not after."
18115 (catch 'exit
18116 (let ((pos (point))
18117 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18118 (lim (save-excursion (org-backward-paragraph) (point)))
18119 dd-on str (start 0) m re)
18120 (goto-char pos)
18121 (when dodollar
18122 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18123 re (nth 1 (assoc "$" org-latex-regexps)))
18124 (while (string-match re str start)
18125 (cond
18126 ((= (match-end 0) (length str))
18127 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18128 ((= (match-end 0) (- (length str) 5))
18129 (throw 'exit nil))
18130 (t (setq start (match-end 0))))))
18131 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18132 (goto-char pos)
18133 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18134 (and (match-beginning 2) (throw 'exit nil))
18135 ;; count $$
18136 (while (re-search-backward "\\$\\$" lim t)
18137 (setq dd-on (not dd-on)))
18138 (goto-char pos)
18139 (when dd-on (cons "$$" m))))))
18141 (defun org-inside-latex-macro-p ()
18142 "Is point inside a LaTeX macro or its arguments?"
18143 (save-match-data
18144 (org-in-regexp
18145 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18147 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18148 "Build an overlay between BEG and END using IMAGE file.
18149 Argument IMAGETYPE is the extension of the displayed image,
18150 as a string. It defaults to \"png\"."
18151 (let ((ov (make-overlay beg end))
18152 (imagetype (or (intern imagetype) 'png)))
18153 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18154 (overlay-put ov 'evaporate t)
18155 (overlay-put ov
18156 'modification-hooks
18157 (list (lambda (o _flag _beg _end &optional _l)
18158 (delete-overlay o))))
18159 (overlay-put ov
18160 'display
18161 (list 'image :type imagetype :file image :ascent 'center))))
18163 (defun org--list-latex-overlays (&optional beg end)
18164 "List all Org LaTeX overlays in current buffer.
18165 Limit to overlays between BEG and END when those are provided."
18166 (cl-remove-if-not
18167 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18168 (overlays-in (or beg (point-min)) (or end (point-max)))))
18170 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18171 "Remove all overlays with LaTeX fragment images in current buffer.
18172 When optional arguments BEG and END are non-nil, remove all
18173 overlays between them instead. Return a non-nil value when some
18174 overlays were removed, nil otherwise."
18175 (let ((overlays (org--list-latex-overlays beg end)))
18176 (mapc #'delete-overlay overlays)
18177 overlays))
18179 (defun org-toggle-latex-fragment (&optional arg)
18180 "Preview the LaTeX fragment at point, or all locally or globally.
18182 If the cursor is on a LaTeX fragment, create the image and overlay
18183 it over the source code, if there is none. Remove it otherwise.
18184 If there is no fragment at point, display all fragments in the
18185 current section.
18187 With prefix ARG, preview or clear image for all fragments in the
18188 current subtree or in the whole buffer when used before the first
18189 headline. With a prefix ARG `\\[universal-argument] \
18190 \\[universal-argument]' preview or clear images
18191 for all fragments in the buffer."
18192 (interactive "P")
18193 (when (display-graphic-p)
18194 (catch 'exit
18195 (save-excursion
18196 (let (beg end msg)
18197 (cond
18198 ((or (equal arg '(16))
18199 (and (equal arg '(4))
18200 (org-with-limited-levels (org-before-first-heading-p))))
18201 (if (org-remove-latex-fragment-image-overlays)
18202 (progn (message "LaTeX fragments images removed from buffer")
18203 (throw 'exit nil))
18204 (setq msg "Creating images for buffer...")))
18205 ((equal arg '(4))
18206 (org-with-limited-levels (org-back-to-heading t))
18207 (setq beg (point))
18208 (setq end (progn (org-end-of-subtree t) (point)))
18209 (if (org-remove-latex-fragment-image-overlays beg end)
18210 (progn
18211 (message "LaTeX fragment images removed from subtree")
18212 (throw 'exit nil))
18213 (setq msg "Creating images for subtree...")))
18214 ((let ((datum (org-element-context)))
18215 (when (memq (org-element-type datum)
18216 '(latex-environment latex-fragment))
18217 (setq beg (org-element-property :begin datum))
18218 (setq end (org-element-property :end datum))
18219 (if (org-remove-latex-fragment-image-overlays beg end)
18220 (progn (message "LaTeX fragment image removed")
18221 (throw 'exit nil))
18222 (setq msg "Creating image...")))))
18224 (org-with-limited-levels
18225 (setq beg (if (org-at-heading-p) (line-beginning-position)
18226 (outline-previous-heading)
18227 (point)))
18228 (setq end (progn (outline-next-heading) (point)))
18229 (if (org-remove-latex-fragment-image-overlays beg end)
18230 (progn
18231 (message "LaTeX fragment images removed from section")
18232 (throw 'exit nil))
18233 (setq msg "Creating images for section...")))))
18234 (let ((file (buffer-file-name (buffer-base-buffer))))
18235 (org-format-latex
18236 (concat org-preview-latex-image-directory "org-ltximg")
18237 beg end
18238 ;; Emacs cannot overlay images from remote hosts. Create
18239 ;; it in `temporary-file-directory' instead.
18240 (if (or (not file) (file-remote-p file))
18241 temporary-file-directory
18242 default-directory)
18243 'overlays msg 'forbuffer org-preview-latex-default-process))
18244 (message (concat msg "done")))))))
18246 (defun org-format-latex
18247 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18248 "Replace LaTeX fragments with links to an image.
18250 The function takes care of creating the replacement image.
18252 Only consider fragments between BEG and END when those are
18253 provided.
18255 When optional argument OVERLAYS is non-nil, display the image on
18256 top of the fragment instead of replacing it.
18258 PROCESSING-TYPE is the conversion method to use, as a symbol.
18260 Some of the options can be changed using the variable
18261 `org-format-latex-options', which see."
18262 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18263 (unless (eq processing-type 'verbatim)
18264 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18265 (cnt 0)
18266 checkdir-flag)
18267 (goto-char (or beg (point-min)))
18268 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18269 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18270 (overlay-recenter (or end (point-max))))
18271 (while (re-search-forward math-regexp end t)
18272 (unless (and overlays
18273 (eq (get-char-property (point) 'org-overlay-type)
18274 'org-latex-overlay))
18275 (let* ((context (org-element-context))
18276 (type (org-element-type context)))
18277 (when (memq type '(latex-environment latex-fragment))
18278 (let ((block-type (eq type 'latex-environment))
18279 (value (org-element-property :value context))
18280 (beg (org-element-property :begin context))
18281 (end (save-excursion
18282 (goto-char (org-element-property :end context))
18283 (skip-chars-backward " \r\t\n")
18284 (point))))
18285 (cond
18286 ((eq processing-type 'mathjax)
18287 ;; Prepare for MathJax processing.
18288 (if (not (string-match "\\`\\$\\$?" value))
18289 (goto-char end)
18290 (delete-region beg end)
18291 (if (string= (match-string 0 value) "$$")
18292 (insert "\\[" (substring value 2 -2) "\\]")
18293 (insert "\\(" (substring value 1 -1) "\\)"))))
18294 ((assq processing-type org-preview-latex-process-alist)
18295 ;; Process to an image.
18296 (cl-incf cnt)
18297 (goto-char beg)
18298 (let* ((processing-info
18299 (cdr (assq processing-type org-preview-latex-process-alist)))
18300 (face (face-at-point))
18301 ;; Get the colors from the face at point.
18303 (let ((color (plist-get org-format-latex-options
18304 :foreground)))
18305 (if (and forbuffer (eq color 'auto))
18306 (face-attribute face :foreground nil 'default)
18307 color)))
18309 (let ((color (plist-get org-format-latex-options
18310 :background)))
18311 (if (and forbuffer (eq color 'auto))
18312 (face-attribute face :background nil 'default)
18313 color)))
18314 (hash (sha1 (prin1-to-string
18315 (list org-format-latex-header
18316 org-latex-default-packages-alist
18317 org-latex-packages-alist
18318 org-format-latex-options
18319 forbuffer value fg bg))))
18320 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18321 (absprefix (expand-file-name prefix dir))
18322 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18323 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18324 (sep (and block-type "\n\n"))
18325 (link (concat sep "[[file:" linkfile "]]" sep))
18326 (options
18327 (org-combine-plists
18328 org-format-latex-options
18329 `(:foreground ,fg :background ,bg))))
18330 (when msg (message msg cnt))
18331 (unless checkdir-flag ; Ensure the directory exists.
18332 (setq checkdir-flag t)
18333 (let ((todir (file-name-directory absprefix)))
18334 (unless (file-directory-p todir)
18335 (make-directory todir t))))
18336 (unless (file-exists-p movefile)
18337 (org-create-formula-image
18338 value movefile options forbuffer processing-type))
18339 (if overlays
18340 (progn
18341 (dolist (o (overlays-in beg end))
18342 (when (eq (overlay-get o 'org-overlay-type)
18343 'org-latex-overlay)
18344 (delete-overlay o)))
18345 (org--format-latex-make-overlay beg end movefile imagetype)
18346 (goto-char end))
18347 (delete-region beg end)
18348 (insert
18349 (org-add-props link
18350 (list 'org-latex-src
18351 (replace-regexp-in-string "\"" "" value)
18352 'org-latex-src-embed-type
18353 (if block-type 'paragraph 'character)))))))
18354 ((eq processing-type 'mathml)
18355 ;; Process to MathML.
18356 (unless (org-format-latex-mathml-available-p)
18357 (user-error "LaTeX to MathML converter not configured"))
18358 (cl-incf cnt)
18359 (when msg (message msg cnt))
18360 (goto-char beg)
18361 (delete-region beg end)
18362 (insert (org-format-latex-as-mathml
18363 value block-type prefix dir)))
18365 (error "Unknown conversion process %s for LaTeX fragments"
18366 processing-type)))))))))))
18368 (defun org-create-math-formula (latex-frag &optional mathml-file)
18369 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18370 Use `org-latex-to-mathml-convert-command'. If the conversion is
18371 sucessful, return the portion between \"<math...> </math>\"
18372 elements otherwise return nil. When MATHML-FILE is specified,
18373 write the results in to that file. When invoked as an
18374 interactive command, prompt for LATEX-FRAG, with initial value
18375 set to the current active region and echo the results for user
18376 inspection."
18377 (interactive (list (let ((frag (when (org-region-active-p)
18378 (buffer-substring-no-properties
18379 (region-beginning) (region-end)))))
18380 (read-string "LaTeX Fragment: " frag nil frag))))
18381 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18382 (let* ((tmp-in-file
18383 (let ((file (file-relative-name
18384 (make-temp-name (expand-file-name "ltxmathml-in")))))
18385 (write-region latex-frag nil file)
18386 file))
18387 (tmp-out-file (file-relative-name
18388 (make-temp-name (expand-file-name "ltxmathml-out"))))
18389 (cmd (format-spec
18390 org-latex-to-mathml-convert-command
18391 `((?j . ,(and org-latex-to-mathml-jar-file
18392 (shell-quote-argument
18393 (expand-file-name
18394 org-latex-to-mathml-jar-file))))
18395 (?I . ,(shell-quote-argument tmp-in-file))
18396 (?i . ,latex-frag)
18397 (?o . ,(shell-quote-argument tmp-out-file)))))
18398 mathml shell-command-output)
18399 (when (called-interactively-p 'any)
18400 (unless (org-format-latex-mathml-available-p)
18401 (user-error "LaTeX to MathML converter not configured")))
18402 (message "Running %s" cmd)
18403 (setq shell-command-output (shell-command-to-string cmd))
18404 (setq mathml
18405 (when (file-readable-p tmp-out-file)
18406 (with-current-buffer (find-file-noselect tmp-out-file t)
18407 (goto-char (point-min))
18408 (when (re-search-forward
18409 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18410 (regexp-quote
18411 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18412 nil t)
18413 (prog1 (match-string 0) (kill-buffer))))))
18414 (cond
18415 (mathml
18416 (setq mathml
18417 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18418 (when mathml-file
18419 (write-region mathml nil mathml-file))
18420 (when (called-interactively-p 'any)
18421 (message mathml)))
18422 ((message "LaTeX to MathML conversion failed")
18423 (message shell-command-output)))
18424 (delete-file tmp-in-file)
18425 (when (file-exists-p tmp-out-file)
18426 (delete-file tmp-out-file))
18427 mathml))
18429 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18430 prefix &optional dir)
18431 "Use `org-create-math-formula' but check local cache first."
18432 (let* ((absprefix (expand-file-name prefix dir))
18433 (print-length nil) (print-level nil)
18434 (formula-id (concat
18435 "formula-"
18436 (sha1
18437 (prin1-to-string
18438 (list latex-frag
18439 org-latex-to-mathml-convert-command)))))
18440 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18441 (formula-cache-dir (file-name-directory formula-cache)))
18443 (unless (file-directory-p formula-cache-dir)
18444 (make-directory formula-cache-dir t))
18446 (unless (file-exists-p formula-cache)
18447 (org-create-math-formula latex-frag formula-cache))
18449 (if (file-exists-p formula-cache)
18450 ;; Successful conversion. Return the link to MathML file.
18451 (org-add-props
18452 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18453 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18454 'org-latex-src-embed-type (if latex-frag-type
18455 'paragraph 'character)))
18456 ;; Failed conversion. Return the LaTeX fragment verbatim
18457 latex-frag)))
18459 (defun org--get-display-dpi ()
18460 "Get the DPI of the display.
18461 The function assumes that the display has the same pixel width in
18462 the horizontal and vertical directions."
18463 (if (display-graphic-p)
18464 (round (/ (display-pixel-height)
18465 (/ (display-mm-height) 25.4)))
18466 (error "Attempt to calculate the dpi of a non-graphic display")))
18468 (defun org-create-formula-image
18469 (string tofile options buffer &optional processing-type)
18470 "Create an image from LaTeX source using external processes.
18472 The LaTeX STRING is saved to a temporary LaTeX file, then
18473 converted to an image file by process PROCESSING-TYPE defined in
18474 `org-preview-latex-process-alist'. A nil value defaults to
18475 `org-preview-latex-default-process'.
18477 The generated image file is eventually moved to TOFILE.
18479 The OPTIONS argument controls the size, foreground color and
18480 background color of the generated image.
18482 When BUFFER non-nil, this function is used for LaTeX previewing.
18483 Otherwise, it is used to deal with LaTeX snippets showed in
18484 a HTML file."
18485 (let* ((processing-type (or processing-type
18486 org-preview-latex-default-process))
18487 (processing-info
18488 (cdr (assq processing-type org-preview-latex-process-alist)))
18489 (programs (plist-get processing-info :programs))
18490 (error-message (or (plist-get processing-info :message) ""))
18491 (use-xcolor (plist-get processing-info :use-xcolor))
18492 (image-input-type (plist-get processing-info :image-input-type))
18493 (image-output-type (plist-get processing-info :image-output-type))
18494 (post-clean (or (plist-get processing-info :post-clean)
18495 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18496 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18497 (latex-header
18498 (or (plist-get processing-info :latex-header)
18499 (org-latex-make-preamble
18500 (org-export-get-environment (org-export-get-backend 'latex))
18501 org-format-latex-header
18502 'snippet)))
18503 (latex-compiler (plist-get processing-info :latex-compiler))
18504 (image-converter (plist-get processing-info :image-converter))
18505 (tmpdir temporary-file-directory)
18506 (texfilebase (make-temp-name
18507 (expand-file-name "orgtex" tmpdir)))
18508 (texfile (concat texfilebase ".tex"))
18509 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18510 '(1.0 . 1.0)))
18511 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18512 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18513 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18514 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18515 "Black"))
18516 (bg (or (plist-get options (if buffer :background :html-background))
18517 "Transparent"))
18518 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18519 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18520 (dolist (program programs)
18521 (org-check-external-command program error-message))
18522 (if use-xcolor
18523 (progn (if (eq fg 'default)
18524 (setq fg (org-latex-color :foreground))
18525 (setq fg (org-latex-color-format fg)))
18526 (if (eq bg 'default)
18527 (setq bg (org-latex-color :background))
18528 (setq bg (org-latex-color-format
18529 (if (string= bg "Transparent") "white" bg))))
18530 (with-temp-file texfile
18531 (insert latex-header)
18532 (insert "\n\\begin{document}\n"
18533 "\\definecolor{fg}{rgb}{" fg "}\n"
18534 "\\definecolor{bg}{rgb}{" bg "}\n"
18535 "\n\\pagecolor{bg}\n"
18536 "\n{\\color{fg}\n"
18537 string
18538 "\n}\n"
18539 "\n\\end{document}\n")))
18540 (if (eq fg 'default)
18541 (setq fg (org-dvipng-color :foreground))
18542 (unless (string= fg "Transparent")
18543 (setq fg (org-dvipng-color-format fg))))
18544 (if (eq bg 'default)
18545 (setq bg (org-dvipng-color :background))
18546 (unless (string= bg "Transparent")
18547 (setq bg (org-dvipng-color-format bg))))
18548 (with-temp-file texfile
18549 (insert latex-header)
18550 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18552 (let* ((err-msg (format "Please adjust `%s' part of \
18553 `org-preview-latex-process-alist'."
18554 processing-type))
18555 (image-input-file
18556 (org-compile-file
18557 texfile latex-compiler image-input-type err-msg log-buf))
18558 (image-output-file
18559 (org-compile-file
18560 image-input-file image-converter image-output-type err-msg log-buf
18561 `((?F . ,(shell-quote-argument fg))
18562 (?B . ,(shell-quote-argument bg))
18563 (?D . ,(shell-quote-argument (format "%s" dpi)))
18564 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18565 (copy-file image-output-file tofile 'replace)
18566 (dolist (e post-clean)
18567 (when (file-exists-p (concat texfilebase e))
18568 (delete-file (concat texfilebase e))))
18569 image-output-file)))
18571 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18572 "Fill a LaTeX header template TPL.
18573 In the template, the following place holders will be recognized:
18575 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18576 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18577 [PACKAGES] \\usepackage statements for PKG
18578 [NO-PACKAGES] do not include PKG
18579 [EXTRA] the string EXTRA
18580 [NO-EXTRA] do not include EXTRA
18582 For backward compatibility, if both the positive and the negative place
18583 holder is missing, the positive one (without the \"NO-\") will be
18584 assumed to be present at the end of the template.
18585 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18586 EXTRA is a string.
18587 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18588 (let (rpl (end ""))
18589 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18590 (setq rpl (if (or (match-end 1) (not def-pkg))
18591 "" (org-latex-packages-to-string def-pkg snippets-p t))
18592 tpl (replace-match rpl t t tpl))
18593 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18595 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18596 (setq rpl (if (or (match-end 1) (not pkg))
18597 "" (org-latex-packages-to-string pkg snippets-p t))
18598 tpl (replace-match rpl t t tpl))
18599 (when pkg (setq end
18600 (concat end "\n"
18601 (org-latex-packages-to-string pkg snippets-p)))))
18603 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18604 (setq rpl (if (or (match-end 1) (not extra))
18605 "" (concat extra "\n"))
18606 tpl (replace-match rpl t t tpl))
18607 (when (and extra (string-match "\\S-" extra))
18608 (setq end (concat end "\n" extra))))
18610 (if (string-match "\\S-" end)
18611 (concat tpl "\n" end)
18612 tpl)))
18614 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18615 "Turn an alist of packages into a string with the \\usepackage macros."
18616 (setq pkg (mapconcat (lambda(p)
18617 (cond
18618 ((stringp p) p)
18619 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18620 (format "%% Package %s omitted" (cadr p)))
18621 ((equal "" (car p))
18622 (format "\\usepackage{%s}" (cadr p)))
18624 (format "\\usepackage[%s]{%s}"
18625 (car p) (cadr p)))))
18627 "\n"))
18628 (if newline (concat pkg "\n") pkg))
18630 (defun org-dvipng-color (attr)
18631 "Return a RGB color specification for dvipng."
18632 (org-dvipng-color-format (face-attribute 'default attr nil)))
18634 (defun org-dvipng-color-format (color-name)
18635 "Convert COLOR-NAME to a RGB color value for dvipng."
18636 (apply #'format "rgb %s %s %s"
18637 (mapcar 'org-normalize-color
18638 (color-values color-name))))
18640 (defun org-latex-color (attr)
18641 "Return a RGB color for the LaTeX color package."
18642 (org-latex-color-format (face-attribute 'default attr nil)))
18644 (defun org-latex-color-format (color-name)
18645 "Convert COLOR-NAME to a RGB color value."
18646 (apply #'format "%s,%s,%s"
18647 (mapcar 'org-normalize-color
18648 (color-values color-name))))
18650 (defun org-normalize-color (value)
18651 "Return string to be used as color value for an RGB component."
18652 (format "%g" (/ value 65535.0)))
18655 ;; Image display
18657 (defvar-local org-inline-image-overlays nil)
18659 (defun org-toggle-inline-images (&optional include-linked)
18660 "Toggle the display of inline images.
18661 INCLUDE-LINKED is passed to `org-display-inline-images'."
18662 (interactive "P")
18663 (if org-inline-image-overlays
18664 (progn
18665 (org-remove-inline-images)
18666 (when (called-interactively-p 'interactive)
18667 (message "Inline image display turned off")))
18668 (org-display-inline-images include-linked)
18669 (when (called-interactively-p 'interactive)
18670 (message (if org-inline-image-overlays
18671 (format "%d images displayed inline"
18672 (length org-inline-image-overlays))
18673 "No images to display inline")))))
18675 (defun org-redisplay-inline-images ()
18676 "Refresh the display of inline images."
18677 (interactive)
18678 (if (not org-inline-image-overlays)
18679 (org-toggle-inline-images)
18680 (org-toggle-inline-images)
18681 (org-toggle-inline-images)))
18683 (defun org-display-inline-images (&optional include-linked refresh beg end)
18684 "Display inline images.
18686 An inline image is a link which follows either of these
18687 conventions:
18689 1. Its path is a file with an extension matching return value
18690 from `image-file-name-regexp' and it has no contents.
18692 2. Its description consists in a single link of the previous
18693 type.
18695 When optional argument INCLUDE-LINKED is non-nil, also links with
18696 a text description part will be inlined. This can be nice for
18697 a quick look at those images, but it does not reflect what
18698 exported files will look like.
18700 When optional argument REFRESH is non-nil, refresh existing
18701 images between BEG and END. This will create new image displays
18702 only if necessary. BEG and END default to the buffer
18703 boundaries."
18704 (interactive "P")
18705 (when (display-graphic-p)
18706 (unless refresh
18707 (org-remove-inline-images)
18708 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18709 (org-with-wide-buffer
18710 (goto-char (or beg (point-min)))
18711 (let* ((case-fold-search t)
18712 (file-extension-re (image-file-name-regexp))
18713 (link-abbrevs (mapcar #'car
18714 (append org-link-abbrev-alist-local
18715 org-link-abbrev-alist)))
18716 ;; Check absolute, relative file names and explicit
18717 ;; "file:" links. Also check link abbreviations since
18718 ;; some might expand to "file" links.
18719 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18720 (if (not link-abbrevs) ""
18721 (format "\\|\\(?:%s:\\)"
18722 (regexp-opt link-abbrevs))))))
18723 (while (re-search-forward file-types-re end t)
18724 (let ((link (save-match-data (org-element-context))))
18725 ;; Check if we're at an inline image, i.e., an image file
18726 ;; link without a description (unless INCLUDE-LINKED is
18727 ;; non-nil).
18728 (when (and (equal "file" (org-element-property :type link))
18729 (or include-linked
18730 (null (org-element-contents link)))
18731 (string-match-p file-extension-re
18732 (org-element-property :path link)))
18733 (let ((file (expand-file-name
18734 (org-link-unescape
18735 (org-element-property :path link)))))
18736 (when (file-exists-p file)
18737 (let ((width
18738 ;; Apply `org-image-actual-width' specifications.
18739 (cond
18740 ((not (image-type-available-p 'imagemagick)) nil)
18741 ((eq org-image-actual-width t) nil)
18742 ((listp org-image-actual-width)
18744 ;; First try to find a width among
18745 ;; attributes associated to the paragraph
18746 ;; containing link.
18747 (let ((paragraph
18748 (let ((e link))
18749 (while (and (setq e (org-element-property
18750 :parent e))
18751 (not (eq (org-element-type e)
18752 'paragraph))))
18753 e)))
18754 (when paragraph
18755 (save-excursion
18756 (goto-char (org-element-property :begin paragraph))
18757 (when
18758 (re-search-forward
18759 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18760 (org-element-property
18761 :post-affiliated paragraph)
18763 (string-to-number (match-string 1))))))
18764 ;; Otherwise, fall-back to provided number.
18765 (car org-image-actual-width)))
18766 ((numberp org-image-actual-width)
18767 org-image-actual-width)))
18768 (old (get-char-property-and-overlay
18769 (org-element-property :begin link)
18770 'org-image-overlay)))
18771 (if (and (car-safe old) refresh)
18772 (image-refresh (overlay-get (cdr old) 'display))
18773 (let ((image (create-image file
18774 (and width 'imagemagick)
18776 :width width)))
18777 (when image
18778 (let ((ov (make-overlay
18779 (org-element-property :begin link)
18780 (progn
18781 (goto-char
18782 (org-element-property :end link))
18783 (skip-chars-backward " \t")
18784 (point)))))
18785 (overlay-put ov 'display image)
18786 (overlay-put ov 'face 'default)
18787 (overlay-put ov 'org-image-overlay t)
18788 (overlay-put
18789 ov 'modification-hooks
18790 (list 'org-display-inline-remove-overlay))
18791 (push ov org-inline-image-overlays)))))))))))))))
18793 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18794 "Remove inline-display overlay if a corresponding region is modified."
18795 (let ((inhibit-modification-hooks t))
18796 (when (and ov after)
18797 (delete ov org-inline-image-overlays)
18798 (delete-overlay ov))))
18800 (defun org-remove-inline-images ()
18801 "Remove inline display of images."
18802 (interactive)
18803 (mapc #'delete-overlay org-inline-image-overlays)
18804 (setq org-inline-image-overlays nil))
18807 ;;; Key bindings
18809 (defun org-remap (map &rest commands)
18810 "In MAP, remap the functions given in COMMANDS.
18811 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18812 (let (new old)
18813 (while commands
18814 (setq old (pop commands) new (pop commands))
18815 (org-defkey map (vector 'remap old) new))))
18817 ;;;; Outline functions that can be remapped in Org
18818 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18819 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18820 (define-key org-mode-map [remap outline-forward-same-level]
18821 #'org-forward-heading-same-level)
18822 (define-key org-mode-map [remap outline-backward-same-level]
18823 #'org-backward-heading-same-level)
18824 (define-key org-mode-map [remap outline-show-branches]
18825 #'org-kill-note-or-show-branches)
18826 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18827 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18828 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18829 (define-key org-mode-map [remap outline-next-visible-heading]
18830 #'org-next-visible-heading)
18831 (define-key org-mode-map [remap outline-previous-visible-heading]
18832 #'org-previous-visible-heading)
18833 (define-key org-mode-map [remap show-children] #'org-show-children)
18835 ;;;; Make `C-c C-x' a prefix key
18836 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18838 ;;;; TAB key with modifiers
18839 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18840 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18841 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18842 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18843 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18845 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18846 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18847 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18849 ;;;; RET key with modifiers
18850 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18851 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18852 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18853 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18854 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18856 ;;;; Cursor keys with modifiers
18857 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18858 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18859 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18860 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18861 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18862 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18863 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18865 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18866 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18867 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18868 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18869 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18870 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18871 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18872 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18873 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18874 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18876 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18877 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18878 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18879 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18881 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18882 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18883 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18884 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18886 ;;;; Babel keys
18887 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18888 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18889 (define-key org-babel-map key def))
18891 ;;;; Extra keys for TTY access.
18893 ;; We only set them when really needed because otherwise the
18894 ;; menus don't show the simple keys
18896 (when (or org-use-extra-keys (not window-system))
18897 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18898 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18899 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18900 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18901 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18902 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18903 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18904 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18905 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18906 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18907 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18908 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18909 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18910 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18911 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18912 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18913 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18914 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18915 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18916 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18917 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18919 ;;;; Narrow map
18920 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18921 (org-defkey narrow-map "b" #'org-narrow-to-block)
18922 (org-defkey narrow-map "e" #'org-narrow-to-element)
18924 ;;;; Remap usual Emacs bindings
18925 (org-remap org-mode-map
18926 'self-insert-command 'org-self-insert-command
18927 'delete-char 'org-delete-char
18928 'delete-backward-char 'org-delete-backward-char
18929 'kill-line 'org-kill-line
18930 'open-line 'org-open-line
18931 'yank 'org-yank
18932 'comment-dwim 'org-comment-dwim
18933 'move-beginning-of-line 'org-beginning-of-line
18934 'move-end-of-line 'org-end-of-line
18935 'forward-paragraph 'org-forward-paragraph
18936 'backward-paragraph 'org-backward-paragraph
18937 'backward-sentence 'org-backward-sentence
18938 'forward-sentence 'org-forward-sentence
18939 'fill-paragraph 'org-fill-paragraph
18940 'delete-indentation 'org-delete-indentation
18941 'transpose-words 'org-transpose-words)
18943 ;;;; All the other keys
18944 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18945 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18946 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18947 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18948 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18949 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18950 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18951 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18952 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18953 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18954 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18955 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18956 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18957 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18958 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18959 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18960 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18961 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18962 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18963 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18964 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18965 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18966 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18967 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18968 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18969 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18970 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18971 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18972 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18973 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18974 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18975 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18976 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18977 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18978 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18979 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18980 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18981 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18982 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18983 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18984 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18985 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
18986 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
18987 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
18988 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
18989 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
18990 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
18991 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
18992 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
18993 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
18994 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
18995 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
18996 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
18997 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
18998 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
18999 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19000 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19001 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19002 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19003 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19004 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19005 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19006 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19007 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19008 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19009 (org-defkey org-mode-map (kbd "RET") #'org-return)
19010 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19011 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19012 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19013 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19014 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19015 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19016 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19017 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19018 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19019 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19020 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19021 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19022 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19023 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19024 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19025 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19026 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19027 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19028 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19029 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19030 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19031 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19032 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19034 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19035 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19036 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19038 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19039 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19040 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19041 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19042 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19043 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19044 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19045 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19046 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19047 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19048 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19049 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19050 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19051 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19052 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19053 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19054 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19055 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19056 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19057 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19058 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19059 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19060 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19061 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19062 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19063 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19064 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19065 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19067 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19069 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19071 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19072 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19074 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19077 ;;; Speed commands
19079 (defconst org-speed-commands-default
19081 ("Outline Navigation")
19082 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19083 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19084 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19085 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19086 ("F" . org-next-block)
19087 ("B" . org-previous-block)
19088 ("u" . (org-speed-move-safe 'outline-up-heading))
19089 ("j" . org-goto)
19090 ("g" . (org-refile t))
19091 ("Outline Visibility")
19092 ("c" . org-cycle)
19093 ("C" . org-shifttab)
19094 (" " . org-display-outline-path)
19095 ("s" . org-narrow-to-subtree)
19096 ("=" . org-columns)
19097 ("Outline Structure Editing")
19098 ("U" . org-metaup)
19099 ("D" . org-metadown)
19100 ("r" . org-metaright)
19101 ("l" . org-metaleft)
19102 ("R" . org-shiftmetaright)
19103 ("L" . org-shiftmetaleft)
19104 ("i" . (progn (forward-char 1) (call-interactively
19105 'org-insert-heading-respect-content)))
19106 ("^" . org-sort)
19107 ("w" . org-refile)
19108 ("a" . org-archive-subtree-default-with-confirmation)
19109 ("@" . org-mark-subtree)
19110 ("#" . org-toggle-comment)
19111 ("Clock Commands")
19112 ("I" . org-clock-in)
19113 ("O" . org-clock-out)
19114 ("Meta Data Editing")
19115 ("t" . org-todo)
19116 ("," . (org-priority))
19117 ("0" . (org-priority ?\ ))
19118 ("1" . (org-priority ?A))
19119 ("2" . (org-priority ?B))
19120 ("3" . (org-priority ?C))
19121 (":" . org-set-tags-command)
19122 ("e" . org-set-effort)
19123 ("E" . org-inc-effort)
19124 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19125 (org-entry-put (point) "APPT_WARNTIME" m)))
19126 ("Agenda Views etc")
19127 ("v" . org-agenda)
19128 ("/" . org-sparse-tree)
19129 ("Misc")
19130 ("o" . org-open-at-point)
19131 ("?" . org-speed-command-help)
19132 ("<" . (org-agenda-set-restriction-lock 'subtree))
19133 (">" . (org-agenda-remove-restriction-lock))
19135 "The default speed commands.")
19137 (defun org-print-speed-command (e)
19138 (if (> (length (car e)) 1)
19139 (progn
19140 (princ "\n")
19141 (princ (car e))
19142 (princ "\n")
19143 (princ (make-string (length (car e)) ?-))
19144 (princ "\n"))
19145 (princ (car e))
19146 (princ " ")
19147 (if (symbolp (cdr e))
19148 (princ (symbol-name (cdr e)))
19149 (prin1 (cdr e)))
19150 (princ "\n")))
19152 (defun org-speed-command-help ()
19153 "Show the available speed commands."
19154 (interactive)
19155 (if (not org-use-speed-commands)
19156 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19157 (with-output-to-temp-buffer "*Help*"
19158 (princ "User-defined Speed commands\n===========================\n")
19159 (mapc #'org-print-speed-command org-speed-commands-user)
19160 (princ "\n")
19161 (princ "Built-in Speed commands\n=======================\n")
19162 (mapc #'org-print-speed-command org-speed-commands-default))
19163 (with-current-buffer "*Help*"
19164 (setq truncate-lines t))))
19166 (defun org-speed-move-safe (cmd)
19167 "Execute CMD, but make sure that the cursor always ends up in a headline.
19168 If not, return to the original position and throw an error."
19169 (interactive)
19170 (let ((pos (point)))
19171 (call-interactively cmd)
19172 (unless (and (bolp) (org-at-heading-p))
19173 (goto-char pos)
19174 (error "Boundary reached while executing %s" cmd))))
19176 (defvar org-self-insert-command-undo-counter 0)
19178 (defvar org-table-auto-blank-field) ; defined in org-table.el
19179 (defvar org-speed-command nil)
19181 (defun org-speed-command-activate (keys)
19182 "Hook for activating single-letter speed commands.
19183 `org-speed-commands-default' specifies a minimal command set.
19184 Use `org-speed-commands-user' for further customization."
19185 (when (or (and (bolp) (looking-at org-outline-regexp))
19186 (and (functionp org-use-speed-commands)
19187 (funcall org-use-speed-commands)))
19188 (cdr (assoc keys (append org-speed-commands-user
19189 org-speed-commands-default)))))
19191 (defun org-babel-speed-command-activate (keys)
19192 "Hook for activating single-letter code block commands."
19193 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19194 (cdr (assoc keys org-babel-key-bindings))))
19196 (defcustom org-speed-command-hook
19197 '(org-speed-command-activate org-babel-speed-command-activate)
19198 "Hook for activating speed commands at strategic locations.
19199 Hook functions are called in sequence until a valid handler is
19200 found.
19202 Each hook takes a single argument, a user-pressed command key
19203 which is also a `self-insert-command' from the global map.
19205 Within the hook, examine the cursor position and the command key
19206 and return nil or a valid handler as appropriate. Handler could
19207 be one of an interactive command, a function, or a form.
19209 Set `org-use-speed-commands' to non-nil value to enable this
19210 hook. The default setting is `org-speed-command-activate'."
19211 :group 'org-structure
19212 :version "24.1"
19213 :type 'hook)
19215 (defun org-self-insert-command (N)
19216 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19217 If the cursor is in a table looking at whitespace, the whitespace is
19218 overwritten, and the table is not marked as requiring realignment."
19219 (interactive "p")
19220 (org-check-before-invisible-edit 'insert)
19221 (cond
19222 ((and org-use-speed-commands
19223 (let ((kv (this-command-keys-vector)))
19224 (setq org-speed-command
19225 (run-hook-with-args-until-success
19226 'org-speed-command-hook
19227 (make-string 1 (aref kv (1- (length kv))))))))
19228 (cond
19229 ((commandp org-speed-command)
19230 (setq this-command org-speed-command)
19231 (call-interactively org-speed-command))
19232 ((functionp org-speed-command)
19233 (funcall org-speed-command))
19234 ((and org-speed-command (listp org-speed-command))
19235 (eval org-speed-command))
19236 (t (let (org-use-speed-commands)
19237 (call-interactively 'org-self-insert-command)))))
19238 ((and
19239 (= N 1)
19240 (not (org-region-active-p))
19241 (org-at-table-p)
19242 (progn
19243 ;; Check if we blank the field, and if that triggers align.
19244 (and (featurep 'org-table)
19245 org-table-auto-blank-field
19246 (memq last-command
19247 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19248 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19249 ;; Got extra space, this field does not determine
19250 ;; column width.
19251 (let (org-table-may-need-update) (org-table-blank-field))
19252 ;; No extra space, this field may determine column
19253 ;; width.
19254 (org-table-blank-field)))
19256 (looking-at "[^|\n]* |"))
19257 ;; There is room for insertion without re-aligning the table.
19258 (self-insert-command N)
19259 (org-table-with-shrunk-field
19260 (save-excursion
19261 (skip-chars-forward "^|")
19262 ;; Do not delete last space, which is
19263 ;; `org-table-separator-space', but the regular space before
19264 ;; it.
19265 (delete-region (- (point) 2) (1- (point))))))
19267 (setq org-table-may-need-update t)
19268 (self-insert-command N)
19269 (org-fix-tags-on-the-fly)
19270 (when org-self-insert-cluster-for-undo
19271 (if (not (eq last-command 'org-self-insert-command))
19272 (setq org-self-insert-command-undo-counter 1)
19273 (if (>= org-self-insert-command-undo-counter 20)
19274 (setq org-self-insert-command-undo-counter 1)
19275 (and (> org-self-insert-command-undo-counter 0)
19276 buffer-undo-list (listp buffer-undo-list)
19277 (not (cadr buffer-undo-list)) ; remove nil entry
19278 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19279 (setq org-self-insert-command-undo-counter
19280 (1+ org-self-insert-command-undo-counter))))))))
19282 (defun org-check-before-invisible-edit (kind)
19283 "Check is editing if kind KIND would be dangerous with invisible text around.
19284 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19285 ;; First, try to get out of here as quickly as possible, to reduce overhead
19286 (when (and org-catch-invisible-edits
19287 (or (not (boundp 'visible-mode)) (not visible-mode))
19288 (or (get-char-property (point) 'invisible)
19289 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19290 ;; OK, we need to take a closer look. Do not consider
19291 ;; invisibility obtained through text properties (e.g., link
19292 ;; fontification), as it cannot be toggled.
19293 (let* ((invisible-at-point
19294 (pcase (get-char-property-and-overlay (point) 'invisible)
19295 (`(,_ . ,(and (pred overlayp) o)) o)))
19296 ;; Assume that point cannot land in the middle of an
19297 ;; overlay, or between two overlays.
19298 (invisible-before-point
19299 (and (not invisible-at-point)
19300 (not (bobp))
19301 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19302 (`(,_ . ,(and (pred overlayp) o)) o))))
19303 (border-and-ok-direction
19305 ;; Check if we are acting predictably before invisible
19306 ;; text.
19307 (and invisible-at-point
19308 (memq kind '(insert delete-backward)))
19309 ;; Check if we are acting predictably after invisible text
19310 ;; This works not well, and I have turned it off. It seems
19311 ;; better to always show and stop after invisible text.
19312 ;; (and (not invisible-at-point) invisible-before-point
19313 ;; (memq kind '(insert delete)))
19315 (when (or invisible-at-point invisible-before-point)
19316 (when (eq org-catch-invisible-edits 'error)
19317 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19318 (if (and org-custom-properties-overlays
19319 (y-or-n-p "Display invisible properties in this buffer? "))
19320 (org-toggle-custom-properties-visibility)
19321 ;; Make the area visible
19322 (save-excursion
19323 (when invisible-before-point
19324 (goto-char
19325 (previous-single-char-property-change (point) 'invisible)))
19326 ;; Remove whatever overlay is currently making yet-to-be
19327 ;; edited text invisible. Also remove nested invisibility
19328 ;; related overlays.
19329 (delete-overlay (or invisible-at-point invisible-before-point))
19330 (let ((origin (if invisible-at-point (point) (1- (point)))))
19331 (while (pcase (get-char-property-and-overlay origin 'invisible)
19332 (`(,_ . ,(and (pred overlayp) o))
19333 (delete-overlay o)
19334 t)))))
19335 (cond
19336 ((eq org-catch-invisible-edits 'show)
19337 ;; That's it, we do the edit after showing
19338 (message
19339 "Unfolding invisible region around point before editing")
19340 (sit-for 1))
19341 ((and (eq org-catch-invisible-edits 'smart)
19342 border-and-ok-direction)
19343 (message "Unfolding invisible region around point before editing"))
19345 ;; Don't do the edit, make the user repeat it in full visibility
19346 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19348 (defun org-fix-tags-on-the-fly ()
19349 "Align tags in headline at point.
19350 Unlike to `org-align-tags', this function does nothing if point
19351 is not currently on a headline."
19352 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19353 (org-at-heading-p))
19354 (org-align-tags)))
19356 (defun org-delete-backward-char (N)
19357 "Like `delete-backward-char', insert whitespace at field end in tables.
19358 When deleting backwards, in tables this function will insert whitespace in
19359 front of the next \"|\" separator, to keep the table aligned. The table will
19360 still be marked for re-alignment if the field did fill the entire column,
19361 because, in this case the deletion might narrow the column."
19362 (interactive "p")
19363 (save-match-data
19364 (org-check-before-invisible-edit 'delete-backward)
19365 (if (and (= N 1)
19366 (not overwrite-mode)
19367 (not (org-region-active-p))
19368 (not (eq (char-before) ?|))
19369 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19370 (looking-at-p ".*?|")
19371 (org-at-table-p))
19372 (progn (forward-char -1) (org-delete-char 1))
19373 (backward-delete-char N)
19374 (org-fix-tags-on-the-fly))))
19376 (defun org-delete-char (N)
19377 "Like `delete-char', but insert whitespace at field end in tables.
19378 When deleting characters, in tables this function will insert whitespace in
19379 front of the next \"|\" separator, to keep the table aligned. The table will
19380 still be marked for re-alignment if the field did fill the entire column,
19381 because, in this case the deletion might narrow the column."
19382 (interactive "p")
19383 (save-match-data
19384 (org-check-before-invisible-edit 'delete)
19385 (cond
19386 ((or (/= N 1)
19387 (eq (char-after) ?|)
19388 (save-excursion (skip-chars-backward " \t") (bolp))
19389 (not (org-at-table-p)))
19390 (delete-char N)
19391 (org-fix-tags-on-the-fly))
19392 ((looking-at ".\\(.*?\\)|")
19393 (let* ((update? org-table-may-need-update)
19394 (noalign (looking-at-p ".*? |")))
19395 (delete-char 1)
19396 (org-table-with-shrunk-field
19397 (save-excursion
19398 ;; Last space is `org-table-separator-space', so insert
19399 ;; a regular one before it instead.
19400 (goto-char (- (match-end 0) 2))
19401 (insert " ")))
19402 ;; If there were two spaces at the end, this field does not
19403 ;; determine the width of the column.
19404 (when noalign (setq org-table-may-need-update update?))))
19406 (delete-char N)))))
19408 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19409 (put 'org-self-insert-command 'delete-selection
19410 (lambda ()
19411 (not (run-hook-with-args-until-success
19412 'self-insert-uses-region-functions))))
19413 (put 'orgtbl-self-insert-command 'delete-selection
19414 (lambda ()
19415 (not (run-hook-with-args-until-success
19416 'self-insert-uses-region-functions))))
19417 (put 'org-delete-char 'delete-selection 'supersede)
19418 (put 'org-delete-backward-char 'delete-selection 'supersede)
19419 (put 'org-yank 'delete-selection 'yank)
19421 ;; Make `flyspell-mode' delay after some commands
19422 (put 'org-self-insert-command 'flyspell-delayed t)
19423 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19424 (put 'org-delete-char 'flyspell-delayed t)
19425 (put 'org-delete-backward-char 'flyspell-delayed t)
19427 ;; Make pabbrev-mode expand after Org mode commands
19428 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19429 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19431 (defun org-transpose-words ()
19432 "Transpose words for Org.
19433 This uses the `org-mode-transpose-word-syntax-table' syntax
19434 table, which interprets characters in `org-emphasis-alist' as
19435 word constituents."
19436 (interactive)
19437 (with-syntax-table org-mode-transpose-word-syntax-table
19438 (call-interactively 'transpose-words)))
19440 (defvar org-ctrl-c-ctrl-c-hook nil
19441 "Hook for functions attaching themselves to `C-c C-c'.
19443 This can be used to add additional functionality to the C-c C-c
19444 key which executes context-dependent commands. This hook is run
19445 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19446 run after the last test.
19448 Each function will be called with no arguments. The function
19449 must check if the context is appropriate for it to act. If yes,
19450 it should do its thing and then return a non-nil value. If the
19451 context is wrong, just do nothing and return nil.")
19453 (defvar org-ctrl-c-ctrl-c-final-hook nil
19454 "Hook for functions attaching themselves to `C-c C-c'.
19456 This can be used to add additional functionality to the C-c C-c
19457 key which executes context-dependent commands. This hook is run
19458 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19459 before the first test.
19461 Each function will be called with no arguments. The function
19462 must check if the context is appropriate for it to act. If yes,
19463 it should do its thing and then return a non-nil value. If the
19464 context is wrong, just do nothing and return nil.")
19466 (defvar org-tab-first-hook nil
19467 "Hook for functions to attach themselves to TAB.
19468 See `org-ctrl-c-ctrl-c-hook' for more information.
19469 This hook runs as the first action when TAB is pressed, even before
19470 `org-cycle' messes around with the `outline-regexp' to cater for
19471 inline tasks and plain list item folding.
19472 If any function in this hook returns t, any other actions that
19473 would have been caused by TAB (such as table field motion or visibility
19474 cycling) will not occur.")
19476 (defvar org-tab-after-check-for-table-hook nil
19477 "Hook for functions to attach themselves to TAB.
19478 See `org-ctrl-c-ctrl-c-hook' for more information.
19479 This hook runs after it has been established that the cursor is not in a
19480 table, but before checking if the cursor is in a headline or if global cycling
19481 should be done.
19482 If any function in this hook returns t, not other actions like visibility
19483 cycling will be done.")
19485 (defvar org-tab-after-check-for-cycling-hook nil
19486 "Hook for functions to attach themselves to TAB.
19487 See `org-ctrl-c-ctrl-c-hook' for more information.
19488 This hook runs after it has been established that not table field motion and
19489 not visibility should be done because of current context. This is probably
19490 the place where a package like yasnippets can hook in.")
19492 (defvar org-tab-before-tab-emulation-hook nil
19493 "Hook for functions to attach themselves to TAB.
19494 See `org-ctrl-c-ctrl-c-hook' for more information.
19495 This hook runs after every other options for TAB have been exhausted, but
19496 before indentation and \t insertion takes place.")
19498 (defvar org-metaleft-hook nil
19499 "Hook for functions attaching themselves to `M-left'.
19500 See `org-ctrl-c-ctrl-c-hook' for more information.")
19501 (defvar org-metaright-hook nil
19502 "Hook for functions attaching themselves to `M-right'.
19503 See `org-ctrl-c-ctrl-c-hook' for more information.")
19504 (defvar org-metaup-hook nil
19505 "Hook for functions attaching themselves to `M-up'.
19506 See `org-ctrl-c-ctrl-c-hook' for more information.")
19507 (defvar org-metadown-hook nil
19508 "Hook for functions attaching themselves to `M-down'.
19509 See `org-ctrl-c-ctrl-c-hook' for more information.")
19510 (defvar org-shiftmetaleft-hook nil
19511 "Hook for functions attaching themselves to `M-S-left'.
19512 See `org-ctrl-c-ctrl-c-hook' for more information.")
19513 (defvar org-shiftmetaright-hook nil
19514 "Hook for functions attaching themselves to `M-S-right'.
19515 See `org-ctrl-c-ctrl-c-hook' for more information.")
19516 (defvar org-shiftmetaup-hook nil
19517 "Hook for functions attaching themselves to `M-S-up'.
19518 See `org-ctrl-c-ctrl-c-hook' for more information.")
19519 (defvar org-shiftmetadown-hook nil
19520 "Hook for functions attaching themselves to `M-S-down'.
19521 See `org-ctrl-c-ctrl-c-hook' for more information.")
19522 (defvar org-metareturn-hook nil
19523 "Hook for functions attaching themselves to `M-RET'.
19524 See `org-ctrl-c-ctrl-c-hook' for more information.")
19525 (defvar org-shiftup-hook nil
19526 "Hook for functions attaching themselves to `S-up'.
19527 See `org-ctrl-c-ctrl-c-hook' for more information.")
19528 (defvar org-shiftup-final-hook nil
19529 "Hook for functions attaching themselves to `S-up'.
19530 This one runs after all other options except shift-select have been excluded.
19531 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defvar org-shiftdown-hook nil
19533 "Hook for functions attaching themselves to `S-down'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-shiftdown-final-hook nil
19536 "Hook for functions attaching themselves to `S-down'.
19537 This one runs after all other options except shift-select have been excluded.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.")
19539 (defvar org-shiftleft-hook nil
19540 "Hook for functions attaching themselves to `S-left'.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.")
19542 (defvar org-shiftleft-final-hook nil
19543 "Hook for functions attaching themselves to `S-left'.
19544 This one runs after all other options except shift-select have been excluded.
19545 See `org-ctrl-c-ctrl-c-hook' for more information.")
19546 (defvar org-shiftright-hook nil
19547 "Hook for functions attaching themselves to `S-right'.
19548 See `org-ctrl-c-ctrl-c-hook' for more information.")
19549 (defvar org-shiftright-final-hook nil
19550 "Hook for functions attaching themselves to `S-right'.
19551 This one runs after all other options except shift-select have been excluded.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defun org-modifier-cursor-error ()
19555 "Throw an error, a modified cursor command was applied in wrong context."
19556 (user-error "This command is active in special context like tables, headlines or items"))
19558 (defun org-shiftselect-error ()
19559 "Throw an error because Shift-Cursor command was applied in wrong context."
19560 (if (and (boundp 'shift-select-mode) shift-select-mode)
19561 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19562 (user-error "This command works only in special context like headlines or timestamps")))
19564 (defun org-call-for-shift-select (cmd)
19565 (let ((this-command-keys-shift-translated t))
19566 (call-interactively cmd)))
19568 (defun org-shifttab (&optional arg)
19569 "Global visibility cycling or move to previous table field.
19570 Call `org-table-previous-field' within a table.
19571 When ARG is nil, cycle globally through visibility states.
19572 When ARG is a numeric prefix, show contents of this level."
19573 (interactive "P")
19574 (cond
19575 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19576 ((integerp arg)
19577 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19578 (message "Content view to level: %d" arg)
19579 (org-content (prefix-numeric-value arg2))
19580 (org-cycle-show-empty-lines t)
19581 (setq org-cycle-global-status 'overview)))
19582 (t (call-interactively 'org-global-cycle))))
19584 (defun org-shiftmetaleft ()
19585 "Promote subtree or delete table column.
19586 Calls `org-promote-subtree', `org-outdent-item-tree', or
19587 `org-table-delete-column', depending on context. See the
19588 individual commands for more information."
19589 (interactive)
19590 (cond
19591 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19592 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19593 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19594 ((if (not (org-region-active-p)) (org-at-item-p)
19595 (save-excursion (goto-char (region-beginning))
19596 (org-at-item-p)))
19597 (call-interactively 'org-outdent-item-tree))
19598 (t (org-modifier-cursor-error))))
19600 (defun org-shiftmetaright ()
19601 "Demote subtree or insert table column.
19602 Calls `org-demote-subtree', `org-indent-item-tree', or
19603 `org-table-insert-column', depending on context. See the
19604 individual commands for more information."
19605 (interactive)
19606 (cond
19607 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19608 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19609 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19610 ((if (not (org-region-active-p)) (org-at-item-p)
19611 (save-excursion (goto-char (region-beginning))
19612 (org-at-item-p)))
19613 (call-interactively 'org-indent-item-tree))
19614 (t (org-modifier-cursor-error))))
19616 (defun org-shiftmetaup (&optional _arg)
19617 "Drag the line at point up.
19618 In a table, kill the current row.
19619 On a clock timestamp, update the value of the timestamp like `S-<up>'
19620 but also adjust the previous clocked item in the clock history.
19621 Everywhere else, drag the line at point up."
19622 (interactive "P")
19623 (cond
19624 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19625 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19626 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19627 (call-interactively 'org-timestamp-up)))
19628 (t (call-interactively 'org-drag-line-backward))))
19630 (defun org-shiftmetadown (&optional _arg)
19631 "Drag the line at point down.
19632 In a table, insert an empty row at the current line.
19633 On a clock timestamp, update the value of the timestamp like `S-<down>'
19634 but also adjust the previous clocked item in the clock history.
19635 Everywhere else, drag the line at point down."
19636 (interactive "P")
19637 (cond
19638 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19639 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19640 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19641 (call-interactively 'org-timestamp-down)))
19642 (t (call-interactively 'org-drag-line-forward))))
19644 (defsubst org-hidden-tree-error ()
19645 (user-error
19646 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19648 (defun org-metaleft (&optional _arg)
19649 "Promote heading, list item at point or move table column left.
19651 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19652 depending on context. With no specific context, calls the Emacs
19653 default `backward-word'. See the individual commands for more
19654 information.
19656 This function runs the hook `org-metaleft-hook' as a first step,
19657 and returns at first non-nil value."
19658 (interactive "P")
19659 (cond
19660 ((run-hook-with-args-until-success 'org-metaleft-hook))
19661 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19662 ((org-with-limited-levels
19663 (or (org-at-heading-p)
19664 (and (org-region-active-p)
19665 (save-excursion
19666 (goto-char (region-beginning))
19667 (org-at-heading-p)))))
19668 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19669 (call-interactively 'org-do-promote))
19670 ;; At an inline task.
19671 ((org-at-heading-p)
19672 (call-interactively 'org-inlinetask-promote))
19673 ((or (org-at-item-p)
19674 (and (org-region-active-p)
19675 (save-excursion
19676 (goto-char (region-beginning))
19677 (org-at-item-p))))
19678 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19679 (call-interactively 'org-outdent-item))
19680 (t (call-interactively 'backward-word))))
19682 (defun org-metaright (&optional _arg)
19683 "Demote heading, list item at point or move table column right.
19685 In front of a drawer or a block keyword, indent it correctly.
19687 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19688 `org-indent-drawer' or `org-indent-block' depending on context.
19689 With no specific context, calls the Emacs default `forward-word'.
19690 See the individual commands for more information.
19692 This function runs the hook `org-metaright-hook' as a first step,
19693 and returns at first non-nil value."
19694 (interactive "P")
19695 (cond
19696 ((run-hook-with-args-until-success 'org-metaright-hook))
19697 ((org-at-table-p) (call-interactively 'org-table-move-column))
19698 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19699 ((org-at-block-p) (call-interactively 'org-indent-block))
19700 ((org-with-limited-levels
19701 (or (org-at-heading-p)
19702 (and (org-region-active-p)
19703 (save-excursion
19704 (goto-char (region-beginning))
19705 (org-at-heading-p)))))
19706 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19707 (call-interactively 'org-do-demote))
19708 ;; At an inline task.
19709 ((org-at-heading-p)
19710 (call-interactively 'org-inlinetask-demote))
19711 ((or (org-at-item-p)
19712 (and (org-region-active-p)
19713 (save-excursion
19714 (goto-char (region-beginning))
19715 (org-at-item-p))))
19716 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19717 (call-interactively 'org-indent-item))
19718 (t (call-interactively 'forward-word))))
19720 (defun org-check-for-hidden (what)
19721 "Check if there are hidden headlines/items in the current visual line.
19722 WHAT can be either `headlines' or `items'. If the current line is
19723 an outline or item heading and it has a folded subtree below it,
19724 this function returns t, nil otherwise."
19725 (let ((re (cond
19726 ((eq what 'headlines) org-outline-regexp-bol)
19727 ((eq what 'items) (org-item-beginning-re))
19728 (t (error "This should not happen"))))
19729 beg end)
19730 (save-excursion
19731 (catch 'exit
19732 (unless (org-region-active-p)
19733 (setq beg (point-at-bol))
19734 (beginning-of-line 2)
19735 (while (and (not (eobp)) ;; this is like `next-line'
19736 (get-char-property (1- (point)) 'invisible))
19737 (beginning-of-line 2))
19738 (setq end (point))
19739 (goto-char beg)
19740 (goto-char (point-at-eol))
19741 (setq end (max end (point)))
19742 (while (re-search-forward re end t)
19743 (when (get-char-property (match-beginning 0) 'invisible)
19744 (throw 'exit t))))
19745 nil))))
19747 (defun org-metaup (&optional _arg)
19748 "Move subtree up or move table row up.
19749 Calls `org-move-subtree-up' or `org-table-move-row' or
19750 `org-move-item-up', depending on context. See the individual commands
19751 for more information."
19752 (interactive "P")
19753 (cond
19754 ((run-hook-with-args-until-success 'org-metaup-hook))
19755 ((org-region-active-p)
19756 (let* ((a (min (region-beginning) (region-end)))
19757 (b (1- (max (region-beginning) (region-end))))
19758 (c (save-excursion (goto-char a)
19759 (move-beginning-of-line 0)))
19760 (d (save-excursion (goto-char a)
19761 (move-end-of-line 0) (point))))
19762 (transpose-regions a b c d)
19763 (goto-char c)))
19764 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19765 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19766 ((org-at-item-p) (call-interactively 'org-move-item-up))
19767 (t (org-drag-element-backward))))
19769 (defun org-metadown (&optional _arg)
19770 "Move subtree down or move table row down.
19771 Calls `org-move-subtree-down' or `org-table-move-row' or
19772 `org-move-item-down', depending on context. See the individual
19773 commands for more information."
19774 (interactive "P")
19775 (cond
19776 ((run-hook-with-args-until-success 'org-metadown-hook))
19777 ((org-region-active-p)
19778 (let* ((a (min (region-beginning) (region-end)))
19779 (b (max (region-beginning) (region-end)))
19780 (c (save-excursion (goto-char b)
19781 (move-beginning-of-line 1)))
19782 (d (save-excursion (goto-char b)
19783 (move-end-of-line 1) (1+ (point)))))
19784 (transpose-regions a b c d)
19785 (goto-char d)))
19786 ((org-at-table-p) (call-interactively 'org-table-move-row))
19787 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19788 ((org-at-item-p) (call-interactively 'org-move-item-down))
19789 (t (org-drag-element-forward))))
19791 (defun org-shiftup (&optional arg)
19792 "Increase item in timestamp or increase priority of current headline.
19793 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19794 depending on context. See the individual commands for more information."
19795 (interactive "P")
19796 (cond
19797 ((run-hook-with-args-until-success 'org-shiftup-hook))
19798 ((and org-support-shift-select (org-region-active-p))
19799 (org-call-for-shift-select 'previous-line))
19800 ((org-at-timestamp-p 'lax)
19801 (call-interactively (if org-edit-timestamp-down-means-later
19802 'org-timestamp-down 'org-timestamp-up)))
19803 ((and (not (eq org-support-shift-select 'always))
19804 org-enable-priority-commands
19805 (org-at-heading-p))
19806 (call-interactively 'org-priority-up))
19807 ((and (not org-support-shift-select) (org-at-item-p))
19808 (call-interactively 'org-previous-item))
19809 ((org-clocktable-try-shift 'up arg))
19810 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19811 (org-support-shift-select
19812 (org-call-for-shift-select 'previous-line))
19813 (t (org-shiftselect-error))))
19815 (defun org-shiftdown (&optional arg)
19816 "Decrease item in timestamp or decrease priority of current headline.
19817 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19818 depending on context. See the individual commands for more information."
19819 (interactive "P")
19820 (cond
19821 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19822 ((and org-support-shift-select (org-region-active-p))
19823 (org-call-for-shift-select 'next-line))
19824 ((org-at-timestamp-p 'lax)
19825 (call-interactively (if org-edit-timestamp-down-means-later
19826 'org-timestamp-up 'org-timestamp-down)))
19827 ((and (not (eq org-support-shift-select 'always))
19828 org-enable-priority-commands
19829 (org-at-heading-p))
19830 (call-interactively 'org-priority-down))
19831 ((and (not org-support-shift-select) (org-at-item-p))
19832 (call-interactively 'org-next-item))
19833 ((org-clocktable-try-shift 'down arg))
19834 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19835 (org-support-shift-select
19836 (org-call-for-shift-select 'next-line))
19837 (t (org-shiftselect-error))))
19839 (defun org-shiftright (&optional arg)
19840 "Cycle the thing at point or in the current line, depending on context.
19841 Depending on context, this does one of the following:
19843 - switch a timestamp at point one day into the future
19844 - on a headline, switch to the next TODO keyword.
19845 - on an item, switch entire list to the next bullet type
19846 - on a property line, switch to the next allowed value
19847 - on a clocktable definition line, move time block into the future"
19848 (interactive "P")
19849 (cond
19850 ((run-hook-with-args-until-success 'org-shiftright-hook))
19851 ((and org-support-shift-select (org-region-active-p))
19852 (org-call-for-shift-select 'forward-char))
19853 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19854 ((and (not (eq org-support-shift-select 'always))
19855 (org-at-heading-p))
19856 (let ((org-inhibit-logging
19857 (not org-treat-S-cursor-todo-selection-as-state-change))
19858 (org-inhibit-blocking
19859 (not org-treat-S-cursor-todo-selection-as-state-change)))
19860 (org-call-with-arg 'org-todo 'right)))
19861 ((or (and org-support-shift-select
19862 (not (eq org-support-shift-select 'always))
19863 (org-at-item-bullet-p))
19864 (and (not org-support-shift-select) (org-at-item-p)))
19865 (org-call-with-arg 'org-cycle-list-bullet nil))
19866 ((and (not (eq org-support-shift-select 'always))
19867 (org-at-property-p))
19868 (call-interactively 'org-property-next-allowed-value))
19869 ((org-clocktable-try-shift 'right arg))
19870 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19871 (org-support-shift-select
19872 (org-call-for-shift-select 'forward-char))
19873 (t (org-shiftselect-error))))
19875 (defun org-shiftleft (&optional arg)
19876 "Cycle the thing at point or in the current line, depending on context.
19877 Depending on context, this does one of the following:
19879 - switch a timestamp at point one day into the past
19880 - on a headline, switch to the previous TODO keyword.
19881 - on an item, switch entire list to the previous bullet type
19882 - on a property line, switch to the previous allowed value
19883 - on a clocktable definition line, move time block into the past"
19884 (interactive "P")
19885 (cond
19886 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19887 ((and org-support-shift-select (org-region-active-p))
19888 (org-call-for-shift-select 'backward-char))
19889 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19890 ((and (not (eq org-support-shift-select 'always))
19891 (org-at-heading-p))
19892 (let ((org-inhibit-logging
19893 (not org-treat-S-cursor-todo-selection-as-state-change))
19894 (org-inhibit-blocking
19895 (not org-treat-S-cursor-todo-selection-as-state-change)))
19896 (org-call-with-arg 'org-todo 'left)))
19897 ((or (and org-support-shift-select
19898 (not (eq org-support-shift-select 'always))
19899 (org-at-item-bullet-p))
19900 (and (not org-support-shift-select) (org-at-item-p)))
19901 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19902 ((and (not (eq org-support-shift-select 'always))
19903 (org-at-property-p))
19904 (call-interactively 'org-property-previous-allowed-value))
19905 ((org-clocktable-try-shift 'left arg))
19906 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19907 (org-support-shift-select
19908 (org-call-for-shift-select 'backward-char))
19909 (t (org-shiftselect-error))))
19911 (defun org-shiftcontrolright ()
19912 "Switch to next TODO set."
19913 (interactive)
19914 (cond
19915 ((and org-support-shift-select (org-region-active-p))
19916 (org-call-for-shift-select 'forward-word))
19917 ((and (not (eq org-support-shift-select 'always))
19918 (org-at-heading-p))
19919 (org-call-with-arg 'org-todo 'nextset))
19920 (org-support-shift-select
19921 (org-call-for-shift-select 'forward-word))
19922 (t (org-shiftselect-error))))
19924 (defun org-shiftcontrolleft ()
19925 "Switch to previous TODO set."
19926 (interactive)
19927 (cond
19928 ((and org-support-shift-select (org-region-active-p))
19929 (org-call-for-shift-select 'backward-word))
19930 ((and (not (eq org-support-shift-select 'always))
19931 (org-at-heading-p))
19932 (org-call-with-arg 'org-todo 'previousset))
19933 (org-support-shift-select
19934 (org-call-for-shift-select 'backward-word))
19935 (t (org-shiftselect-error))))
19937 (defun org-shiftcontrolup (&optional n)
19938 "Change timestamps synchronously up in CLOCK log lines.
19939 Optional argument N tells to change by that many units."
19940 (interactive "P")
19941 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19942 (let (org-support-shift-select)
19943 (org-clock-timestamps-up n))
19944 (user-error "Not at a clock log")))
19946 (defun org-shiftcontroldown (&optional n)
19947 "Change timestamps synchronously down in CLOCK log lines.
19948 Optional argument N tells to change by that many units."
19949 (interactive "P")
19950 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19951 (let (org-support-shift-select)
19952 (org-clock-timestamps-down n))
19953 (user-error "Not at a clock log")))
19955 (defun org-increase-number-at-point (&optional inc)
19956 "Increment the number at point.
19957 With an optional prefix numeric argument INC, increment using
19958 this numeric value."
19959 (interactive "p")
19960 (if (not (number-at-point))
19961 (user-error "Not on a number")
19962 (unless inc (setq inc 1))
19963 (let ((pos (point))
19964 (beg (skip-chars-backward "-+^/*0-9eE."))
19965 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19966 (setq nap (buffer-substring-no-properties
19967 (+ pos beg) (+ pos beg end)))
19968 (delete-region (+ pos beg) (+ pos beg end))
19969 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19970 (when (org-at-table-p)
19971 (org-table-align)
19972 (org-table-end-of-field 1))))
19974 (defun org-decrease-number-at-point (&optional inc)
19975 "Decrement the number at point.
19976 With an optional prefix numeric argument INC, decrement using
19977 this numeric value."
19978 (interactive "p")
19979 (org-increase-number-at-point (- (or inc 1))))
19981 (defun org-ctrl-c-ret ()
19982 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19983 (interactive)
19984 (cond
19985 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19986 (t (call-interactively 'org-insert-heading))))
19988 (defun org-find-visible ()
19989 (let ((s (point)))
19990 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19991 (get-char-property s 'invisible)))
19993 (defun org-find-invisible ()
19994 (let ((s (point)))
19995 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19996 (not (get-char-property s 'invisible))))
19999 (defun org-copy-visible (beg end)
20000 "Copy the visible parts of the region."
20001 (interactive "r")
20002 (let ((result ""))
20003 (while (/= beg end)
20004 (when (get-char-property beg 'invisible)
20005 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20006 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20007 (setq result (concat result (buffer-substring beg next)))
20008 (setq beg next)))
20009 (kill-new result)))
20011 (defun org-copy-special ()
20012 "Copy region in table or copy current subtree.
20013 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20014 context. See the individual commands for more information."
20015 (interactive)
20016 (call-interactively
20017 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20019 (defun org-cut-special ()
20020 "Cut region in table or cut current subtree.
20021 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20022 context. See the individual commands for more information."
20023 (interactive)
20024 (call-interactively
20025 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20027 (defun org-paste-special (arg)
20028 "Paste rectangular region into table, or past subtree relative to level.
20029 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20030 See the individual commands for more information."
20031 (interactive "P")
20032 (if (org-at-table-p)
20033 (org-table-paste-rectangle)
20034 (org-paste-subtree arg)))
20036 (defun org-edit-special (&optional arg)
20037 "Call a special editor for the element at point.
20038 When at a table, call the formula editor with `org-table-edit-formulas'.
20039 When in a source code block, call `org-edit-src-code'.
20040 When in a fixed-width region, call `org-edit-fixed-width-region'.
20041 When in an export block, call `org-edit-export-block'.
20042 When in a LaTeX environment, call `org-edit-latex-environment'.
20043 When at an #+INCLUDE keyword, visit the included file.
20044 When at a footnote reference, call `org-edit-footnote-reference'
20045 On a link, call `ffap' to visit the link at point.
20046 Otherwise, return a user error."
20047 (interactive "P")
20048 (let ((element (org-element-at-point)))
20049 (barf-if-buffer-read-only)
20050 (pcase (org-element-type element)
20051 (`src-block
20052 (if (not arg) (org-edit-src-code)
20053 (let* ((info (org-babel-get-src-block-info))
20054 (lang (nth 0 info))
20055 (params (nth 2 info))
20056 (session (cdr (assq :session params))))
20057 (if (not session) (org-edit-src-code)
20058 ;; At a src-block with a session and function called with
20059 ;; an ARG: switch to the buffer related to the inferior
20060 ;; process.
20061 (switch-to-buffer
20062 (funcall (intern (concat "org-babel-prep-session:" lang))
20063 session params))))))
20064 (`keyword
20065 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20066 (org-open-link-from-string
20067 (format "[[%s]]"
20068 (expand-file-name
20069 (let ((value (org-element-property :value element)))
20070 (cond ((org-file-url-p value)
20071 (user-error "The file is specified as a URL, cannot be edited"))
20072 ((not (org-string-nw-p value))
20073 (user-error "No file to edit"))
20074 ((string-match "\\`\"\\(.*?\\)\"" value)
20075 (match-string 1 value))
20076 ((string-match "\\`[^ \t\"]\\S-*" value)
20077 (match-string 0 value))
20078 (t (user-error "No valid file specified")))))))
20079 (user-error "No special environment to edit here")))
20080 (`table
20081 (if (eq (org-element-property :type element) 'table.el)
20082 (org-edit-table.el)
20083 (call-interactively 'org-table-edit-formulas)))
20084 ;; Only Org tables contain `table-row' type elements.
20085 (`table-row (call-interactively 'org-table-edit-formulas))
20086 (`example-block (org-edit-src-code))
20087 (`export-block (org-edit-export-block))
20088 (`fixed-width (org-edit-fixed-width-region))
20089 (`latex-environment (org-edit-latex-environment))
20091 ;; No notable element at point. Though, we may be at a link or
20092 ;; a footnote reference, which are objects. Thus, scan deeper.
20093 (let ((context (org-element-context element)))
20094 (pcase (org-element-type context)
20095 (`footnote-reference (org-edit-footnote-reference))
20096 (`inline-src-block (org-edit-inline-src-code))
20097 (`link (call-interactively #'ffap))
20098 (_ (user-error "No special environment to edit here"))))))))
20100 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20101 (defun org-ctrl-c-ctrl-c (&optional arg)
20102 "Set tags in headline, or update according to changed information at point.
20104 This command does many different things, depending on context:
20106 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20107 this is what we do.
20109 - If the cursor is on a statistics cookie, update it.
20111 - If the cursor is in a headline, prompt for tags and insert them
20112 into the current line, aligned to `org-tags-column'. When called
20113 with prefix arg, realign all tags in the current buffer.
20115 - If the cursor is in one of the special #+KEYWORD lines, this
20116 triggers scanning the buffer for these lines and updating the
20117 information.
20119 - If the cursor is inside a table, realign the table. This command
20120 works even if the automatic table editor has been turned off.
20122 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20123 the entire table.
20125 - If the cursor is at a footnote reference or definition, jump to
20126 the corresponding definition or references, respectively.
20128 - If the cursor is a the beginning of a dynamic block, update it.
20130 - If the current buffer is a capture buffer, close note and file it.
20132 - If the cursor is on a <<<target>>>, update radio targets and
20133 corresponding links in this buffer.
20135 - If the cursor is on a numbered item in a plain list, renumber the
20136 ordered list.
20138 - If the cursor is on a checkbox, toggle it.
20140 - If the cursor is on a code block, evaluate it. The variable
20141 `org-confirm-babel-evaluate' can be used to control prompting
20142 before code block evaluation, by default every code block
20143 evaluation requires confirmation. Code block evaluation can be
20144 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20145 (interactive "P")
20146 (cond
20147 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20148 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20149 (org-remove-occur-highlights)
20150 (message "Temporary highlights/overlays removed from current buffer"))
20151 ((and (local-variable-p 'org-finish-function)
20152 (fboundp org-finish-function))
20153 (funcall org-finish-function))
20154 ((org-babel-hash-at-point))
20155 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20157 (let* ((context
20158 (org-element-lineage
20159 (org-element-context)
20160 ;; Limit to supported contexts.
20161 '(babel-call clock dynamic-block footnote-definition
20162 footnote-reference inline-babel-call inline-src-block
20163 inlinetask item keyword node-property paragraph
20164 plain-list planning property-drawer radio-target
20165 src-block statistics-cookie table table-cell table-row
20166 timestamp)
20168 (type (org-element-type context)))
20169 ;; For convenience: at the first line of a paragraph on the same
20170 ;; line as an item, apply function on that item instead.
20171 (when (eq type 'paragraph)
20172 (let ((parent (org-element-property :parent context)))
20173 (when (and (eq (org-element-type parent) 'item)
20174 (= (line-beginning-position)
20175 (org-element-property :begin parent)))
20176 (setq context parent)
20177 (setq type 'item))))
20178 ;; Act according to type of element or object at point.
20180 ;; Do nothing on a blank line, except if it is contained in
20181 ;; a src block. Hence, we first check if point is in such
20182 ;; a block and then if it is at a blank line.
20183 (pcase type
20184 ((or `inline-src-block `src-block)
20185 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20186 (org-babel-eval-wipe-error-buffer)
20187 (org-babel-execute-src-block
20188 current-prefix-arg (org-babel-get-src-block-info nil context))))
20189 ((guard (org-match-line "[ \t]*$"))
20190 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20191 (user-error
20192 (substitute-command-keys
20193 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20194 ((or `babel-call `inline-babel-call)
20195 (let ((info (org-babel-lob-get-info context)))
20196 (when info (org-babel-execute-src-block nil info))))
20197 (`clock (org-clock-update-time-maybe))
20198 (`dynamic-block
20199 (save-excursion
20200 (goto-char (org-element-property :post-affiliated context))
20201 (org-update-dblock)))
20202 (`footnote-definition
20203 (goto-char (org-element-property :post-affiliated context))
20204 (call-interactively 'org-footnote-action))
20205 (`footnote-reference (call-interactively #'org-footnote-action))
20206 ((or `headline `inlinetask)
20207 (save-excursion (goto-char (org-element-property :begin context))
20208 (call-interactively #'org-set-tags-command)))
20209 (`item
20210 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20211 ;; unconditionally, whereas `C-u' will toggle its presence.
20212 ;; Without a universal argument, if the item has a checkbox,
20213 ;; toggle it. Otherwise repair the list.
20214 (let* ((box (org-element-property :checkbox context))
20215 (struct (org-element-property :structure context))
20216 (old-struct (copy-tree struct))
20217 (parents (org-list-parents-alist struct))
20218 (prevs (org-list-prevs-alist struct))
20219 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20220 (org-list-set-checkbox
20221 (org-element-property :begin context) struct
20222 (cond ((equal arg '(16)) "[-]")
20223 ((and (not box) (equal arg '(4))) "[ ]")
20224 ((or (not box) (equal arg '(4))) nil)
20225 ((eq box 'on) "[ ]")
20226 (t "[X]")))
20227 ;; Mimic `org-list-write-struct' but with grabbing a return
20228 ;; value from `org-list-struct-fix-box'.
20229 (org-list-struct-fix-ind struct parents 2)
20230 (org-list-struct-fix-item-end struct)
20231 (org-list-struct-fix-bul struct prevs)
20232 (org-list-struct-fix-ind struct parents)
20233 (let ((block-item
20234 (org-list-struct-fix-box struct parents prevs orderedp)))
20235 (if (and box (equal struct old-struct))
20236 (if (equal arg '(16))
20237 (message "Checkboxes already reset")
20238 (user-error "Cannot toggle this checkbox: %s"
20239 (if (eq box 'on)
20240 "all subitems checked"
20241 "unchecked subitems")))
20242 (org-list-struct-apply-struct struct old-struct)
20243 (org-update-checkbox-count-maybe))
20244 (when block-item
20245 (message "Checkboxes were removed due to empty box at line %d"
20246 (org-current-line block-item))))))
20247 (`keyword
20248 (let ((org-inhibit-startup-visibility-stuff t)
20249 (org-startup-align-all-tables nil))
20250 (when (boundp 'org-table-coordinate-overlays)
20251 (mapc #'delete-overlay org-table-coordinate-overlays)
20252 (setq org-table-coordinate-overlays nil))
20253 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20254 (message "Local setup has been refreshed"))
20255 (`plain-list
20256 ;; At a plain list, with a double C-u argument, set
20257 ;; checkboxes of each item to "[-]", whereas a single one
20258 ;; will toggle their presence according to the state of the
20259 ;; first item in the list. Without an argument, repair the
20260 ;; list.
20261 (let* ((begin (org-element-property :contents-begin context))
20262 (struct (org-element-property :structure context))
20263 (old-struct (copy-tree struct))
20264 (first-box (save-excursion
20265 (goto-char begin)
20266 (looking-at org-list-full-item-re)
20267 (match-string-no-properties 3)))
20268 (new-box (cond ((equal arg '(16)) "[-]")
20269 ((equal arg '(4)) (unless first-box "[ ]"))
20270 ((equal first-box "[X]") "[ ]")
20271 (t "[X]"))))
20272 (cond
20273 (arg
20274 (dolist (pos
20275 (org-list-get-all-items
20276 begin struct (org-list-prevs-alist struct)))
20277 (org-list-set-checkbox pos struct new-box)))
20278 ((and first-box (eq (point) begin))
20279 ;; For convenience, when point is at bol on the first
20280 ;; item of the list and no argument is provided, simply
20281 ;; toggle checkbox of that item, if any.
20282 (org-list-set-checkbox begin struct new-box)))
20283 (org-list-write-struct
20284 struct (org-list-parents-alist struct) old-struct)
20285 (org-update-checkbox-count-maybe)))
20286 ((or `property-drawer `node-property)
20287 (call-interactively #'org-property-action))
20288 (`radio-target
20289 (call-interactively #'org-update-radio-target-regexp))
20290 (`statistics-cookie
20291 (call-interactively #'org-update-statistics-cookies))
20292 ((or `table `table-cell `table-row)
20293 ;; At a table, recalculate every field and align it. Also
20294 ;; send the table if necessary. If the table has
20295 ;; a `table.el' type, just give up. At a table row or cell,
20296 ;; maybe recalculate line but always align table.
20297 (if (eq (org-element-property :type context) 'table.el)
20298 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20299 Use `\\[org-edit-special]' to edit table.el tables"))
20300 (if (or (eq type 'table)
20301 ;; Check if point is at a TBLFM line.
20302 (and (eq type 'table-row)
20303 (= (point) (org-element-property :end context))))
20304 (save-excursion
20305 (if (org-at-TBLFM-p)
20306 (progn (require 'org-table)
20307 (org-table-calc-current-TBLFM))
20308 (goto-char (org-element-property :contents-begin context))
20309 (org-call-with-arg 'org-table-recalculate (or arg t))
20310 (orgtbl-send-table 'maybe)))
20311 (org-table-maybe-eval-formula)
20312 (cond (arg (call-interactively #'org-table-recalculate))
20313 ((org-table-maybe-recalculate-line))
20314 (t (org-table-align))))))
20315 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20316 (org-timestamp-change 0 'day))
20317 ((and `nil (guard (org-at-heading-p)))
20318 ;; When point is on an unsupported object type, we can miss
20319 ;; the fact that it also is at a heading. Handle it here.
20320 (call-interactively #'org-set-tags-command))
20321 ((guard
20322 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20324 (user-error
20325 (substitute-command-keys
20326 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20328 (defun org-mode-restart ()
20329 (interactive)
20330 (let ((indent-status (bound-and-true-p org-indent-mode)))
20331 (funcall major-mode)
20332 (hack-local-variables)
20333 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20334 (org-indent-mode -1))
20335 (org-reset-file-cache))
20336 (message "%s restarted" major-mode))
20338 (defun org-kill-note-or-show-branches ()
20339 "Abort storing current note, or call `outline-show-branches'."
20340 (interactive)
20341 (if (not org-finish-function)
20342 (save-excursion
20343 (save-restriction
20344 (org-narrow-to-subtree)
20345 (org-flag-subtree t)
20346 (call-interactively 'outline-show-branches)
20347 (org-hide-archived-subtrees (point-min) (point-max))))
20348 (let ((org-note-abort t))
20349 (funcall org-finish-function))))
20351 (defun org-delete-indentation (&optional arg)
20352 "Join current line to previous and fix whitespace at join.
20354 If previous line is a headline add to headline title. Otherwise
20355 the function calls `delete-indentation'.
20357 With a non-nil optional argument, join it to the following one."
20358 (interactive "*P")
20359 (if (save-excursion
20360 (beginning-of-line (if arg 1 0))
20361 (let ((case-fold-search nil))
20362 (looking-at org-complex-heading-regexp)))
20363 ;; At headline.
20364 (let ((tags-column (when (match-beginning 5)
20365 (save-excursion (goto-char (match-beginning 5))
20366 (current-column))))
20367 (string (concat " " (progn (when arg (forward-line 1))
20368 (org-trim (delete-and-extract-region
20369 (line-beginning-position)
20370 (line-end-position)))))))
20371 (unless (bobp) (delete-region (point) (1- (point))))
20372 (goto-char (or (match-end 4)
20373 (match-beginning 5)
20374 (match-end 0)))
20375 (skip-chars-backward " \t")
20376 (save-excursion (insert string))
20377 ;; Adjust alignment of tags.
20378 (cond
20379 ((not tags-column)) ;no tags
20380 (org-auto-align-tags (org-align-tags))
20381 (t (org--align-tags-here tags-column)))) ;preserve tags column
20382 (delete-indentation arg)))
20384 (defun org-open-line (n)
20385 "Insert a new row in tables, call `open-line' elsewhere.
20386 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20387 As a special case, when a document starts with a table, allow to
20388 call `open-line' on the very first character."
20389 (interactive "*p")
20390 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20391 (org-table-insert-row)
20392 (open-line n)))
20394 (defun org-return (&optional indent)
20395 "Goto next table row or insert a newline.
20397 Calls `org-table-next-row' or `newline', depending on context.
20399 When optional INDENT argument is non-nil, call
20400 `newline-and-indent' instead of `newline'.
20402 When `org-return-follows-link' is non-nil and point is on
20403 a timestamp or a link, call `org-open-at-point'. However, it
20404 will not happen if point is in a table or on a \"dead\"
20405 object (e.g., within a comment). In these case, you need to use
20406 `org-open-at-point' directly."
20407 (interactive)
20408 (let ((context (if org-return-follows-link (org-element-context)
20409 (org-element-at-point))))
20410 (cond
20411 ;; In a table, call `org-table-next-row'. However, before first
20412 ;; column or after last one, split the table.
20413 ((or (and (eq (org-element-type context) 'table)
20414 (>= (point) (org-element-property :contents-begin context))
20415 (< (point) (org-element-property :contents-end context)))
20416 (org-element-lineage context '(table-row table-cell) t))
20417 (if (or (looking-at-p "[ \t]*$")
20418 (save-excursion (skip-chars-backward " \t") (bolp)))
20419 (insert "\n")
20420 (org-table-justify-field-maybe)
20421 (call-interactively #'org-table-next-row)))
20422 ;; On a link or a timestamp, call `org-open-at-point' if
20423 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20424 ;; locations, e.g., in a comment, as `org-open-at-point'.
20425 ((and org-return-follows-link
20426 (or (and (eq 'link (org-element-type context))
20427 ;; Ensure point is not on the white spaces after
20428 ;; the link.
20429 (let ((origin (point)))
20430 (org-with-point-at (org-element-property :end context)
20431 (skip-chars-backward " \t")
20432 (> (point) origin))))
20433 (org-in-regexp org-ts-regexp-both nil t)
20434 (org-in-regexp org-tsr-regexp-both nil t)
20435 (org-in-regexp org-any-link-re nil t)))
20436 (call-interactively #'org-open-at-point))
20437 ;; Insert newline in heading, but preserve tags.
20438 ((and (not (bolp))
20439 (save-excursion (beginning-of-line)
20440 (let ((case-fold-search nil))
20441 (looking-at org-complex-heading-regexp))))
20442 ;; At headline. Split line. However, if point is on keyword,
20443 ;; priority cookie or tags, do not break any of them: add
20444 ;; a newline after the headline instead.
20445 (let ((tags-column (and (match-beginning 5)
20446 (save-excursion (goto-char (match-beginning 5))
20447 (current-column))))
20448 (string
20449 (when (and (match-end 4) (org-point-in-group (point) 4))
20450 (delete-and-extract-region (point) (match-end 4)))))
20451 ;; Adjust tag alignment.
20452 (cond
20453 ((not (and tags-column string)))
20454 (org-auto-align-tags (org-align-tags))
20455 (t (org--align-tags-here tags-column))) ;preserve tags column
20456 (end-of-line)
20457 (org-show-entry)
20458 (if indent (newline-and-indent) (newline))
20459 (when string (save-excursion (insert (org-trim string))))))
20460 ;; In a list, make sure indenting keeps trailing text within.
20461 ((and indent
20462 (not (eolp))
20463 (org-element-lineage context '(item)))
20464 (let ((trailing-data
20465 (delete-and-extract-region (point) (line-end-position))))
20466 (newline-and-indent)
20467 (save-excursion (insert trailing-data))))
20469 ;; Do not auto-fill when point is in an Org property drawer.
20470 (let ((auto-fill-function (and (not (org-at-property-p))
20471 auto-fill-function)))
20472 (if indent
20473 (newline-and-indent)
20474 (newline)))))))
20476 (defun org-return-indent ()
20477 "Goto next table row or insert a newline and indent.
20478 Calls `org-table-next-row' or `newline-and-indent', depending on
20479 context. See the individual commands for more information."
20480 (interactive)
20481 (org-return t))
20483 (defun org-ctrl-c-tab (&optional _arg)
20484 "Toggle columns width in a table, or show children.
20485 Call `org-table-toggle-column-width' if point is in a table.
20486 Otherwise, call `org-show-children'."
20487 (interactive "p")
20488 (call-interactively
20489 (if (org-at-table-p) #'org-table-toggle-column-width
20490 #'org-show-children)))
20492 (defun org-ctrl-c-star ()
20493 "Compute table, or change heading status of lines.
20494 Calls `org-table-recalculate' or `org-toggle-heading',
20495 depending on context."
20496 (interactive)
20497 (cond
20498 ((org-at-table-p)
20499 (call-interactively 'org-table-recalculate))
20501 ;; Convert all lines in region to list items
20502 (call-interactively 'org-toggle-heading))))
20504 (defun org-ctrl-c-minus ()
20505 "Insert separator line in table or modify bullet status of line.
20506 Also turns a plain line or a region of lines into list items.
20507 Calls `org-table-insert-hline', `org-toggle-item', or
20508 `org-cycle-list-bullet', depending on context."
20509 (interactive)
20510 (cond
20511 ((org-at-table-p)
20512 (call-interactively 'org-table-insert-hline))
20513 ((org-region-active-p)
20514 (call-interactively 'org-toggle-item))
20515 ((org-in-item-p)
20516 (call-interactively 'org-cycle-list-bullet))
20518 (call-interactively 'org-toggle-item))))
20520 (defun org-toggle-heading (&optional nstars)
20521 "Convert headings to normal text, or items or text to headings.
20522 If there is no active region, only convert the current line.
20524 With a `\\[universal-argument]' prefix, convert the whole list at
20525 point into heading.
20527 In a region:
20529 - If the first non blank line is a headline, remove the stars
20530 from all headlines in the region.
20532 - If it is a normal line, turn each and every normal line (i.e.,
20533 not an heading or an item) in the region into headings. If you
20534 want to convert only the first line of this region, use one
20535 universal prefix argument.
20537 - If it is a plain list item, turn all plain list items into headings.
20539 When converting a line into a heading, the number of stars is chosen
20540 such that the lines become children of the current entry. However,
20541 when a numeric prefix argument is given, its value determines the
20542 number of stars to add."
20543 (interactive "P")
20544 (let ((skip-blanks
20545 (function
20546 ;; Return beginning of first non-blank line, starting from
20547 ;; line at POS.
20548 (lambda (pos)
20549 (save-excursion
20550 (goto-char pos)
20551 (while (org-at-comment-p) (forward-line))
20552 (skip-chars-forward " \r\t\n")
20553 (point-at-bol)))))
20554 beg end toggled)
20555 ;; Determine boundaries of changes. If a universal prefix has
20556 ;; been given, put the list in a region. If region ends at a bol,
20557 ;; do not consider the last line to be in the region.
20559 (when (and current-prefix-arg (org-at-item-p))
20560 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20561 (org-mark-element))
20563 (if (org-region-active-p)
20564 (setq beg (funcall skip-blanks (region-beginning))
20565 end (copy-marker (save-excursion
20566 (goto-char (region-end))
20567 (if (bolp) (point) (point-at-eol)))))
20568 (setq beg (funcall skip-blanks (point-at-bol))
20569 end (copy-marker (point-at-eol))))
20570 ;; Ensure inline tasks don't count as headings.
20571 (org-with-limited-levels
20572 (save-excursion
20573 (goto-char beg)
20574 (cond
20575 ;; Case 1. Started at an heading: de-star headings.
20576 ((org-at-heading-p)
20577 (while (< (point) end)
20578 (when (org-at-heading-p t)
20579 (looking-at org-outline-regexp) (replace-match "")
20580 (setq toggled t))
20581 (forward-line)))
20582 ;; Case 2. Started at an item: change items into headlines.
20583 ;; One star will be added by `org-list-to-subtree'.
20584 ((org-at-item-p)
20585 (while (< (point) end)
20586 (when (org-at-item-p)
20587 ;; Pay attention to cases when region ends before list.
20588 (let* ((struct (org-list-struct))
20589 (list-end
20590 (min (org-list-get-bottom-point struct) (1+ end))))
20591 (save-restriction
20592 (narrow-to-region (point) list-end)
20593 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20594 (setq toggled t))
20595 (forward-line)))
20596 ;; Case 3. Started at normal text: make every line an heading,
20597 ;; skipping headlines and items.
20598 (t (let* ((stars
20599 (make-string
20600 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20601 (add-stars
20602 (cond (nstars "") ; stars from prefix only
20603 ((equal stars "") "*") ; before first heading
20604 (org-odd-levels-only "**") ; inside heading, odd
20605 (t "*"))) ; inside heading, oddeven
20606 (rpl (concat stars add-stars " "))
20607 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20608 (while (< (point) (if (equal nstars '(4)) lend end))
20609 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20610 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20611 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20612 (forward-line)))))))
20613 (unless toggled (message "Cannot toggle heading from here"))))
20615 (defun org-meta-return (&optional arg)
20616 "Insert a new heading or wrap a region in a table.
20617 Calls `org-insert-heading', `org-insert-item' or
20618 `org-table-wrap-region', depending on context. When called with
20619 an argument, unconditionally call `org-insert-heading'."
20620 (interactive "P")
20621 (org-check-before-invisible-edit 'insert)
20622 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20623 (call-interactively (cond (arg #'org-insert-heading)
20624 ((org-at-table-p) #'org-table-wrap-region)
20625 ((org-in-item-p) #'org-insert-item)
20626 (t #'org-insert-heading)))))
20628 ;;; Menu entries
20630 (defsubst org-in-subtree-not-table-p ()
20631 "Are we in a subtree and not in a table?"
20632 (and (not (org-before-first-heading-p))
20633 (not (org-at-table-p))))
20635 ;; Define the Org mode menus
20636 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20637 '("Tbl"
20638 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20639 ["Next Field" org-cycle (org-at-table-p)]
20640 ["Previous Field" org-shifttab (org-at-table-p)]
20641 ["Next Row" org-return (org-at-table-p)]
20642 "--"
20643 ["Blank Field" org-table-blank-field (org-at-table-p)]
20644 ["Edit Field" org-table-edit-field (org-at-table-p)]
20645 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20646 "--"
20647 ("Column"
20648 ["Move Column Left" org-metaleft (org-at-table-p)]
20649 ["Move Column Right" org-metaright (org-at-table-p)]
20650 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20651 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20652 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20653 ("Row"
20654 ["Move Row Up" org-metaup (org-at-table-p)]
20655 ["Move Row Down" org-metadown (org-at-table-p)]
20656 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20657 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20658 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20659 "--"
20660 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20661 ("Rectangle"
20662 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20663 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20664 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20665 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20666 "--"
20667 ("Calculate"
20668 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20669 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20670 ["Edit Formulas" org-edit-special (org-at-table-p)]
20671 "--"
20672 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20673 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20674 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20675 "--"
20676 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20677 "--"
20678 ["Sum Column/Rectangle" org-table-sum
20679 (or (org-at-table-p) (org-region-active-p))]
20680 ["Which Column?" org-table-current-column (org-at-table-p)])
20681 ["Debug Formulas"
20682 org-table-toggle-formula-debugger
20683 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20684 ["Show Col/Row Numbers"
20685 org-table-toggle-coordinate-overlays
20686 :style toggle
20687 :selected (bound-and-true-p org-table-overlay-coordinates)]
20688 "--"
20689 ["Create" org-table-create (not (org-at-table-p))]
20690 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20691 ["Import from File" org-table-import (not (org-at-table-p))]
20692 ["Export to File" org-table-export (org-at-table-p)]
20693 "--"
20694 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20695 "--"
20696 ("Plot"
20697 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20698 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20700 (easy-menu-define org-org-menu org-mode-map "Org menu"
20701 '("Org"
20702 ("Show/Hide"
20703 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20704 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20705 ["Sparse Tree..." org-sparse-tree t]
20706 ["Reveal Context" org-reveal t]
20707 ["Show All" org-show-all t]
20708 "--"
20709 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20710 "--"
20711 ["New Heading" org-insert-heading t]
20712 ("Navigate Headings"
20713 ["Up" outline-up-heading t]
20714 ["Next" outline-next-visible-heading t]
20715 ["Previous" outline-previous-visible-heading t]
20716 ["Next Same Level" outline-forward-same-level t]
20717 ["Previous Same Level" outline-backward-same-level t]
20718 "--"
20719 ["Jump" org-goto t])
20720 ("Edit Structure"
20721 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20722 "--"
20723 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20724 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20725 "--"
20726 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20727 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20728 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20729 "--"
20730 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20731 "--"
20732 ["Copy visible text" org-copy-visible t]
20733 "--"
20734 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20735 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20736 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20737 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20738 "--"
20739 ["Sort Region/Children" org-sort t]
20740 "--"
20741 ["Convert to odd levels" org-convert-to-odd-levels t]
20742 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20743 ("Editing"
20744 ["Emphasis..." org-emphasize t]
20745 ["Edit Source Example" org-edit-special t]
20746 "--"
20747 ["Footnote new/jump" org-footnote-action t]
20748 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20749 ("Archive"
20750 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20751 "--"
20752 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20753 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20754 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20756 "--"
20757 ("Hyperlinks"
20758 ["Store Link (Global)" org-store-link t]
20759 ["Find existing link to here" org-occur-link-in-agenda-files t]
20760 ["Insert Link" org-insert-link t]
20761 ["Follow Link" org-open-at-point t]
20762 "--"
20763 ["Next link" org-next-link t]
20764 ["Previous link" org-previous-link t]
20765 "--"
20766 ["Descriptive Links"
20767 org-toggle-link-display
20768 :style radio
20769 :selected org-descriptive-links
20771 ["Literal Links"
20772 org-toggle-link-display
20773 :style radio
20774 :selected (not org-descriptive-links)])
20775 "--"
20776 ("TODO Lists"
20777 ["TODO/DONE/-" org-todo t]
20778 ("Select keyword"
20779 ["Next keyword" org-shiftright (org-at-heading-p)]
20780 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20781 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20782 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20783 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20784 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20785 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20786 "--"
20787 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20788 :selected org-enforce-todo-dependencies :style toggle :active t]
20789 "Settings for tree at point"
20790 ["Do Children sequentially" org-toggle-ordered-property :style radio
20791 :selected (org-entry-get nil "ORDERED")
20792 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20793 ["Do Children parallel" org-toggle-ordered-property :style radio
20794 :selected (not (org-entry-get nil "ORDERED"))
20795 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20796 "--"
20797 ["Set Priority" org-priority t]
20798 ["Priority Up" org-shiftup t]
20799 ["Priority Down" org-shiftdown t]
20800 "--"
20801 ["Get news from all feeds" org-feed-update-all t]
20802 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20803 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20804 ("TAGS and Properties"
20805 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20806 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20807 "--"
20808 ["Set property" org-set-property (not (org-before-first-heading-p))]
20809 ["Column view of properties" org-columns t]
20810 ["Insert Column View DBlock" org-columns-insert-dblock t])
20811 ("Dates and Scheduling"
20812 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20813 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20814 ("Change Date"
20815 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20816 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20817 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20818 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20819 ["Compute Time Range" org-evaluate-time-range t]
20820 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20821 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20822 "--"
20823 ["Custom time format" org-toggle-time-stamp-overlays
20824 :style radio :selected org-display-custom-times]
20825 "--"
20826 ["Goto Calendar" org-goto-calendar t]
20827 ["Date from Calendar" org-date-from-calendar t]
20828 "--"
20829 ["Start/Restart Timer" org-timer-start t]
20830 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20831 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20832 ["Insert Timer String" org-timer t]
20833 ["Insert Timer Item" org-timer-item t])
20834 ("Logging work"
20835 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20836 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20837 ["Clock out" org-clock-out t]
20838 ["Clock cancel" org-clock-cancel t]
20839 "--"
20840 ["Mark as default task" org-clock-mark-default-task t]
20841 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20842 ["Goto running clock" org-clock-goto t]
20843 "--"
20844 ["Display times" org-clock-display t]
20845 ["Create clock table" org-clock-report t]
20846 "--"
20847 ["Record DONE time"
20848 (progn (setq org-log-done (not org-log-done))
20849 (message "Switching to %s will %s record a timestamp"
20850 (car org-done-keywords)
20851 (if org-log-done "automatically" "not")))
20852 :style toggle :selected org-log-done])
20853 "--"
20854 ["Agenda Command..." org-agenda t]
20855 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20856 ("File List for Agenda")
20857 ("Special views current file"
20858 ["TODO Tree" org-show-todo-tree t]
20859 ["Check Deadlines" org-check-deadlines t]
20860 ["Tags/Property tree" org-match-sparse-tree t])
20861 "--"
20862 ["Export/Publish..." org-export-dispatch t]
20863 ("LaTeX"
20864 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20865 :style toggle :selected org-cdlatex-mode]
20866 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20867 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20868 ["Modify math symbol" org-cdlatex-math-modify
20869 (org-inside-LaTeX-fragment-p)]
20870 ["Insert citation" org-reftex-citation t])
20871 "--"
20872 ("MobileOrg"
20873 ["Push Files and Views" org-mobile-push t]
20874 ["Get Captured and Flagged" org-mobile-pull t]
20875 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20876 "--"
20877 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20878 "--"
20879 ("Documentation"
20880 ["Show Version" org-version t]
20881 ["Info Documentation" org-info t])
20882 ("Customize"
20883 ["Browse Org Group" org-customize t]
20884 "--"
20885 ["Expand This Menu" org-create-customize-menu
20886 (fboundp 'customize-menu-create)])
20887 ["Send bug report" org-submit-bug-report t]
20888 "--"
20889 ("Refresh/Reload"
20890 ["Refresh setup current buffer" org-mode-restart t]
20891 ["Reload Org (after update)" org-reload t]
20892 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20895 (defun org-info (&optional node)
20896 "Read documentation for Org in the info system.
20897 With optional NODE, go directly to that node."
20898 (interactive)
20899 (info (format "(org)%s" (or node ""))))
20901 ;;;###autoload
20902 (defun org-submit-bug-report ()
20903 "Submit a bug report on Org via mail.
20905 Don't hesitate to report any problems or inaccurate documentation.
20907 If you don't have setup sending mail from (X)Emacs, please copy the
20908 output buffer into your mail program, as it gives us important
20909 information about your Org version and configuration."
20910 (interactive)
20911 (require 'reporter)
20912 (defvar reporter-prompt-for-summary-p)
20913 (org-load-modules-maybe)
20914 (org-require-autoloaded-modules)
20915 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20916 (reporter-submit-bug-report
20917 "emacs-orgmode@gnu.org"
20918 (org-version nil 'full)
20919 (let (list)
20920 (save-window-excursion
20921 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20922 (delete-other-windows)
20923 (erase-buffer)
20924 (insert "You are about to submit a bug report to the Org mailing list.
20926 We would like to add your full Org and Outline configuration to the
20927 bug report. This greatly simplifies the work of the maintainer and
20928 other experts on the mailing list.
20930 HOWEVER, some variables you have customized may contain private
20931 information. The names of customers, colleagues, or friends, might
20932 appear in the form of file names, tags, todo states, or search strings.
20933 If you answer yes to the prompt, you might want to check and remove
20934 such private information before sending the email.")
20935 (add-text-properties (point-min) (point-max) '(face org-warning))
20936 (when (yes-or-no-p "Include your Org configuration ")
20937 (mapatoms
20938 (lambda (v)
20939 (and (boundp v)
20940 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20941 (or (and (symbol-value v)
20942 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20943 (and
20944 (get v 'custom-type) (get v 'standard-value)
20945 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20946 (push v list)))))
20947 (kill-buffer (get-buffer "*Warn about privacy*"))
20948 list))
20949 nil nil
20950 "Remember to cover the basics, that is, what you expected to happen and
20951 what in fact did happen. You don't know how to make a good report? See
20953 https://orgmode.org/manual/Feedback.html#Feedback
20955 Your bug report will be posted to the Org mailing list.
20956 ------------------------------------------------------------------------")
20957 (save-excursion
20958 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20959 (replace-match "\\1Bug: \\3 [\\2]")))))
20962 (defun org-install-agenda-files-menu ()
20963 (let ((bl (buffer-list)))
20964 (save-excursion
20965 (while bl
20966 (set-buffer (pop bl))
20967 (when (derived-mode-p 'org-mode) (setq bl nil)))
20968 (when (derived-mode-p 'org-mode)
20969 (easy-menu-change
20970 '("Org") "File List for Agenda"
20971 (append
20972 (list
20973 ["Edit File List" (org-edit-agenda-file-list) t]
20974 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20975 ["Remove Current File from List" org-remove-file t]
20976 ["Cycle through agenda files" org-cycle-agenda-files t]
20977 ["Occur in all agenda files" org-occur-in-agenda-files t]
20978 "--")
20979 (mapcar 'org-file-menu-entry
20980 ;; Prevent initialization from failing.
20981 (ignore-errors (org-agenda-files t)))))))))
20983 ;;;; Documentation
20985 (defun org-require-autoloaded-modules ()
20986 (interactive)
20987 (mapc #'require
20988 '(org-agenda org-archive org-attach org-clock org-colview org-id
20989 org-table org-timer)))
20991 ;;;###autoload
20992 (defun org-reload (&optional uncompiled)
20993 "Reload all Org Lisp files.
20994 With prefix arg UNCOMPILED, load the uncompiled versions."
20995 (interactive "P")
20996 (require 'loadhist)
20997 (let* ((org-dir (org-find-library-dir "org"))
20998 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20999 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21000 (remove-re (format "\\`%s\\'"
21001 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21002 (feats (delete-dups
21003 (mapcar 'file-name-sans-extension
21004 (mapcar 'file-name-nondirectory
21005 (delq nil
21006 (mapcar 'feature-file
21007 features))))))
21008 (lfeat (append
21009 (sort
21010 (setq feats
21011 (delq nil (mapcar
21012 (lambda (f)
21013 (if (and (string-match feature-re f)
21014 (not (string-match remove-re f)))
21015 f nil))
21016 feats)))
21017 'string-lessp)
21018 (list "org-version" "org")))
21019 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21020 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21021 load-uncore load-misses)
21022 (setq load-misses
21023 (delq 't
21024 (mapcar (lambda (f)
21025 (or (org-load-noerror-mustsuffix (concat org-dir f))
21026 (and (string= org-dir contrib-dir)
21027 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21028 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21029 (add-to-list 'load-uncore f 'append)
21032 lfeat)))
21033 (when load-uncore
21034 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21035 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21036 (if load-misses
21037 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21038 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21039 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21041 ;;;###autoload
21042 (defun org-customize ()
21043 "Call the customize function with org as argument."
21044 (interactive)
21045 (org-load-modules-maybe)
21046 (org-require-autoloaded-modules)
21047 (customize-browse 'org))
21049 (defun org-create-customize-menu ()
21050 "Create a full customization menu for Org mode, insert it into the menu."
21051 (interactive)
21052 (org-load-modules-maybe)
21053 (org-require-autoloaded-modules)
21054 (if (fboundp 'customize-menu-create)
21055 (progn
21056 (easy-menu-change
21057 '("Org") "Customize"
21058 `(["Browse Org group" org-customize t]
21059 "--"
21060 ,(customize-menu-create 'org)
21061 ["Set" Custom-set t]
21062 ["Save" Custom-save t]
21063 ["Reset to Current" Custom-reset-current t]
21064 ["Reset to Saved" Custom-reset-saved t]
21065 ["Reset to Standard Settings" Custom-reset-standard t]))
21066 (message "\"Org\"-menu now contains full customization menu"))
21067 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21069 ;;;; Miscellaneous stuff
21071 ;;; Generally useful functions
21073 (defun org-link-display-format (s)
21074 "Replace links in string S with their description.
21075 If there is no description, use the link target."
21076 (save-match-data
21077 (replace-regexp-in-string
21078 org-bracket-link-analytic-regexp
21079 (lambda (m)
21080 (if (match-end 5) (match-string 5 m)
21081 (concat (match-string 1 m) (match-string 3 m))))
21082 s nil t)))
21084 (defun org-toggle-link-display ()
21085 "Toggle the literal or descriptive display of links."
21086 (interactive)
21087 (if org-descriptive-links
21088 (progn (org-remove-from-invisibility-spec '(org-link))
21089 (org-restart-font-lock)
21090 (setq org-descriptive-links nil))
21091 (progn (add-to-invisibility-spec '(org-link))
21092 (org-restart-font-lock)
21093 (setq org-descriptive-links t))))
21095 (defun org-in-clocktable-p ()
21096 "Check if the cursor is in a clocktable."
21097 (let ((pos (point)) start)
21098 (save-excursion
21099 (end-of-line 1)
21100 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21101 (setq start (match-beginning 0))
21102 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21103 (>= (match-end 0) pos)
21104 start))))
21106 (defun org-in-verbatim-emphasis ()
21107 (save-match-data
21108 (and (org-in-regexp org-verbatim-re 2)
21109 (>= (point) (match-beginning 3))
21110 (<= (point) (match-end 4)))))
21112 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21113 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21114 (if (and marker (marker-buffer marker)
21115 (buffer-live-p (marker-buffer marker)))
21116 (progn
21117 (pop-to-buffer-same-window (marker-buffer marker))
21118 (when (or (> marker (point-max)) (< marker (point-min)))
21119 (widen))
21120 (goto-char marker)
21121 (org-show-context 'org-goto))
21122 (if bookmark
21123 (bookmark-jump bookmark)
21124 (error "Cannot find location"))))
21126 (defun org-quote-csv-field (s)
21127 "Quote field for inclusion in CSV material."
21128 (if (string-match "[\",]" s)
21129 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21132 (defun org-force-self-insert (N)
21133 "Needed to enforce self-insert under remapping."
21134 (interactive "p")
21135 (self-insert-command N))
21137 (defun org-fill-template (template alist)
21138 "Find each %key of ALIST in TEMPLATE and replace it."
21139 (let ((case-fold-search nil))
21140 (dolist (entry (sort (copy-sequence alist)
21141 (lambda (a b) (< (length (car a)) (length (car b))))))
21142 (setq template
21143 (replace-regexp-in-string
21144 (concat "%" (regexp-quote (car entry)))
21145 (or (cdr entry) "") template t t)))
21146 template))
21148 (defun org-quote-vert (s)
21149 "Replace \"|\" with \"\\vert\"."
21150 (while (string-match "|" s)
21151 (setq s (replace-match "\\vert" t t s)))
21154 (defun org-uuidgen-p (s)
21155 "Is S an ID created by UUIDGEN?"
21156 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21158 (defun org-in-src-block-p (&optional inside)
21159 "Whether point is in a code source block.
21160 When INSIDE is non-nil, don't consider we are within a src block
21161 when point is at #+BEGIN_SRC or #+END_SRC."
21162 (let ((case-fold-search t))
21163 (or (and (eq (get-char-property (point) 'src-block) t))
21164 (and (not inside)
21165 (save-match-data
21166 (save-excursion
21167 (beginning-of-line)
21168 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21170 (defun org-context ()
21171 "Return a list of contexts of the current cursor position.
21172 If several contexts apply, all are returned.
21173 Each context entry is a list with a symbol naming the context, and
21174 two positions indicating start and end of the context. Possible
21175 contexts are:
21177 :headline anywhere in a headline
21178 :headline-stars on the leading stars in a headline
21179 :todo-keyword on a TODO keyword (including DONE) in a headline
21180 :tags on the TAGS in a headline
21181 :priority on the priority cookie in a headline
21182 :item on the first line of a plain list item
21183 :item-bullet on the bullet/number of a plain list item
21184 :checkbox on the checkbox in a plain list item
21185 :table in an Org table
21186 :table-special on a special filed in a table
21187 :table-table in a table.el table
21188 :clocktable in a clocktable
21189 :src-block in a source block
21190 :link on a hyperlink
21191 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21192 :target on a <<target>>
21193 :radio-target on a <<<radio-target>>>
21194 :latex-fragment on a LaTeX fragment
21195 :latex-preview on a LaTeX fragment with overlaid preview image
21197 This function expects the position to be visible because it uses font-lock
21198 faces as a help to recognize the following contexts: :table-special, :link,
21199 and :keyword."
21200 (let* ((f (get-text-property (point) 'face))
21201 (faces (if (listp f) f (list f)))
21202 (case-fold-search t)
21203 (p (point)) clist o)
21204 ;; First the large context
21205 (cond
21206 ((org-at-heading-p t)
21207 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21208 (when (progn
21209 (beginning-of-line 1)
21210 (looking-at org-todo-line-tags-regexp))
21211 (push (org-point-in-group p 1 :headline-stars) clist)
21212 (push (org-point-in-group p 2 :todo-keyword) clist)
21213 (push (org-point-in-group p 4 :tags) clist))
21214 (goto-char p)
21215 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21216 (when (looking-at "\\[#[A-Z0-9]\\]")
21217 (push (org-point-in-group p 0 :priority) clist)))
21219 ((org-at-item-p)
21220 (push (org-point-in-group p 2 :item-bullet) clist)
21221 (push (list :item (point-at-bol)
21222 (save-excursion (org-end-of-item) (point)))
21223 clist)
21224 (and (org-at-item-checkbox-p)
21225 (push (org-point-in-group p 0 :checkbox) clist)))
21227 ((org-at-table-p)
21228 (push (list :table (org-table-begin) (org-table-end)) clist)
21229 (when (memq 'org-formula faces)
21230 (push (list :table-special
21231 (previous-single-property-change p 'face)
21232 (next-single-property-change p 'face)) clist)))
21233 ((org-at-table-p 'any)
21234 (push (list :table-table) clist)))
21235 (goto-char p)
21237 (let ((case-fold-search t))
21238 ;; New the "medium" contexts: clocktables, source blocks
21239 (cond ((org-in-clocktable-p)
21240 (push (list :clocktable
21241 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21242 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21243 (match-beginning 1))
21244 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21245 (match-end 0))) clist))
21246 ((org-in-src-block-p)
21247 (push (list :src-block
21248 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21249 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21250 (match-beginning 1))
21251 (and (search-forward "#+END_SRC" nil t)
21252 (match-beginning 0))) clist))))
21253 (goto-char p)
21255 ;; Now the small context
21256 (cond
21257 ((org-at-timestamp-p)
21258 (push (org-point-in-group p 0 :timestamp) clist))
21259 ((memq 'org-link faces)
21260 (push (list :link
21261 (previous-single-property-change p 'face)
21262 (next-single-property-change p 'face)) clist))
21263 ((memq 'org-special-keyword faces)
21264 (push (list :keyword
21265 (previous-single-property-change p 'face)
21266 (next-single-property-change p 'face)) clist))
21267 ((org-at-target-p)
21268 (push (org-point-in-group p 0 :target) clist)
21269 (goto-char (1- (match-beginning 0)))
21270 (when (looking-at org-radio-target-regexp)
21271 (push (org-point-in-group p 0 :radio-target) clist))
21272 (goto-char p))
21273 ((setq o (cl-some
21274 (lambda (o)
21275 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21277 (overlays-at (point))))
21278 (push (list :latex-fragment
21279 (overlay-start o) (overlay-end o)) clist)
21280 (push (list :latex-preview
21281 (overlay-start o) (overlay-end o)) clist))
21282 ((org-inside-LaTeX-fragment-p)
21283 ;; FIXME: positions wrong.
21284 (push (list :latex-fragment (point) (point)) clist)))
21286 (setq clist (nreverse (delq nil clist)))
21287 clist))
21289 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21290 "Non-nil when point is between matches of START-RE and END-RE.
21292 Also return a non-nil value when point is on one of the matches.
21294 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21295 buffer positions. Default values are the positions of headlines
21296 surrounding the point.
21298 The functions returns a cons cell whose car (resp. cdr) is the
21299 position before START-RE (resp. after END-RE)."
21300 (save-match-data
21301 (let ((pos (point))
21302 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21303 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21304 beg end)
21305 (save-excursion
21306 ;; Point is on a block when on START-RE or if START-RE can be
21307 ;; found before it...
21308 (and (or (org-in-regexp start-re)
21309 (re-search-backward start-re limit-up t))
21310 (setq beg (match-beginning 0))
21311 ;; ... and END-RE after it...
21312 (goto-char (match-end 0))
21313 (re-search-forward end-re limit-down t)
21314 (> (setq end (match-end 0)) pos)
21315 ;; ... without another START-RE in-between.
21316 (goto-char (match-beginning 0))
21317 (not (re-search-backward start-re (1+ beg) t))
21318 ;; Return value.
21319 (cons beg end))))))
21321 (defun org-in-block-p (names)
21322 "Non-nil when point belongs to a block whose name belongs to NAMES.
21324 NAMES is a list of strings containing names of blocks.
21326 Return first block name matched, or nil. Beware that in case of
21327 nested blocks, the returned name may not belong to the closest
21328 block from point."
21329 (save-match-data
21330 (catch 'exit
21331 (let ((case-fold-search t)
21332 (lim-up (save-excursion (outline-previous-heading)))
21333 (lim-down (save-excursion (outline-next-heading))))
21334 (dolist (name names)
21335 (let ((n (regexp-quote name)))
21336 (when (org-between-regexps-p
21337 (concat "^[ \t]*#\\+begin_" n)
21338 (concat "^[ \t]*#\\+end_" n)
21339 lim-up lim-down)
21340 (throw 'exit n)))))
21341 nil)))
21343 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21344 "Call `multi-occur' with buffers for all agenda files."
21345 (interactive "sOrg-files matching: ")
21346 (let* ((files (org-agenda-files))
21347 (tnames (mapcar #'file-truename files))
21348 (extra org-agenda-text-search-extra-files))
21349 (when (eq (car extra) 'agenda-archives)
21350 (setq extra (cdr extra))
21351 (setq files (org-add-archive-files files)))
21352 (dolist (f extra)
21353 (unless (member (file-truename f) tnames)
21354 (unless (member f files) (setq files (append files (list f))))
21355 (setq tnames (append tnames (list (file-truename f))))))
21356 (multi-occur
21357 (mapcar (lambda (x)
21358 (with-current-buffer
21359 ;; FIXME: Why not just (find-file-noselect x)?
21360 ;; Is it to avoid the "revert buffer" prompt?
21361 (or (get-file-buffer x) (find-file-noselect x))
21362 (widen)
21363 (current-buffer)))
21364 files)
21365 regexp)))
21367 (add-hook 'occur-mode-find-occurrence-hook
21368 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21370 (defun org-occur-link-in-agenda-files ()
21371 "Create a link and search for it in the agendas.
21372 The link is not stored in `org-stored-links', it is just created
21373 for the search purpose."
21374 (interactive)
21375 (let ((link (condition-case nil
21376 (org-store-link nil)
21377 (error "Unable to create a link to here"))))
21378 (org-occur-in-agenda-files (regexp-quote link))))
21380 (defun org-back-over-empty-lines ()
21381 "Move backwards over whitespace, to the beginning of the first empty line.
21382 Returns the number of empty lines passed."
21383 (let ((pos (point)))
21384 (if (cdr (assq 'heading org-blank-before-new-entry))
21385 (skip-chars-backward " \t\n\r")
21386 (unless (eobp)
21387 (forward-line -1)))
21388 (beginning-of-line 2)
21389 (goto-char (min (point) pos))
21390 (count-lines (point) pos)))
21392 (defun org-switch-to-buffer-other-window (&rest args)
21393 "Switch to buffer in a second window on the current frame.
21394 In particular, do not allow pop-up frames.
21395 Returns the newly created buffer."
21396 (org-no-popups
21397 (apply 'switch-to-buffer-other-window args)))
21399 (defun org-replace-escapes (string table)
21400 "Replace %-escapes in STRING with values in TABLE.
21401 TABLE is an association list with keys like \"%a\" and string values.
21402 The sequences in STRING may contain normal field width and padding information,
21403 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21404 so values can contain further %-escapes if they are define later in TABLE."
21405 (let ((tbl (copy-alist table))
21406 (case-fold-search nil)
21407 (pchg 0)
21408 re rpl)
21409 (dolist (e tbl)
21410 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21411 (when (and (cdr e) (string-match re (cdr e)))
21412 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21413 (safe "SREF"))
21414 (add-text-properties 0 3 (list 'sref sref) safe)
21415 (setcdr e (replace-match safe t t (cdr e)))))
21416 (while (string-match re string)
21417 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21418 (cdr e)))
21419 (setq string (replace-match rpl t t string))))
21420 (while (setq pchg (next-property-change pchg string))
21421 (let ((sref (get-text-property pchg 'sref string)))
21422 (when (and sref (string-match "SREF" string pchg))
21423 (setq string (replace-match sref t t string)))))
21424 string))
21426 ;;; TODO: Only called once, from ox-odt which should probably use
21427 ;;; org-export-inline-image-p or something.
21428 (defun org-file-image-p (file)
21429 "Return non-nil if FILE is an image."
21430 (save-match-data
21431 (string-match (image-file-name-regexp) file)))
21433 (defun org-get-cursor-date (&optional with-time)
21434 "Return the date at cursor in as a time.
21435 This works in the calendar and in the agenda, anywhere else it just
21436 returns the current time.
21437 If WITH-TIME is non-nil, returns the time of the event at point (in
21438 the agenda) or the current time of the day."
21439 (let (date day defd tp hod mod)
21440 (when with-time
21441 (setq tp (get-text-property (point) 'time))
21442 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21443 (setq hod (string-to-number (match-string 1 tp))
21444 mod (string-to-number (match-string 2 tp))))
21445 (or tp (let ((now (decode-time)))
21446 (setq hod (nth 2 now)
21447 mod (nth 1 now)))))
21448 (cond
21449 ((eq major-mode 'calendar-mode)
21450 (setq date (calendar-cursor-to-date)
21451 defd (encode-time 0 (or mod 0) (or hod 0)
21452 (nth 1 date) (nth 0 date) (nth 2 date))))
21453 ((eq major-mode 'org-agenda-mode)
21454 (setq day (get-text-property (point) 'day))
21455 (when day
21456 (setq date (calendar-gregorian-from-absolute day)
21457 defd (encode-time 0 (or mod 0) (or hod 0)
21458 (nth 1 date) (nth 0 date) (nth 2 date))))))
21459 (or defd (current-time))))
21461 (defun org-mark-subtree (&optional up)
21462 "Mark the current subtree.
21463 This puts point at the start of the current subtree, and mark at
21464 the end. If a numeric prefix UP is given, move up into the
21465 hierarchy of headlines by UP levels before marking the subtree."
21466 (interactive "P")
21467 (org-with-limited-levels
21468 (cond ((org-at-heading-p) (beginning-of-line))
21469 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21470 (t (outline-previous-visible-heading 1))))
21471 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21472 (if (called-interactively-p 'any)
21473 (call-interactively 'org-mark-element)
21474 (org-mark-element)))
21476 ;;; Indentation
21478 (defvar org-element-greater-elements)
21479 (defun org--get-expected-indentation (element contentsp)
21480 "Expected indentation column for current line, according to ELEMENT.
21481 ELEMENT is an element containing point. CONTENTSP is non-nil
21482 when indentation is to be computed according to contents of
21483 ELEMENT."
21484 (let ((type (org-element-type element))
21485 (start (org-element-property :begin element))
21486 (post-affiliated (org-element-property :post-affiliated element)))
21487 (org-with-wide-buffer
21488 (cond
21489 (contentsp
21490 (cl-case type
21491 ((diary-sexp footnote-definition) 0)
21492 ((headline inlinetask nil)
21493 (if (not org-adapt-indentation) 0
21494 (let ((level (org-current-level)))
21495 (if level (1+ level) 0))))
21496 ((item plain-list) (org-list-item-body-column post-affiliated))
21498 (goto-char start)
21499 (org-get-indentation))))
21500 ((memq type '(headline inlinetask nil))
21501 (if (org-match-line "[ \t]*$")
21502 (org--get-expected-indentation element t)
21504 ((memq type '(diary-sexp footnote-definition)) 0)
21505 ;; First paragraph of a footnote definition or an item.
21506 ;; Indent like parent.
21507 ((< (line-beginning-position) start)
21508 (org--get-expected-indentation
21509 (org-element-property :parent element) t))
21510 ;; At first line: indent according to previous sibling, if any,
21511 ;; ignoring footnote definitions and inline tasks, or parent's
21512 ;; contents.
21513 ((= (line-beginning-position) start)
21514 (catch 'exit
21515 (while t
21516 (if (= (point-min) start) (throw 'exit 0)
21517 (goto-char (1- start))
21518 (let* ((previous (org-element-at-point))
21519 (parent previous))
21520 (while (and parent (<= (org-element-property :end parent) start))
21521 (setq previous parent
21522 parent (org-element-property :parent parent)))
21523 (cond
21524 ((not previous) (throw 'exit 0))
21525 ((> (org-element-property :end previous) start)
21526 (throw 'exit (org--get-expected-indentation previous t)))
21527 ((memq (org-element-type previous)
21528 '(footnote-definition inlinetask))
21529 (setq start (org-element-property :begin previous)))
21530 (t (goto-char (org-element-property :begin previous))
21531 (throw 'exit
21532 (if (bolp) (org-get-indentation)
21533 ;; At first paragraph in an item or
21534 ;; a footnote definition.
21535 (org--get-expected-indentation
21536 (org-element-property :parent previous) t))))))))))
21537 ;; Otherwise, move to the first non-blank line above.
21539 (beginning-of-line)
21540 (let ((pos (point)))
21541 (skip-chars-backward " \r\t\n")
21542 (cond
21543 ;; Two blank lines end a footnote definition or a plain
21544 ;; list. When we indent an empty line after them, the
21545 ;; containing list or footnote definition is over, so it
21546 ;; qualifies as a previous sibling. Therefore, we indent
21547 ;; like its first line.
21548 ((and (memq type '(footnote-definition plain-list))
21549 (> (count-lines (point) pos) 2))
21550 (goto-char start)
21551 (org-get-indentation))
21552 ;; Line above is the first one of a paragraph at the
21553 ;; beginning of an item or a footnote definition. Indent
21554 ;; like parent.
21555 ((< (line-beginning-position) start)
21556 (org--get-expected-indentation
21557 (org-element-property :parent element) t))
21558 ;; Line above is the beginning of an element, i.e., point
21559 ;; was originally on the blank lines between element's start
21560 ;; and contents.
21561 ((= (line-beginning-position) post-affiliated)
21562 (org--get-expected-indentation element t))
21563 ;; POS is after contents in a greater element. Indent like
21564 ;; the beginning of the element.
21565 ((and (memq type org-element-greater-elements)
21566 (let ((cend (org-element-property :contents-end element)))
21567 (and cend (<= cend pos))))
21568 ;; As a special case, if point is at the end of a footnote
21569 ;; definition or an item, indent like the very last element
21570 ;; within. If that last element is an item, indent like
21571 ;; its contents.
21572 (if (memq type '(footnote-definition item plain-list))
21573 (let ((last (org-element-at-point)))
21574 (goto-char pos)
21575 (org--get-expected-indentation
21576 last (eq (org-element-type last) 'item)))
21577 (goto-char start)
21578 (org-get-indentation)))
21579 ;; In any other case, indent like the current line.
21580 (t (org-get-indentation)))))))))
21582 (defun org--align-node-property ()
21583 "Align node property at point.
21584 Alignment is done according to `org-property-format', which see."
21585 (when (save-excursion
21586 (beginning-of-line)
21587 (looking-at org-property-re))
21588 (replace-match
21589 (concat (match-string 4)
21590 (org-trim
21591 (format org-property-format (match-string 1) (match-string 3))))
21592 t t)))
21594 (defun org-indent-line ()
21595 "Indent line depending on context.
21597 Indentation is done according to the following rules:
21599 - Footnote definitions, diary sexps, headlines and inline tasks
21600 have to start at column 0.
21602 - On the very first line of an element, consider, in order, the
21603 next rules until one matches:
21605 1. If there's a sibling element before, ignoring footnote
21606 definitions and inline tasks, indent like its first line.
21608 2. If element has a parent, indent like its contents. More
21609 precisely, if parent is an item, indent after the
21610 description part, if any, or the bullet (see
21611 `org-list-description-max-indent'). Else, indent like
21612 parent's first line.
21614 3. Otherwise, indent relatively to current level, if
21615 `org-adapt-indentation' is non-nil, or to left margin.
21617 - On a blank line at the end of an element, indent according to
21618 the type of the element. More precisely
21620 1. If element is a plain list, an item, or a footnote
21621 definition, indent like the very last element within.
21623 2. If element is a paragraph, indent like its last non blank
21624 line.
21626 3. Otherwise, indent like its very first line.
21628 - In the code part of a source block, use language major mode
21629 to indent current line if `org-src-tab-acts-natively' is
21630 non-nil. If it is nil, do nothing.
21632 - Otherwise, indent like the first non-blank line above.
21634 The function doesn't indent an item as it could break the whole
21635 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21636 `\\[org-shiftmetaright]'.
21638 Also align node properties according to `org-property-format'."
21639 (interactive)
21640 (cond
21641 ((org-at-heading-p) 'noindent)
21643 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21644 (type (org-element-type element)))
21645 (cond ((and (memq type '(plain-list item))
21646 (= (line-beginning-position)
21647 (org-element-property :post-affiliated element)))
21648 'noindent)
21649 ((and (eq type 'latex-environment)
21650 (>= (point) (org-element-property :post-affiliated element))
21651 (< (point) (org-with-wide-buffer
21652 (goto-char (org-element-property :end element))
21653 (skip-chars-backward " \r\t\n")
21654 (line-beginning-position 2))))
21655 'noindent)
21656 ((and (eq type 'src-block)
21657 org-src-tab-acts-natively
21658 (> (line-beginning-position)
21659 (org-element-property :post-affiliated element))
21660 (< (line-beginning-position)
21661 (org-with-wide-buffer
21662 (goto-char (org-element-property :end element))
21663 (skip-chars-backward " \r\t\n")
21664 (line-beginning-position))))
21665 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21667 (let ((column (org--get-expected-indentation element nil)))
21668 ;; Preserve current column.
21669 (if (<= (current-column) (current-indentation))
21670 (indent-line-to column)
21671 (save-excursion (indent-line-to column))))
21672 ;; Align node property. Also preserve current column.
21673 (when (eq type 'node-property)
21674 (let ((column (current-column)))
21675 (org--align-node-property)
21676 (org-move-to-column column)))))))))
21678 (defun org-indent-region (start end)
21679 "Indent each non-blank line in the region.
21680 Called from a program, START and END specify the region to
21681 indent. The function will not indent contents of example blocks,
21682 verse blocks and export blocks as leading white spaces are
21683 assumed to be significant there."
21684 (interactive "r")
21685 (save-excursion
21686 (goto-char start)
21687 (skip-chars-forward " \r\t\n")
21688 (unless (eobp) (beginning-of-line))
21689 (let ((indent-to
21690 (lambda (ind pos)
21691 ;; Set IND as indentation for all lines between point and
21692 ;; POS. Blank lines are ignored. Leave point after POS
21693 ;; once done.
21694 (let ((limit (copy-marker pos)))
21695 (while (< (point) limit)
21696 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21697 (forward-line))
21698 (set-marker limit nil))))
21699 (end (copy-marker end)))
21700 (while (< (point) end)
21701 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21702 (let* ((element (org-element-at-point))
21703 (type (org-element-type element))
21704 (element-end (copy-marker (org-element-property :end element)))
21705 (ind (org--get-expected-indentation element nil)))
21706 (cond
21707 ;; Element indented as a single block. Example blocks
21708 ;; preserving indentation are a special case since the
21709 ;; "contents" must not be indented whereas the block
21710 ;; boundaries can.
21711 ((or (memq type '(export-block latex-environment))
21712 (and (eq type 'example-block)
21713 (not
21714 (or org-src-preserve-indentation
21715 (org-element-property :preserve-indent element)))))
21716 (let ((offset (- ind (org-get-indentation))))
21717 (unless (zerop offset)
21718 (indent-rigidly (org-element-property :begin element)
21719 (org-element-property :end element)
21720 offset)))
21721 (goto-char element-end))
21722 ;; Elements indented line wise. Be sure to exclude
21723 ;; example blocks (preserving indentation) and source
21724 ;; blocks from this category as they are treated
21725 ;; specially later.
21726 ((or (memq type '(paragraph table table-row))
21727 (not (or (org-element-property :contents-begin element)
21728 (memq type '(example-block src-block)))))
21729 (when (eq type 'node-property)
21730 (org--align-node-property)
21731 (beginning-of-line))
21732 (funcall indent-to ind (min element-end end)))
21733 ;; Elements consisting of three parts: before the
21734 ;; contents, the contents, and after the contents. The
21735 ;; contents are treated specially, according to the
21736 ;; element type, or not indented at all. Other parts are
21737 ;; indented as a single block.
21739 (let* ((post (copy-marker
21740 (org-element-property :post-affiliated element)))
21741 (cbeg
21742 (copy-marker
21743 (cond
21744 ((not (org-element-property :contents-begin element))
21745 ;; Fake contents for source blocks.
21746 (org-with-wide-buffer
21747 (goto-char post)
21748 (line-beginning-position 2)))
21749 ((memq type '(footnote-definition item plain-list))
21750 ;; Contents in these elements could start on
21751 ;; the same line as the beginning of the
21752 ;; element. Make sure we start indenting
21753 ;; from the second line.
21754 (org-with-wide-buffer
21755 (goto-char post)
21756 (end-of-line)
21757 (skip-chars-forward " \r\t\n")
21758 (if (eobp) (point) (line-beginning-position))))
21759 (t (org-element-property :contents-begin element)))))
21760 (cend (copy-marker
21761 (or (org-element-property :contents-end element)
21762 ;; Fake contents for source blocks.
21763 (org-with-wide-buffer
21764 (goto-char element-end)
21765 (skip-chars-backward " \r\t\n")
21766 (line-beginning-position)))
21767 t)))
21768 ;; Do not change items indentation individually as it
21769 ;; might break the list as a whole. On the other
21770 ;; hand, when at a plain list, indent it as a whole.
21771 (cond ((eq type 'plain-list)
21772 (let ((offset (- ind (org-get-indentation))))
21773 (unless (zerop offset)
21774 (indent-rigidly (org-element-property :begin element)
21775 (org-element-property :end element)
21776 offset))
21777 (goto-char cbeg)))
21778 ((eq type 'item) (goto-char cbeg))
21779 (t (funcall indent-to ind (min cbeg end))))
21780 (when (< (point) end)
21781 (cl-case type
21782 ((example-block verse-block))
21783 (src-block
21784 ;; In a source block, indent source code
21785 ;; according to language major mode, but only if
21786 ;; `org-src-tab-acts-natively' is non-nil.
21787 (when (and (< (point) end) org-src-tab-acts-natively)
21788 (ignore-errors
21789 (org-babel-do-in-edit-buffer
21790 (indent-region (point-min) (point-max))))))
21791 (t (org-indent-region (point) (min cend end))))
21792 (goto-char (min cend end))
21793 (when (< (point) end)
21794 (funcall indent-to ind (min element-end end))))
21795 (set-marker post nil)
21796 (set-marker cbeg nil)
21797 (set-marker cend nil))))
21798 (set-marker element-end nil))))
21799 (set-marker end nil))))
21801 (defun org-indent-drawer ()
21802 "Indent the drawer at point."
21803 (interactive)
21804 (unless (save-excursion
21805 (beginning-of-line)
21806 (looking-at-p org-drawer-regexp))
21807 (user-error "Not at a drawer"))
21808 (let ((element (org-element-at-point)))
21809 (unless (memq (org-element-type element) '(drawer property-drawer))
21810 (user-error "Not at a drawer"))
21811 (org-with-wide-buffer
21812 (org-indent-region (org-element-property :begin element)
21813 (org-element-property :end element))))
21814 (message "Drawer at point indented"))
21816 (defun org-indent-block ()
21817 "Indent the block at point."
21818 (interactive)
21819 (unless (save-excursion
21820 (beginning-of-line)
21821 (let ((case-fold-search t))
21822 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21823 (user-error "Not at a block"))
21824 (let ((element (org-element-at-point)))
21825 (unless (memq (org-element-type element)
21826 '(comment-block center-block dynamic-block example-block
21827 export-block quote-block special-block
21828 src-block verse-block))
21829 (user-error "Not at a block"))
21830 (org-with-wide-buffer
21831 (org-indent-region (org-element-property :begin element)
21832 (org-element-property :end element))))
21833 (message "Block at point indented"))
21836 ;;; Filling
21838 ;; We use our own fill-paragraph and auto-fill functions.
21840 ;; `org-fill-paragraph' relies on adaptive filling and context
21841 ;; checking. Appropriate `fill-prefix' is computed with
21842 ;; `org-adaptive-fill-function'.
21844 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21845 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21846 ;; `org-adaptive-fill-function' value. Internally,
21847 ;; `org-comment-line-break-function' breaks the line.
21849 ;; `org-setup-filling' installs filling and auto-filling related
21850 ;; variables during `org-mode' initialization.
21852 (defun org-setup-filling ()
21853 (require 'org-element)
21854 ;; Prevent auto-fill from inserting unwanted new items.
21855 (when (boundp 'fill-nobreak-predicate)
21856 (setq-local
21857 fill-nobreak-predicate
21858 (org-uniquify
21859 (append fill-nobreak-predicate
21860 '(org-fill-line-break-nobreak-p
21861 org-fill-n-macro-as-item-nobreak-p
21862 org-fill-paragraph-with-timestamp-nobreak-p)))))
21863 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21864 (setq-local paragraph-start paragraph-ending)
21865 (setq-local paragraph-separate paragraph-ending))
21866 (setq-local fill-paragraph-function 'org-fill-paragraph)
21867 (setq-local auto-fill-inhibit-regexp nil)
21868 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21869 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21870 (setq-local comment-line-break-function 'org-comment-line-break-function))
21872 (defun org-fill-line-break-nobreak-p ()
21873 "Non-nil when a new line at point would create an Org line break."
21874 (save-excursion
21875 (skip-chars-backward "[ \t]")
21876 (skip-chars-backward "\\\\")
21877 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21879 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21880 "Non-nil when a new line at point would split a timestamp."
21881 (and (org-at-timestamp-p 'lax)
21882 (not (looking-at org-ts-regexp-both))))
21884 (defun org-fill-n-macro-as-item-nobreak-p ()
21885 "Non-nil when a new line at point would create a new list."
21886 ;; During export, a "n" macro followed by a dot or a closing
21887 ;; parenthesis can end up being parsed as a new list item.
21888 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21890 (defvar orgtbl-line-start-regexp) ; From org-table.el
21891 (defun org-adaptive-fill-function ()
21892 "Compute a fill prefix for the current line.
21893 Return fill prefix, as a string, or nil if current line isn't
21894 meant to be filled. For convenience, if `adaptive-fill-regexp'
21895 matches in paragraphs or comments, use it."
21896 (org-with-wide-buffer
21897 (unless (org-at-heading-p)
21898 (let* ((p (line-beginning-position))
21899 (element (save-excursion
21900 (beginning-of-line)
21901 (org-element-at-point)))
21902 (type (org-element-type element))
21903 (post-affiliated (org-element-property :post-affiliated element)))
21904 (unless (< p post-affiliated)
21905 (cl-case type
21906 (comment
21907 (save-excursion
21908 (beginning-of-line)
21909 (looking-at "[ \t]*")
21910 (concat (match-string 0) "# ")))
21911 (footnote-definition "")
21912 ((item plain-list)
21913 (make-string (org-list-item-body-column post-affiliated) ?\s))
21914 (paragraph
21915 ;; Fill prefix is usually the same as the current line,
21916 ;; unless the paragraph is at the beginning of an item.
21917 (let ((parent (org-element-property :parent element)))
21918 (save-excursion
21919 (beginning-of-line)
21920 (cond ((eq (org-element-type parent) 'item)
21921 (make-string (org-list-item-body-column
21922 (org-element-property :begin parent))
21923 ?\s))
21924 ((and adaptive-fill-regexp
21925 ;; Locally disable
21926 ;; `adaptive-fill-function' to let
21927 ;; `fill-context-prefix' handle
21928 ;; `adaptive-fill-regexp' variable.
21929 (let (adaptive-fill-function)
21930 (fill-context-prefix
21931 post-affiliated
21932 (org-element-property :end element)))))
21933 ((looking-at "[ \t]+") (match-string 0))
21934 (t "")))))
21935 (comment-block
21936 ;; Only fill contents if P is within block boundaries.
21937 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21938 (forward-line)
21939 (point)))
21940 (cend (save-excursion
21941 (goto-char (org-element-property :end element))
21942 (skip-chars-backward " \r\t\n")
21943 (line-beginning-position))))
21944 (when (and (>= p cbeg) (< p cend))
21945 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21946 (match-string 0)
21947 ""))))))))))
21949 (defun org-fill-element (&optional justify)
21950 "Fill element at point, when applicable.
21952 This function only applies to comment blocks, comments, example
21953 blocks and paragraphs. Also, as a special case, re-align table
21954 when point is at one.
21956 If JUSTIFY is non-nil (interactively, with prefix argument),
21957 justify as well. If `sentence-end-double-space' is non-nil, then
21958 period followed by one space does not end a sentence, so don't
21959 break a line there. The variable `fill-column' controls the
21960 width for filling.
21962 For convenience, when point is at a plain list, an item or
21963 a footnote definition, try to fill the first paragraph within."
21964 (with-syntax-table org-mode-transpose-word-syntax-table
21965 ;; Move to end of line in order to get the first paragraph within
21966 ;; a plain list or a footnote definition.
21967 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21968 ;; First check if point is in a blank line at the beginning of
21969 ;; the buffer. In that case, ignore filling.
21970 (cl-case (org-element-type element)
21971 ;; Use major mode filling function is src blocks.
21972 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21973 ;; Align Org tables, leave table.el tables as-is.
21974 (table-row (org-table-align) t)
21975 (table
21976 (when (eq (org-element-property :type element) 'org)
21977 (save-excursion
21978 (goto-char (org-element-property :post-affiliated element))
21979 (org-table-align)))
21981 (paragraph
21982 ;; Paragraphs may contain `line-break' type objects.
21983 (let ((beg (max (point-min)
21984 (org-element-property :contents-begin element)))
21985 (end (min (point-max)
21986 (org-element-property :contents-end element))))
21987 ;; Do nothing if point is at an affiliated keyword.
21988 (if (< (line-end-position) beg) t
21989 ;; Fill paragraph, taking line breaks into account.
21990 (save-excursion
21991 (goto-char beg)
21992 (let ((cuts (list beg)))
21993 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
21994 (when (eq 'line-break
21995 (org-element-type
21996 (save-excursion (backward-char)
21997 (org-element-context))))
21998 (push (point) cuts)))
21999 (dolist (c (delq end cuts))
22000 (fill-region-as-paragraph c end justify)
22001 (setq end c))))
22002 t)))
22003 ;; Contents of `comment-block' type elements should be
22004 ;; filled as plain text, but only if point is within block
22005 ;; markers.
22006 (comment-block
22007 (let* ((case-fold-search t)
22008 (beg (save-excursion
22009 (goto-char (org-element-property :begin element))
22010 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22011 (forward-line)
22012 (point)))
22013 (end (save-excursion
22014 (goto-char (org-element-property :end element))
22015 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22016 (line-beginning-position))))
22017 (if (or (< (point) beg) (> (point) end)) t
22018 (fill-region-as-paragraph
22019 (save-excursion (end-of-line)
22020 (re-search-backward "^[ \t]*$" beg 'move)
22021 (line-beginning-position))
22022 (save-excursion (beginning-of-line)
22023 (re-search-forward "^[ \t]*$" end 'move)
22024 (line-beginning-position))
22025 justify))))
22026 ;; Fill comments.
22027 (comment
22028 (let ((begin (org-element-property :post-affiliated element))
22029 (end (org-element-property :end element)))
22030 (when (and (>= (point) begin) (<= (point) end))
22031 (let ((begin (save-excursion
22032 (end-of-line)
22033 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22034 (progn (forward-line) (point))
22035 begin)))
22036 (end (save-excursion
22037 (end-of-line)
22038 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22039 (1- (line-beginning-position))
22040 (skip-chars-backward " \r\t\n")
22041 (line-end-position)))))
22042 ;; Do not fill comments when at a blank line.
22043 (when (> end begin)
22044 (let ((fill-prefix
22045 (save-excursion
22046 (beginning-of-line)
22047 (looking-at "[ \t]*#")
22048 (let ((comment-prefix (match-string 0)))
22049 (goto-char (match-end 0))
22050 (if (looking-at adaptive-fill-regexp)
22051 (concat comment-prefix (match-string 0))
22052 (concat comment-prefix " "))))))
22053 (save-excursion
22054 (fill-region-as-paragraph begin end justify))))))
22056 ;; Ignore every other element.
22057 (otherwise t)))))
22059 (defun org-fill-paragraph (&optional justify region)
22060 "Fill element at point, when applicable.
22062 This function only applies to comment blocks, comments, example
22063 blocks and paragraphs. Also, as a special case, re-align table
22064 when point is at one.
22066 For convenience, when point is at a plain list, an item or
22067 a footnote definition, try to fill the first paragraph within.
22069 If JUSTIFY is non-nil (interactively, with prefix argument),
22070 justify as well. If `sentence-end-double-space' is non-nil, then
22071 period followed by one space does not end a sentence, so don't
22072 break a line there. The variable `fill-column' controls the
22073 width for filling.
22075 The REGION argument is non-nil if called interactively; in that
22076 case, if Transient Mark mode is enabled and the mark is active,
22077 fill each of the elements in the active region, instead of just
22078 filling the current element."
22079 (interactive (progn
22080 (barf-if-buffer-read-only)
22081 (list (if current-prefix-arg 'full) t)))
22082 (cond
22083 ((and region transient-mark-mode mark-active
22084 (not (eq (region-beginning) (region-end))))
22085 (let ((origin (point-marker))
22086 (start (region-beginning)))
22087 (unwind-protect
22088 (progn
22089 (goto-char (region-end))
22090 (while (> (point) start)
22091 (org-backward-paragraph)
22092 (org-fill-element justify)))
22093 (goto-char origin)
22094 (set-marker origin nil))))
22095 (t (org-fill-element justify))))
22097 (defun org-auto-fill-function ()
22098 "Auto-fill function."
22099 ;; Check if auto-filling is meaningful.
22100 (let ((fc (current-fill-column)))
22101 (when (and fc (> (current-column) fc))
22102 (let* ((fill-prefix (org-adaptive-fill-function))
22103 ;; Enforce empty fill prefix, if required. Otherwise, it
22104 ;; will be computed again.
22105 (adaptive-fill-mode (not (equal fill-prefix ""))))
22106 (when fill-prefix (do-auto-fill))))))
22108 (defun org-comment-line-break-function (&optional soft)
22109 "Break line at point and indent, continuing comment if within one.
22110 The inserted newline is marked hard if variable
22111 `use-hard-newlines' is true, unless optional argument SOFT is
22112 non-nil."
22113 (if soft (insert-and-inherit ?\n) (newline 1))
22114 (save-excursion (forward-char -1) (delete-horizontal-space))
22115 (delete-horizontal-space)
22116 (indent-to-left-margin)
22117 (insert-before-markers-and-inherit fill-prefix))
22120 ;;; Fixed Width Areas
22122 (defun org-toggle-fixed-width ()
22123 "Toggle fixed-width markup.
22125 Add or remove fixed-width markup on current line, whenever it
22126 makes sense. Return an error otherwise.
22128 If a region is active and if it contains only fixed-width areas
22129 or blank lines, remove all fixed-width markup in it. If the
22130 region contains anything else, convert all non-fixed-width lines
22131 to fixed-width ones.
22133 Blank lines at the end of the region are ignored unless the
22134 region only contains such lines."
22135 (interactive)
22136 (if (not (org-region-active-p))
22137 ;; No region:
22139 ;; Remove fixed width marker only in a fixed-with element.
22141 ;; Add fixed width maker in paragraphs, in blank lines after
22142 ;; elements or at the beginning of a headline or an inlinetask,
22143 ;; and before any one-line elements (e.g., a clock).
22144 (progn
22145 (beginning-of-line)
22146 (let* ((element (org-element-at-point))
22147 (type (org-element-type element)))
22148 (cond
22149 ((and (eq type 'fixed-width)
22150 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22151 (replace-match
22152 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22153 ((and (memq type '(babel-call clock comment diary-sexp headline
22154 horizontal-rule keyword paragraph
22155 planning))
22156 (<= (org-element-property :post-affiliated element) (point)))
22157 (skip-chars-forward " \t")
22158 (insert ": "))
22159 ((and (looking-at-p "[ \t]*$")
22160 (or (eq type 'inlinetask)
22161 (save-excursion
22162 (skip-chars-forward " \r\t\n")
22163 (<= (org-element-property :end element) (point)))))
22164 (delete-region (point) (line-end-position))
22165 (org-indent-line)
22166 (insert ": "))
22167 (t (user-error "Cannot insert a fixed-width line here")))))
22168 ;; Region active.
22169 (let* ((begin (save-excursion
22170 (goto-char (region-beginning))
22171 (line-beginning-position)))
22172 (end (copy-marker
22173 (save-excursion
22174 (goto-char (region-end))
22175 (unless (eolp) (beginning-of-line))
22176 (if (save-excursion (re-search-backward "\\S-" begin t))
22177 (progn (skip-chars-backward " \r\t\n") (point))
22178 (point)))))
22179 (all-fixed-width-p
22180 (catch 'not-all-p
22181 (save-excursion
22182 (goto-char begin)
22183 (skip-chars-forward " \r\t\n")
22184 (when (eobp) (throw 'not-all-p nil))
22185 (while (< (point) end)
22186 (let ((element (org-element-at-point)))
22187 (if (eq (org-element-type element) 'fixed-width)
22188 (goto-char (org-element-property :end element))
22189 (throw 'not-all-p nil))))
22190 t))))
22191 (if all-fixed-width-p
22192 (save-excursion
22193 (goto-char begin)
22194 (while (< (point) end)
22195 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22196 (replace-match
22197 "" nil nil nil
22198 (if (= (line-end-position) (match-end 0)) 0 1)))
22199 (forward-line)))
22200 (let ((min-ind (point-max)))
22201 ;; Find minimum indentation across all lines.
22202 (save-excursion
22203 (goto-char begin)
22204 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22205 (setq min-ind 0)
22206 (catch 'zerop
22207 (while (< (point) end)
22208 (unless (looking-at-p "[ \t]*$")
22209 (let ((ind (org-get-indentation)))
22210 (setq min-ind (min min-ind ind))
22211 (when (zerop ind) (throw 'zerop t))))
22212 (forward-line)))))
22213 ;; Loop over all lines and add fixed-width markup everywhere
22214 ;; but in fixed-width lines.
22215 (save-excursion
22216 (goto-char begin)
22217 (while (< (point) end)
22218 (cond
22219 ((org-at-heading-p)
22220 (insert ": ")
22221 (forward-line)
22222 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22223 (insert ":")
22224 (forward-line)))
22225 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22226 (let* ((element (org-element-at-point))
22227 (element-end (org-element-property :end element)))
22228 (if (eq (org-element-type element) 'fixed-width)
22229 (progn (goto-char element-end)
22230 (skip-chars-backward " \r\t\n")
22231 (forward-line))
22232 (let ((limit (min end element-end)))
22233 (while (< (point) limit)
22234 (org-move-to-column min-ind t)
22235 (insert ": ")
22236 (forward-line))))))
22238 (org-move-to-column min-ind t)
22239 (insert ": ")
22240 (forward-line)))))))
22241 (set-marker end nil))))
22244 ;;; Blocks
22246 (defun org-block-map (function &optional start end)
22247 "Call FUNCTION at the head of all source blocks in the current buffer.
22248 Optional arguments START and END can be used to limit the range."
22249 (let ((start (or start (point-min)))
22250 (end (or end (point-max))))
22251 (save-excursion
22252 (goto-char start)
22253 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22254 (save-excursion
22255 (save-match-data
22256 (goto-char (match-beginning 0))
22257 (funcall function)))))))
22259 (defun org-next-block (arg &optional backward block-regexp)
22260 "Jump to the next block.
22262 With a prefix argument ARG, jump forward ARG many blocks.
22264 When BACKWARD is non-nil, jump to the previous block.
22266 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22267 Match data is set according to this regexp when the function
22268 returns.
22270 Return point at beginning of the opening line of found block.
22271 Throw an error if no block is found."
22272 (interactive "p")
22273 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22274 (case-fold-search t)
22275 (search-fn (if backward #'re-search-backward #'re-search-forward))
22276 (count (or arg 1))
22277 (origin (point))
22278 last-element)
22279 (if backward (beginning-of-line) (end-of-line))
22280 (while (and (> count 0) (funcall search-fn re nil t))
22281 (let ((element (save-excursion
22282 (goto-char (match-beginning 0))
22283 (save-match-data (org-element-at-point)))))
22284 (when (and (memq (org-element-type element)
22285 '(center-block comment-block dynamic-block
22286 example-block export-block quote-block
22287 special-block src-block verse-block))
22288 (<= (match-beginning 0)
22289 (org-element-property :post-affiliated element)))
22290 (setq last-element element)
22291 (cl-decf count))))
22292 (if (= count 0)
22293 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22294 (save-match-data (org-show-context)))
22295 (goto-char origin)
22296 (user-error "No %s code blocks" (if backward "previous" "further")))))
22298 (defun org-previous-block (arg &optional block-regexp)
22299 "Jump to the previous block.
22300 With a prefix argument ARG, jump backward ARG many source blocks.
22301 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22302 (interactive "p")
22303 (org-next-block arg t block-regexp))
22306 ;;; Comments
22308 ;; Org comments syntax is quite complex. It requires the entire line
22309 ;; to be just a comment. Also, even with the right syntax at the
22310 ;; beginning of line, some elements (e.g., verse-block or
22311 ;; example-block) don't accept comments. Usual Emacs comment commands
22312 ;; cannot cope with those requirements. Therefore, Org replaces them.
22314 ;; Org still relies on `comment-dwim', but cannot trust
22315 ;; `comment-only-p'. So, `comment-region-function' and
22316 ;; `uncomment-region-function' both point
22317 ;; to`org-comment-or-uncomment-region'. Eventually,
22318 ;; `org-insert-comment' takes care of insertion of comments at the
22319 ;; beginning of line.
22321 ;; `org-setup-comments-handling' install comments related variables
22322 ;; during `org-mode' initialization.
22324 (defun org-setup-comments-handling ()
22325 (interactive)
22326 (setq-local comment-use-syntax nil)
22327 (setq-local comment-start "# ")
22328 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22329 (setq-local comment-insert-comment-function 'org-insert-comment)
22330 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22331 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22333 (defun org-insert-comment ()
22334 "Insert an empty comment above current line.
22335 If the line is empty, insert comment at its beginning. When
22336 point is within a source block, comment according to the related
22337 major mode."
22338 (if (let ((element (org-element-at-point)))
22339 (and (eq (org-element-type element) 'src-block)
22340 (< (save-excursion
22341 (goto-char (org-element-property :post-affiliated element))
22342 (line-end-position))
22343 (point))
22344 (> (save-excursion
22345 (goto-char (org-element-property :end element))
22346 (skip-chars-backward " \r\t\n")
22347 (line-beginning-position))
22348 (point))))
22349 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22350 (beginning-of-line)
22351 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22352 (open-line 1))
22353 (org-indent-line)
22354 (insert "# ")))
22356 (defvar comment-empty-lines) ; From newcomment.el.
22357 (defun org-comment-or-uncomment-region (beg end &rest _)
22358 "Comment or uncomment each non-blank line in the region.
22359 Uncomment each non-blank line between BEG and END if it only
22360 contains commented lines. Otherwise, comment them. If region is
22361 strictly within a source block, use appropriate comment syntax."
22362 (if (let ((element (org-element-at-point)))
22363 (and (eq (org-element-type element) 'src-block)
22364 (< (save-excursion
22365 (goto-char (org-element-property :post-affiliated element))
22366 (line-end-position))
22367 beg)
22368 (>= (save-excursion
22369 (goto-char (org-element-property :end element))
22370 (skip-chars-backward " \r\t\n")
22371 (line-beginning-position))
22372 end)))
22373 ;; Translate region boundaries for the Org buffer to the source
22374 ;; buffer.
22375 (let ((offset (- end beg)))
22376 (save-excursion
22377 (goto-char beg)
22378 (org-babel-do-in-edit-buffer
22379 (comment-or-uncomment-region (point) (+ offset (point))))))
22380 (save-restriction
22381 ;; Restrict region
22382 (narrow-to-region (save-excursion (goto-char beg)
22383 (skip-chars-forward " \r\t\n" end)
22384 (line-beginning-position))
22385 (save-excursion (goto-char end)
22386 (skip-chars-backward " \r\t\n" beg)
22387 (line-end-position)))
22388 (let ((uncommentp
22389 ;; UNCOMMENTP is non-nil when every non blank line between
22390 ;; BEG and END is a comment.
22391 (save-excursion
22392 (goto-char (point-min))
22393 (while (and (not (eobp))
22394 (let ((element (org-element-at-point)))
22395 (and (eq (org-element-type element) 'comment)
22396 (goto-char (min (point-max)
22397 (org-element-property
22398 :end element)))))))
22399 (eobp))))
22400 (if uncommentp
22401 ;; Only blank lines and comments in region: uncomment it.
22402 (save-excursion
22403 (goto-char (point-min))
22404 (while (not (eobp))
22405 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22406 (replace-match "" nil nil nil 1))
22407 (forward-line)))
22408 ;; Comment each line in region.
22409 (let ((min-indent (point-max)))
22410 ;; First find the minimum indentation across all lines.
22411 (save-excursion
22412 (goto-char (point-min))
22413 (while (and (not (eobp)) (not (zerop min-indent)))
22414 (unless (looking-at "[ \t]*$")
22415 (setq min-indent (min min-indent (current-indentation))))
22416 (forward-line)))
22417 ;; Then loop over all lines.
22418 (save-excursion
22419 (goto-char (point-min))
22420 (while (not (eobp))
22421 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22422 ;; Don't get fooled by invisible text (e.g. link path)
22423 ;; when moving to column MIN-INDENT.
22424 (let ((buffer-invisibility-spec nil))
22425 (org-move-to-column min-indent t))
22426 (insert comment-start))
22427 (forward-line)))))))))
22429 (defun org-comment-dwim (_arg)
22430 "Call the comment command you mean.
22431 Call `org-toggle-comment' if on a heading, otherwise call
22432 `comment-dwim', within a source edit buffer if needed."
22433 (interactive "*P")
22434 (cond ((org-at-heading-p)
22435 (call-interactively #'org-toggle-comment))
22436 ((org-in-src-block-p)
22437 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22438 (t (call-interactively #'comment-dwim))))
22441 ;;; Timestamps API
22443 ;; This section contains tools to operate on, or create, timestamp
22444 ;; objects, as returned by, e.g. `org-element-context'.
22446 (defun org-timestamp-from-string (s)
22447 "Convert Org timestamp S, as a string, into a timestamp object.
22448 Return nil if S is not a valid timestamp string."
22449 (when (org-string-nw-p s)
22450 (with-temp-buffer
22451 (save-excursion (insert s))
22452 (org-element-timestamp-parser))))
22454 (defun org-timestamp-from-time (time &optional with-time inactive)
22455 "Convert a time value into a timestamp object.
22457 TIME is an Emacs internal time representation, as returned, e.g.,
22458 by `current-time'.
22460 When optional argument WITH-TIME is non-nil, return a timestamp
22461 object with a time part, i.e., with hours and minutes.
22463 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22464 return an active timestamp."
22465 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22466 (org-element-create 'timestamp
22467 (list :type (if inactive 'inactive 'active)
22468 :year-start year
22469 :month-start month
22470 :day-start day
22471 :hour-start (and with-time hour)
22472 :minute-start (and with-time minute)))))
22474 (defun org-timestamp-to-time (timestamp &optional end)
22475 "Convert TIMESTAMP object into an Emacs internal time value.
22476 Use end of date range or time range when END is non-nil.
22477 Otherwise, use its start."
22478 (apply #'encode-time
22479 (cons 0
22480 (mapcar
22481 (lambda (prop) (or (org-element-property prop timestamp) 0))
22482 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22483 '(:minute-start :hour-start :day-start :month-start
22484 :year-start))))))
22486 (defun org-timestamp-has-time-p (timestamp)
22487 "Non-nil when TIMESTAMP has a time specified."
22488 (org-element-property :hour-start timestamp))
22490 (defun org-timestamp-format (timestamp format &optional end utc)
22491 "Format a TIMESTAMP object into a string.
22493 FORMAT is a format specifier to be passed to
22494 `format-time-string'.
22496 When optional argument END is non-nil, use end of date-range or
22497 time-range, if possible.
22499 When optional argument UTC is non-nil, time is be expressed as
22500 Universal Time."
22501 (format-time-string format (org-timestamp-to-time timestamp end)
22502 (and utc t)))
22504 (defun org-timestamp-split-range (timestamp &optional end)
22505 "Extract a TIMESTAMP object from a date or time range.
22507 END, when non-nil, means extract the end of the range.
22508 Otherwise, extract its start.
22510 Return a new timestamp object."
22511 (let ((type (org-element-property :type timestamp)))
22512 (if (memq type '(active inactive diary)) timestamp
22513 (let ((split-ts (org-element-copy timestamp)))
22514 ;; Set new type.
22515 (org-element-put-property
22516 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22517 ;; Copy start properties over end properties if END is
22518 ;; non-nil. Otherwise, copy end properties over `start' ones.
22519 (let ((p-alist '((:minute-start . :minute-end)
22520 (:hour-start . :hour-end)
22521 (:day-start . :day-end)
22522 (:month-start . :month-end)
22523 (:year-start . :year-end))))
22524 (dolist (p-cell p-alist)
22525 (org-element-put-property
22526 split-ts
22527 (funcall (if end #'car #'cdr) p-cell)
22528 (org-element-property
22529 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22530 ;; Eventually refresh `:raw-value'.
22531 (org-element-put-property split-ts :raw-value nil)
22532 (org-element-put-property
22533 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22535 (defun org-timestamp-translate (timestamp &optional boundary)
22536 "Translate TIMESTAMP object to custom format.
22538 Format string is defined in `org-time-stamp-custom-formats',
22539 which see.
22541 When optional argument BOUNDARY is non-nil, it is either the
22542 symbol `start' or `end'. In this case, only translate the
22543 starting or ending part of TIMESTAMP if it is a date or time
22544 range. Otherwise, translate both parts.
22546 Return timestamp as-is if `org-display-custom-times' is nil or if
22547 it has a `diary' type."
22548 (let ((type (org-element-property :type timestamp)))
22549 (if (or (not org-display-custom-times) (eq type 'diary))
22550 (org-element-interpret-data timestamp)
22551 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22552 org-time-stamp-custom-formats)))
22553 (if (and (not boundary) (memq type '(active-range inactive-range)))
22554 (concat (org-timestamp-format timestamp fmt)
22555 "--"
22556 (org-timestamp-format timestamp fmt t))
22557 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22559 ;;; Other stuff
22561 (defvar reftex-docstruct-symbol)
22562 (defvar org--rds)
22564 (defun org-reftex-citation ()
22565 "Use reftex-citation to insert a citation into the buffer.
22566 This looks for a line like
22568 #+BIBLIOGRAPHY: foo plain option:-d
22570 and derives from it that foo.bib is the bibliography file relevant
22571 for this document. It then installs the necessary environment for RefTeX
22572 to work in this buffer and calls `reftex-citation' to insert a citation
22573 into the buffer.
22575 Export of such citations to both LaTeX and HTML is handled by the contributed
22576 package ox-bibtex by Taru Karttunen."
22577 (interactive)
22578 (let ((reftex-docstruct-symbol 'org--rds)
22579 org--rds bib)
22580 (org-with-wide-buffer
22581 (let ((case-fold-search t)
22582 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22583 (if (not (save-excursion
22584 (or (re-search-forward re nil t)
22585 (re-search-backward re nil t))))
22586 (user-error "No bibliography defined in file")
22587 (setq bib (concat (match-string 1) ".bib")
22588 org--rds (list (list 'bib bib))))))
22589 (call-interactively 'reftex-citation)))
22591 ;;;; Functions extending outline functionality
22593 (defun org-beginning-of-line (&optional n)
22594 "Go to the beginning of the current visible line.
22596 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22597 symbol `reversed', on the first attempt move to where the
22598 headline text starts, and only move to beginning of line when the
22599 cursor is already before the start of the text of the headline.
22601 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22602 start of the text on the second attempt.
22604 With argument N not nil or 1, move forward N - 1 lines first."
22605 (interactive "^p")
22606 (let ((origin (point))
22607 (special (pcase org-special-ctrl-a/e
22608 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22609 deactivate-mark)
22610 ;; First move to a visible line.
22611 (if (bound-and-true-p visual-line-mode)
22612 (beginning-of-visual-line n)
22613 (move-beginning-of-line n)
22614 ;; `move-beginning-of-line' may leave point after invisible
22615 ;; characters if line starts with such of these (e.g., with
22616 ;; a link at column 0). Really move to the beginning of the
22617 ;; current visible line.
22618 (beginning-of-line))
22619 (cond
22620 ;; No special behavior. Point is already at the beginning of
22621 ;; a line, logical or visual.
22622 ((not special))
22623 ;; `beginning-of-visual-line' left point before logical beginning
22624 ;; of line: point is at the beginning of a visual line. Bail
22625 ;; out.
22626 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22627 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22628 ;; At a headline, special position is before the title, but
22629 ;; after any TODO keyword or priority cookie.
22630 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22631 (line-end-position)))
22632 (bol (point)))
22633 (if (eq special 'reversed)
22634 (when (and (= origin bol) (eq last-command this-command))
22635 (goto-char refpos))
22636 (when (or (> origin refpos) (= origin bol))
22637 (goto-char refpos)))))
22638 ((and (looking-at org-list-full-item-re)
22639 (memq (org-element-type (save-match-data (org-element-at-point)))
22640 '(item plain-list)))
22641 ;; Set special position at first white space character after
22642 ;; bullet, and check-box, if any.
22643 (let ((after-bullet
22644 (let ((box (match-end 3)))
22645 (cond ((not box) (match-end 1))
22646 ((eq (char-after box) ?\s) (1+ box))
22647 (t box)))))
22648 (if (eq special 'reversed)
22649 (when (and (= (point) origin) (eq last-command this-command))
22650 (goto-char after-bullet))
22651 (when (or (> origin after-bullet) (= (point) origin))
22652 (goto-char after-bullet)))))
22653 ;; No special context. Point is already at beginning of line.
22654 (t nil))))
22656 (defun org-end-of-line (&optional n)
22657 "Go to the end of the line, but before ellipsis, if any.
22659 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22660 symbol `reversed', ignore tags on the first attempt, and only
22661 move to after the tags when the cursor is already beyond the end
22662 of the headline.
22664 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22665 on the second attempt.
22667 With argument N not nil or 1, move forward N - 1 lines first."
22668 (interactive "^p")
22669 (let ((origin (point))
22670 (special (pcase org-special-ctrl-a/e
22671 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22672 deactivate-mark)
22673 ;; First move to a visible line.
22674 (if (bound-and-true-p visual-line-mode)
22675 (beginning-of-visual-line n)
22676 (move-beginning-of-line n))
22677 (cond
22678 ;; At a headline, with tags.
22679 ((and special
22680 (save-excursion
22681 (beginning-of-line)
22682 (let ((case-fold-search nil))
22683 (looking-at org-complex-heading-regexp)))
22684 (match-end 5))
22685 (let ((tags (save-excursion
22686 (goto-char (match-beginning 5))
22687 (skip-chars-backward " \t")
22688 (point)))
22689 (visual-end (and (bound-and-true-p visual-line-mode)
22690 (save-excursion
22691 (end-of-visual-line)
22692 (point)))))
22693 ;; If `end-of-visual-line' brings us before end of line or
22694 ;; even tags, i.e., the headline spans over multiple visual
22695 ;; lines, move there.
22696 (cond ((and visual-end
22697 (< visual-end tags)
22698 (<= origin visual-end))
22699 (goto-char visual-end))
22700 ((eq special 'reversed)
22701 (if (and (= origin (line-end-position))
22702 (eq this-command last-command))
22703 (goto-char tags)
22704 (end-of-line)))
22706 (if (or (< origin tags) (= origin (line-end-position)))
22707 (goto-char tags)
22708 (end-of-line))))))
22709 ((bound-and-true-p visual-line-mode)
22710 (let ((bol (line-beginning-position)))
22711 (end-of-visual-line)
22712 ;; If `end-of-visual-line' gets us past the ellipsis at the
22713 ;; end of a line, backtrack and use `end-of-line' instead.
22714 (when (/= bol (line-beginning-position))
22715 (goto-char bol)
22716 (end-of-line))))
22717 (t (end-of-line)))))
22719 (defun org-backward-sentence (&optional _arg)
22720 "Go to beginning of sentence, or beginning of table field.
22721 This will call `backward-sentence' or `org-table-beginning-of-field',
22722 depending on context."
22723 (interactive)
22724 (let* ((element (org-element-at-point))
22725 (contents-begin (org-element-property :contents-begin element))
22726 (table (org-element-lineage element '(table) t)))
22727 (if (and table
22728 (> (point) contents-begin)
22729 (<= (point) (org-element-property :contents-end table)))
22730 (call-interactively #'org-table-beginning-of-field)
22731 (save-restriction
22732 (when (and contents-begin
22733 (< (point-min) contents-begin)
22734 (> (point) contents-begin))
22735 (narrow-to-region contents-begin
22736 (org-element-property :contents-end element)))
22737 (call-interactively #'backward-sentence)))))
22739 (defun org-forward-sentence (&optional _arg)
22740 "Go to end of sentence, or end of table field.
22741 This will call `forward-sentence' or `org-table-end-of-field',
22742 depending on context."
22743 (interactive)
22744 (if (and (org-at-heading-p)
22745 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22746 (save-restriction
22747 (narrow-to-region (line-beginning-position) (line-end-position))
22748 (call-interactively #'forward-sentence))
22749 (let* ((element (org-element-at-point))
22750 (contents-end (org-element-property :contents-end element))
22751 (table (org-element-lineage element '(table) t)))
22752 (if (and table
22753 (>= (point) (org-element-property :contents-begin table))
22754 (< (point) contents-end))
22755 (call-interactively #'org-table-end-of-field)
22756 (save-restriction
22757 (when (and contents-end
22758 (> (point-max) contents-end)
22759 ;; Skip blank lines between elements.
22760 (< (org-element-property :end element)
22761 (save-excursion (goto-char contents-end)
22762 (skip-chars-forward " \r\t\n"))))
22763 (narrow-to-region (org-element-property :contents-begin element)
22764 contents-end))
22765 ;; End of heading is considered as the end of a sentence.
22766 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22767 (call-interactively #'forward-sentence)))))))
22769 (defun org-kill-line (&optional _arg)
22770 "Kill line, to tags or end of line."
22771 (interactive)
22772 (cond
22773 ((or (not org-special-ctrl-k)
22774 (bolp)
22775 (not (org-at-heading-p)))
22776 (when (and (get-char-property (line-end-position) 'invisible)
22777 org-ctrl-k-protect-subtree
22778 (or (eq org-ctrl-k-protect-subtree 'error)
22779 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22780 (user-error
22781 (substitute-command-keys
22782 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22783 (call-interactively
22784 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22785 ((looking-at org-tag-line-re)
22786 (let ((end (save-excursion
22787 (goto-char (match-beginning 1))
22788 (skip-chars-backward " \t"))))
22789 (if (<= end (point)) ;on tags part
22790 (kill-region (point) (line-end-position))
22791 (kill-region (point) end)))
22792 (org-align-tags))
22793 (t (kill-region (point) (line-end-position)))))
22795 (defun org-yank (&optional arg)
22796 "Yank. If the kill is a subtree, treat it specially.
22797 This command will look at the current kill and check if is a single
22798 subtree, or a series of subtrees[1]. If it passes the test, and if the
22799 cursor is at the beginning of a line or after the stars of a currently
22800 empty headline, then the yank is handled specially. How exactly depends
22801 on the value of the following variables.
22803 `org-yank-folded-subtrees'
22804 By default, this variable is non-nil, which results in
22805 subtree(s) being folded after insertion, except if doing so
22806 would swallow text after the yanked text.
22808 `org-yank-adjusted-subtrees'
22809 When non-nil (the default value is nil), the subtree will be
22810 promoted or demoted in order to fit into the local outline tree
22811 structure, which means that the level will be adjusted so that it
22812 becomes the smaller one of the two *visible* surrounding headings.
22814 Any prefix to this command will cause `yank' to be called directly with
22815 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22816 will just
22817 plainly yank the text as it is.
22819 \[1] The test checks if the first non-white line is a heading
22820 and if there are no other headings with fewer stars."
22821 (interactive "P")
22822 (org-yank-generic 'yank arg))
22824 (defun org-yank-generic (command arg)
22825 "Perform some yank-like command.
22827 This function implements the behavior described in the `org-yank'
22828 documentation. However, it has been generalized to work for any
22829 interactive command with similar behavior."
22831 ;; pretend to be command COMMAND
22832 (setq this-command command)
22834 (if arg
22835 (call-interactively command)
22837 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22838 (and (org-kill-is-subtree-p)
22839 (or (bolp)
22840 (and (looking-at "[ \t]*$")
22841 (string-match
22842 "\\`\\*+\\'"
22843 (buffer-substring (point-at-bol) (point)))))))
22844 swallowp)
22845 (cond
22846 ((and subtreep org-yank-folded-subtrees)
22847 (let ((beg (point))
22848 end)
22849 (if (and subtreep org-yank-adjusted-subtrees)
22850 (org-paste-subtree nil nil 'for-yank)
22851 (call-interactively command))
22853 (setq end (point))
22854 (goto-char beg)
22855 (when (and (bolp) subtreep
22856 (not (setq swallowp
22857 (org-yank-folding-would-swallow-text beg end))))
22858 (org-with-limited-levels
22859 (or (looking-at org-outline-regexp)
22860 (re-search-forward org-outline-regexp-bol end t))
22861 (while (and (< (point) end) (looking-at org-outline-regexp))
22862 (outline-hide-subtree)
22863 (org-cycle-show-empty-lines 'folded)
22864 (condition-case nil
22865 (outline-forward-same-level 1)
22866 (error (goto-char end))))))
22867 (when swallowp
22868 (message
22869 "Inserted text not folded because that would swallow text"))
22871 (goto-char end)
22872 (skip-chars-forward " \t\n\r")
22873 (beginning-of-line 1)
22874 (push-mark beg 'nomsg)))
22875 ((and subtreep org-yank-adjusted-subtrees)
22876 (let ((beg (point-at-bol)))
22877 (org-paste-subtree nil nil 'for-yank)
22878 (push-mark beg 'nomsg)))
22880 (call-interactively command))))))
22882 (defun org-yank-folding-would-swallow-text (beg end)
22883 "Would hide-subtree at BEG swallow any text after END?"
22884 (let (level)
22885 (org-with-limited-levels
22886 (save-excursion
22887 (goto-char beg)
22888 (when (or (looking-at org-outline-regexp)
22889 (re-search-forward org-outline-regexp-bol end t))
22890 (setq level (org-outline-level)))
22891 (goto-char end)
22892 (skip-chars-forward " \t\r\n\v\f")
22893 (not (or (eobp)
22894 (and (bolp) (looking-at-p org-outline-regexp)
22895 (<= (org-outline-level) level))))))))
22897 (defun org-back-to-heading (&optional invisible-ok)
22898 "Call `outline-back-to-heading', but provide a better error message."
22899 (condition-case nil
22900 (outline-back-to-heading invisible-ok)
22901 (error (error "Before first headline at position %d in buffer %s"
22902 (point) (current-buffer)))))
22904 (defun org-before-first-heading-p ()
22905 "Before first heading?"
22906 (save-excursion
22907 (end-of-line)
22908 (null (re-search-backward org-outline-regexp-bol nil t))))
22910 (defun org-at-heading-p (&optional ignored)
22911 (outline-on-heading-p t))
22913 (defun org-in-commented-heading-p (&optional no-inheritance)
22914 "Non-nil if point is under a commented heading.
22915 This function also checks ancestors of the current headline,
22916 unless optional argument NO-INHERITANCE is non-nil."
22917 (cond
22918 ((org-before-first-heading-p) nil)
22919 ((let ((headline (nth 4 (org-heading-components))))
22920 (and headline
22921 (let ((case-fold-search nil))
22922 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22923 headline)))))
22924 (no-inheritance nil)
22926 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22928 (defun org-at-comment-p nil
22929 "Is cursor in a commented line?"
22930 (save-excursion
22931 (save-match-data
22932 (beginning-of-line)
22933 (looking-at "^[ \t]*# "))))
22935 (defun org-at-drawer-p nil
22936 "Is cursor at a drawer keyword?"
22937 (save-excursion
22938 (move-beginning-of-line 1)
22939 (looking-at org-drawer-regexp)))
22941 (defun org-at-block-p nil
22942 "Is cursor at a block keyword?"
22943 (save-excursion
22944 (move-beginning-of-line 1)
22945 (looking-at org-block-regexp)))
22947 (defun org-point-at-end-of-empty-headline ()
22948 "If point is at the end of an empty headline, return t, else nil.
22949 If the heading only contains a TODO keyword, it is still still considered
22950 empty."
22951 (let ((case-fold-search nil))
22952 (and (looking-at "[ \t]*$")
22953 org-todo-line-regexp
22954 (save-excursion
22955 (beginning-of-line)
22956 (looking-at org-todo-line-regexp)
22957 (string= (match-string 3) "")))))
22959 (defun org-at-heading-or-item-p ()
22960 (or (org-at-heading-p) (org-at-item-p)))
22962 (defun org-at-target-p ()
22963 (or (org-in-regexp org-radio-target-regexp)
22964 (org-in-regexp org-target-regexp)))
22965 ;; Compatibility alias with Org versions < 7.8.03
22966 (defalias 'org-on-target-p 'org-at-target-p)
22968 (defun org-up-heading-all (arg)
22969 "Move to the heading line of which the present line is a subheading.
22970 This function considers both visible and invisible heading lines.
22971 With argument, move up ARG levels."
22972 (outline-up-heading arg t))
22974 (defun org-up-heading-safe ()
22975 "Move to the heading line of which the present line is a subheading.
22976 This version will not throw an error. It will return the level of the
22977 headline found, or nil if no higher level is found.
22979 Also, this function will be a lot faster than `outline-up-heading',
22980 because it relies on stars being the outline starters. This can really
22981 make a significant difference in outlines with very many siblings."
22982 (when (ignore-errors (org-back-to-heading t))
22983 (let ((level-up (1- (funcall outline-level))))
22984 (and (> level-up 0)
22985 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
22986 (funcall outline-level)))))
22988 (defun org-first-sibling-p ()
22989 "Is this heading the first child of its parents?"
22990 (interactive)
22991 (let ((re org-outline-regexp-bol)
22992 level l)
22993 (unless (org-at-heading-p t)
22994 (user-error "Not at a heading"))
22995 (setq level (funcall outline-level))
22996 (save-excursion
22997 (if (not (re-search-backward re nil t))
22999 (setq l (funcall outline-level))
23000 (< l level)))))
23002 (defun org-goto-sibling (&optional previous)
23003 "Goto the next sibling, even if it is invisible.
23004 When PREVIOUS is set, go to the previous sibling instead. Returns t
23005 when a sibling was found. When none is found, return nil and don't
23006 move point."
23007 (let ((fun (if previous 're-search-backward 're-search-forward))
23008 (pos (point))
23009 (re org-outline-regexp-bol)
23010 level l)
23011 (when (ignore-errors (org-back-to-heading t))
23012 (setq level (funcall outline-level))
23013 (catch 'exit
23014 (or previous (forward-char 1))
23015 (while (funcall fun re nil t)
23016 (setq l (funcall outline-level))
23017 (when (< l level) (goto-char pos) (throw 'exit nil))
23018 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23019 (goto-char pos)
23020 nil))))
23022 (defun org-show-siblings ()
23023 "Show all siblings of the current headline."
23024 (save-excursion
23025 (while (org-goto-sibling) (org-flag-heading nil)))
23026 (save-excursion
23027 (while (org-goto-sibling 'previous)
23028 (org-flag-heading nil))))
23030 (defun org-goto-first-child ()
23031 "Goto the first child, even if it is invisible.
23032 Return t when a child was found. Otherwise don't move point and
23033 return nil."
23034 (let (level (pos (point)) (re org-outline-regexp-bol))
23035 (when (ignore-errors (org-back-to-heading t))
23036 (setq level (outline-level))
23037 (forward-char 1)
23038 (if (and (re-search-forward re nil t) (> (outline-level) level))
23039 (progn (goto-char (match-beginning 0)) t)
23040 (goto-char pos) nil))))
23042 (defun org-show-hidden-entry ()
23043 "Show an entry where even the heading is hidden."
23044 (save-excursion
23045 (org-show-entry)))
23047 (defun org-flag-heading (flag &optional entry)
23048 "Flag the current heading. FLAG non-nil means make invisible.
23049 When ENTRY is non-nil, show the entire entry."
23050 (save-excursion
23051 (org-back-to-heading t)
23052 ;; Check if we should show the entire entry
23053 (if (not entry)
23054 (org-flag-region
23055 (line-end-position 0) (line-end-position) flag 'outline)
23056 (org-show-entry)
23057 (save-excursion
23058 (and (outline-next-heading)
23059 (org-flag-heading nil))))))
23061 (defun org-get-next-sibling ()
23062 "Move to next heading of the same level, and return point.
23063 If there is no such heading, return nil.
23064 This is like outline-next-sibling, but invisible headings are ok."
23065 (let ((level (funcall outline-level)))
23066 (outline-next-heading)
23067 (while (and (not (eobp)) (> (funcall outline-level) level))
23068 (outline-next-heading))
23069 (unless (or (eobp) (< (funcall outline-level) level))
23070 (point))))
23072 (defun org-get-last-sibling ()
23073 "Move to previous heading of the same level, and return point.
23074 If there is no such heading, return nil."
23075 (let ((opoint (point))
23076 (level (funcall outline-level)))
23077 (outline-previous-heading)
23078 (when (and (/= (point) opoint) (outline-on-heading-p t))
23079 (while (and (> (funcall outline-level) level)
23080 (not (bobp)))
23081 (outline-previous-heading))
23082 (unless (< (funcall outline-level) level)
23083 (point)))))
23085 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23086 "Goto to the end of a subtree."
23087 ;; This contains an exact copy of the original function, but it uses
23088 ;; `org-back-to-heading', to make it work also in invisible
23089 ;; trees. And is uses an invisible-ok argument.
23090 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23091 ;; Furthermore, when used inside Org, finding the end of a large subtree
23092 ;; with many children and grandchildren etc, this can be much faster
23093 ;; than the outline version.
23094 (org-back-to-heading invisible-ok)
23095 (let ((first t)
23096 (level (funcall outline-level)))
23097 (if (and (derived-mode-p 'org-mode) (< level 1000))
23098 ;; A true heading (not a plain list item), in Org
23099 ;; This means we can easily find the end by looking
23100 ;; only for the right number of stars. Using a regexp to do
23101 ;; this is so much faster than using a Lisp loop.
23102 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23103 (forward-char 1)
23104 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23105 ;; something else, do it the slow way
23106 (while (and (not (eobp))
23107 (or first (> (funcall outline-level) level)))
23108 (setq first nil)
23109 (outline-next-heading)))
23110 (unless to-heading
23111 (when (memq (preceding-char) '(?\n ?\^M))
23112 ;; Go to end of line before heading
23113 (forward-char -1)
23114 (when (memq (preceding-char) '(?\n ?\^M))
23115 ;; leave blank line before heading
23116 (forward-char -1)))))
23117 (point))
23119 (defun org-end-of-meta-data (&optional full)
23120 "Skip planning line and properties drawer in current entry.
23121 When optional argument FULL is non-nil, also skip empty lines,
23122 clocking lines and regular drawers at the beginning of the
23123 entry."
23124 (org-back-to-heading t)
23125 (forward-line)
23126 (when (looking-at-p org-planning-line-re) (forward-line))
23127 (when (looking-at org-property-drawer-re)
23128 (goto-char (match-end 0))
23129 (forward-line))
23130 (when (and full (not (org-at-heading-p)))
23131 (catch 'exit
23132 (let ((end (save-excursion (outline-next-heading) (point)))
23133 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23134 (while (not (eobp))
23135 (cond ((looking-at-p org-drawer-regexp)
23136 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23137 (forward-line)
23138 (throw 'exit t)))
23139 ((looking-at-p re) (forward-line))
23140 (t (throw 'exit t))))))))
23142 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23143 "Move forward to the ARG'th subheading at same level as this one.
23144 Stop at the first and last subheadings of a superior heading.
23145 Normally this only looks at visible headings, but when INVISIBLE-OK is
23146 non-nil it will also look at invisible ones."
23147 (interactive "p")
23148 (let ((backward? (and arg (< arg 0))))
23149 (if (org-before-first-heading-p)
23150 (if backward? (goto-char (point-min)) (outline-next-heading))
23151 (org-back-to-heading invisible-ok)
23152 (unless backward? (end-of-line)) ;do not match current headline
23153 (let ((level (- (match-end 0) (match-beginning 0) 1))
23154 (f (if backward? #'re-search-backward #'re-search-forward))
23155 (count (if arg (abs arg) 1))
23156 (result (point)))
23157 (while (and (> count 0)
23158 (funcall f org-outline-regexp-bol nil 'move))
23159 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23160 (cond ((< l level) (setq count 0))
23161 ((and (= l level)
23162 (or invisible-ok
23163 (not (org-invisible-p
23164 (line-beginning-position)))))
23165 (cl-decf count)
23166 (when (= l level) (setq result (point)))))))
23167 (goto-char result))
23168 (beginning-of-line))))
23170 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23171 "Move backward to the ARG'th subheading at same level as this one.
23172 Stop at the first and last subheadings of a superior heading."
23173 (interactive "p")
23174 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23176 (defun org-next-visible-heading (arg)
23177 "Move to the next visible heading.
23179 This function wraps `outline-next-visible-heading' with
23180 `org-with-limited-levels' in order to skip over inline tasks and
23181 respect customization of `org-odd-levels-only'."
23182 (interactive "p")
23183 (org-with-limited-levels
23184 (outline-next-visible-heading arg)))
23186 (defun org-previous-visible-heading (arg)
23187 "Move to the previous visible heading.
23189 This function wraps `outline-previous-visible-heading' with
23190 `org-with-limited-levels' in order to skip over inline tasks and
23191 respect customization of `org-odd-levels-only'."
23192 (interactive "p")
23193 (org-with-limited-levels
23194 (outline-previous-visible-heading arg)))
23196 (defun org-forward-paragraph ()
23197 "Move forward to beginning of next paragraph or equivalent.
23199 The function moves point to the beginning of the next visible
23200 structural element, which can be a paragraph, a table, a list
23201 item, etc. It also provides some special moves for convenience:
23203 - On an affiliated keyword, jump to the beginning of the
23204 relative element.
23205 - On an item or a footnote definition, move to the second
23206 element inside, if any.
23207 - On a table or a property drawer, jump after it.
23208 - On a verse or source block, stop after blank lines."
23209 (interactive)
23210 (unless (eobp)
23211 (let* ((deactivate-mark nil)
23212 (element (org-element-at-point))
23213 (type (org-element-type element))
23214 (post-affiliated (org-element-property :post-affiliated element))
23215 (contents-begin (org-element-property :contents-begin element))
23216 (contents-end (org-element-property :contents-end element))
23217 (end (let ((end (org-element-property :end element)) (parent element))
23218 (while (and (setq parent (org-element-property :parent parent))
23219 (= (org-element-property :contents-end parent) end))
23220 (setq end (org-element-property :end parent)))
23221 end)))
23222 (cond ((not element)
23223 (skip-chars-forward " \r\t\n")
23224 (or (eobp) (beginning-of-line)))
23225 ;; On affiliated keywords, move to element's beginning.
23226 ((< (point) post-affiliated)
23227 (goto-char post-affiliated))
23228 ;; At a table row, move to the end of the table. Similarly,
23229 ;; at a node property, move to the end of the property
23230 ;; drawer.
23231 ((memq type '(node-property table-row))
23232 (goto-char (org-element-property
23233 :end (org-element-property :parent element))))
23234 ((memq type '(property-drawer table)) (goto-char end))
23235 ;; Consider blank lines as separators in verse and source
23236 ;; blocks to ease editing.
23237 ((memq type '(src-block verse-block))
23238 (when (eq type 'src-block)
23239 (setq contents-end
23240 (save-excursion (goto-char end)
23241 (skip-chars-backward " \r\t\n")
23242 (line-beginning-position))))
23243 (beginning-of-line)
23244 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23245 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23246 (goto-char end)
23247 (skip-chars-forward " \r\t\n")
23248 (if (= (point) contents-end) (goto-char end)
23249 (beginning-of-line))))
23250 ;; With no contents, just skip element.
23251 ((not contents-begin) (goto-char end))
23252 ;; If contents are invisible, skip the element altogether.
23253 ((org-invisible-p (line-end-position))
23254 (cl-case type
23255 (headline
23256 (org-with-limited-levels (outline-next-visible-heading 1)))
23257 ;; At a plain list, make sure we move to the next item
23258 ;; instead of skipping the whole list.
23259 (plain-list (forward-char)
23260 (org-forward-paragraph))
23261 (otherwise (goto-char end))))
23262 ((>= (point) contents-end) (goto-char end))
23263 ((>= (point) contents-begin)
23264 ;; This can only happen on paragraphs and plain lists.
23265 (cl-case type
23266 (paragraph (goto-char end))
23267 ;; At a plain list, try to move to second element in
23268 ;; first item, if possible.
23269 (plain-list (end-of-line)
23270 (org-forward-paragraph))))
23271 ;; When contents start on the middle of a line (e.g. in
23272 ;; items and footnote definitions), try to reach first
23273 ;; element starting after current line.
23274 ((> (line-end-position) contents-begin)
23275 (end-of-line)
23276 (org-forward-paragraph))
23277 (t (goto-char contents-begin))))))
23279 (defun org-backward-paragraph ()
23280 "Move backward to start of previous paragraph or equivalent.
23282 The function moves point to the beginning of the current
23283 structural element, which can be a paragraph, a table, a list
23284 item, etc., or to the beginning of the previous visible one if
23285 point is already there. It also provides some special moves for
23286 convenience:
23288 - On an affiliated keyword, jump to the first one.
23289 - On a table or a property drawer, move to its beginning.
23290 - On comment, example, export, src and verse blocks, stop
23291 before blank lines."
23292 (interactive)
23293 (unless (bobp)
23294 (let* ((deactivate-mark nil)
23295 (element (org-element-at-point))
23296 (type (org-element-type element))
23297 (contents-end (org-element-property :contents-end element))
23298 (post-affiliated (org-element-property :post-affiliated element))
23299 (begin (org-element-property :begin element))
23300 (special? ;blocks handled specially
23301 (memq type '(comment-block example-block export-block src-block
23302 verse-block)))
23303 (contents-begin
23304 (if special?
23305 ;; These types have no proper contents. Fake line
23306 ;; below the block opening line as contents beginning.
23307 (save-excursion (goto-char begin) (line-beginning-position 2))
23308 (org-element-property :contents-begin element))))
23309 (cond
23310 ((not element) (goto-char (point-min)))
23311 ((= (point) begin)
23312 (backward-char)
23313 (org-backward-paragraph))
23314 ((<= (point) post-affiliated) (goto-char begin))
23315 ;; Special behavior: on a table or a property drawer, move to
23316 ;; its beginning.
23317 ((memq type '(node-property table-row))
23318 (goto-char (org-element-property
23319 :post-affiliated (org-element-property :parent element))))
23320 (special?
23321 (if (<= (point) contents-begin) (goto-char post-affiliated)
23322 ;; Inside a verse block, see blank lines as paragraph
23323 ;; separators.
23324 (let ((origin (point)))
23325 (skip-chars-backward " \r\t\n" contents-begin)
23326 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23327 (skip-chars-forward " \r\t\n" origin)
23328 (if (= (point) origin) (goto-char contents-begin)
23329 (beginning-of-line))))))
23330 ((eq type 'paragraph) (goto-char contents-begin)
23331 ;; When at first paragraph in an item or a footnote definition,
23332 ;; move directly to beginning of line.
23333 (let ((parent-contents
23334 (org-element-property
23335 :contents-begin (org-element-property :parent element))))
23336 (when (and parent-contents (= parent-contents contents-begin))
23337 (beginning-of-line))))
23338 ;; At the end of a greater element, move to the beginning of
23339 ;; the last element within.
23340 ((and contents-end (>= (point) contents-end))
23341 (goto-char (1- contents-end))
23342 (org-backward-paragraph))
23343 (t (goto-char (or post-affiliated begin))))
23344 ;; Ensure we never leave point invisible.
23345 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23347 (defun org-forward-element ()
23348 "Move forward by one element.
23349 Move to the next element at the same level, when possible."
23350 (interactive)
23351 (cond ((eobp) (user-error "Cannot move further down"))
23352 ((org-with-limited-levels (org-at-heading-p))
23353 (let ((origin (point)))
23354 (goto-char (org-end-of-subtree nil t))
23355 (unless (org-with-limited-levels (org-at-heading-p))
23356 (goto-char origin)
23357 (user-error "Cannot move further down"))))
23359 (let* ((elem (org-element-at-point))
23360 (end (org-element-property :end elem))
23361 (parent (org-element-property :parent elem)))
23362 (cond ((and parent (= (org-element-property :contents-end parent) end))
23363 (goto-char (org-element-property :end parent)))
23364 ((integer-or-marker-p end) (goto-char end))
23365 (t (message "No element at point")))))))
23367 (defun org-backward-element ()
23368 "Move backward by one element.
23369 Move to the previous element at the same level, when possible."
23370 (interactive)
23371 (cond ((bobp) (user-error "Cannot move further up"))
23372 ((org-with-limited-levels (org-at-heading-p))
23373 ;; At a headline, move to the previous one, if any, or stay
23374 ;; here.
23375 (let ((origin (point)))
23376 (org-with-limited-levels (org-backward-heading-same-level 1))
23377 ;; When current headline has no sibling above, move to its
23378 ;; parent.
23379 (when (= (point) origin)
23380 (or (org-with-limited-levels (org-up-heading-safe))
23381 (progn (goto-char origin)
23382 (user-error "Cannot move further up"))))))
23384 (let* ((elem (org-element-at-point))
23385 (beg (org-element-property :begin elem)))
23386 (cond
23387 ;; Move to beginning of current element if point isn't
23388 ;; there already.
23389 ((null beg) (message "No element at point"))
23390 ((/= (point) beg) (goto-char beg))
23391 (t (goto-char beg)
23392 (skip-chars-backward " \r\t\n")
23393 (unless (bobp)
23394 (let ((prev (org-element-at-point)))
23395 (goto-char (org-element-property :begin prev))
23396 (while (and (setq prev (org-element-property :parent prev))
23397 (<= (org-element-property :end prev) beg))
23398 (goto-char (org-element-property :begin prev)))))))))))
23400 (defun org-up-element ()
23401 "Move to upper element."
23402 (interactive)
23403 (if (org-with-limited-levels (org-at-heading-p))
23404 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23405 (let* ((elem (org-element-at-point))
23406 (parent (org-element-property :parent elem)))
23407 (if parent (goto-char (org-element-property :begin parent))
23408 (if (org-with-limited-levels (org-before-first-heading-p))
23409 (user-error "No surrounding element")
23410 (org-with-limited-levels (org-back-to-heading)))))))
23412 (defun org-down-element ()
23413 "Move to inner element."
23414 (interactive)
23415 (let ((element (org-element-at-point)))
23416 (cond
23417 ((memq (org-element-type element) '(plain-list table))
23418 (goto-char (org-element-property :contents-begin element))
23419 (forward-char))
23420 ((memq (org-element-type element) org-element-greater-elements)
23421 ;; If contents are hidden, first disclose them.
23422 (when (org-invisible-p (line-end-position)) (org-cycle))
23423 (goto-char (or (org-element-property :contents-begin element)
23424 (user-error "No content for this element"))))
23425 (t (user-error "No inner element")))))
23427 (defun org-drag-element-backward ()
23428 "Move backward element at point."
23429 (interactive)
23430 (let ((elem (or (org-element-at-point)
23431 (user-error "No element at point"))))
23432 (if (eq (org-element-type elem) 'headline)
23433 ;; Preserve point when moving a whole tree, even if point was
23434 ;; on blank lines below the headline.
23435 (let ((offset (skip-chars-backward " \t\n")))
23436 (unwind-protect (org-move-subtree-up)
23437 (forward-char (- offset))))
23438 (let ((prev-elem
23439 (save-excursion
23440 (goto-char (org-element-property :begin elem))
23441 (skip-chars-backward " \r\t\n")
23442 (unless (bobp)
23443 (let* ((beg (org-element-property :begin elem))
23444 (prev (org-element-at-point))
23445 (up prev))
23446 (while (and (setq up (org-element-property :parent up))
23447 (<= (org-element-property :end up) beg))
23448 (setq prev up))
23449 prev)))))
23450 ;; Error out if no previous element or previous element is
23451 ;; a parent of the current one.
23452 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23453 (user-error "Cannot drag element backward")
23454 (let ((pos (point)))
23455 (org-element-swap-A-B prev-elem elem)
23456 (goto-char (+ (org-element-property :begin prev-elem)
23457 (- pos (org-element-property :begin elem))))))))))
23459 (defun org-drag-element-forward ()
23460 "Move forward element at point."
23461 (interactive)
23462 (let* ((pos (point))
23463 (elem (or (org-element-at-point)
23464 (user-error "No element at point"))))
23465 (when (= (point-max) (org-element-property :end elem))
23466 (user-error "Cannot drag element forward"))
23467 (goto-char (org-element-property :end elem))
23468 (let ((next-elem (org-element-at-point)))
23469 (when (or (org-element-nested-p elem next-elem)
23470 (and (eq (org-element-type next-elem) 'headline)
23471 (not (eq (org-element-type elem) 'headline))))
23472 (goto-char pos)
23473 (user-error "Cannot drag element forward"))
23474 ;; Compute new position of point: it's shifted by NEXT-ELEM
23475 ;; body's length (without final blanks) and by the length of
23476 ;; blanks between ELEM and NEXT-ELEM.
23477 (let ((size-next (- (save-excursion
23478 (goto-char (org-element-property :end next-elem))
23479 (skip-chars-backward " \r\t\n")
23480 (forward-line)
23481 ;; Small correction if buffer doesn't end
23482 ;; with a newline character.
23483 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23484 (org-element-property :begin next-elem)))
23485 (size-blank (- (org-element-property :end elem)
23486 (save-excursion
23487 (goto-char (org-element-property :end elem))
23488 (skip-chars-backward " \r\t\n")
23489 (forward-line)
23490 (point)))))
23491 (org-element-swap-A-B elem next-elem)
23492 (goto-char (+ pos size-next size-blank))))))
23494 (defun org-drag-line-forward (arg)
23495 "Drag the line at point ARG lines forward."
23496 (interactive "p")
23497 (dotimes (_ (abs arg))
23498 (let ((c (current-column)))
23499 (if (< 0 arg)
23500 (progn
23501 (beginning-of-line 2)
23502 (transpose-lines 1)
23503 (beginning-of-line 0))
23504 (transpose-lines 1)
23505 (beginning-of-line -1))
23506 (org-move-to-column c))))
23508 (defun org-drag-line-backward (arg)
23509 "Drag the line at point ARG lines backward."
23510 (interactive "p")
23511 (org-drag-line-forward (- arg)))
23513 (defun org-mark-element ()
23514 "Put point at beginning of this element, mark at end.
23516 Interactively, if this command is repeated or (in Transient Mark
23517 mode) if the mark is active, it marks the next element after the
23518 ones already marked."
23519 (interactive)
23520 (let (deactivate-mark)
23521 (if (and (called-interactively-p 'any)
23522 (or (and (eq last-command this-command) (mark t))
23523 (and transient-mark-mode mark-active)))
23524 (set-mark
23525 (save-excursion
23526 (goto-char (mark))
23527 (goto-char (org-element-property :end (org-element-at-point)))))
23528 (let ((element (org-element-at-point)))
23529 (end-of-line)
23530 (push-mark (org-element-property :end element) t t)
23531 (goto-char (org-element-property :begin element))))))
23533 (defun org-narrow-to-element ()
23534 "Narrow buffer to current element."
23535 (interactive)
23536 (let ((elem (org-element-at-point)))
23537 (cond
23538 ((eq (car elem) 'headline)
23539 (narrow-to-region
23540 (org-element-property :begin elem)
23541 (org-element-property :end elem)))
23542 ((memq (car elem) org-element-greater-elements)
23543 (narrow-to-region
23544 (org-element-property :contents-begin elem)
23545 (org-element-property :contents-end elem)))
23547 (narrow-to-region
23548 (org-element-property :begin elem)
23549 (org-element-property :end elem))))))
23551 (defun org-transpose-element ()
23552 "Transpose current and previous elements, keeping blank lines between.
23553 Point is moved after both elements."
23554 (interactive)
23555 (org-skip-whitespace)
23556 (let ((end (org-element-property :end (org-element-at-point))))
23557 (org-drag-element-backward)
23558 (goto-char end)))
23560 (defun org-unindent-buffer ()
23561 "Un-indent the visible part of the buffer.
23562 Relative indentation (between items, inside blocks, etc.) isn't
23563 modified."
23564 (interactive)
23565 (unless (eq major-mode 'org-mode)
23566 (user-error "Cannot un-indent a buffer not in Org mode"))
23567 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23568 (unindent-tree
23569 (lambda (contents)
23570 (dolist (element (reverse contents))
23571 (if (memq (org-element-type element) '(headline section))
23572 (funcall unindent-tree (org-element-contents element))
23573 (save-excursion
23574 (save-restriction
23575 (narrow-to-region
23576 (org-element-property :begin element)
23577 (org-element-property :end element))
23578 (org-do-remove-indentation))))))))
23579 (funcall unindent-tree (org-element-contents parse-tree))))
23581 (defun org-make-options-regexp (kwds &optional extra)
23582 "Make a regular expression for keyword lines.
23583 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23584 when non-nil, is a regexp matching keywords names."
23585 (concat "^[ \t]*#\\+\\("
23586 (regexp-opt kwds)
23587 (and extra (concat (and kwds "\\|") extra))
23588 "\\):[ \t]*\\(.*\\)"))
23591 ;;; Finish up
23593 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23594 (lambda () (add-hook 'change-major-mode-hook
23595 'org-show-all 'append 'local)))
23597 (provide 'org)
23599 (run-hooks 'org-load-hook)
23601 ;;; org.el ends here