Improve docstring
[org-mode/org-tableheadings.git] / lisp / org.el
bloba56c595850428c958136f1f3c6dfd5fac072d8ad
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.11
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)
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 "24.4"
703 :package-version '(Org . "8.0")
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 ?@ "w")
5436 (modify-syntax-entry ?\" "\"")
5437 (modify-syntax-entry ?\\ "_")
5438 (modify-syntax-entry ?~ "_")
5439 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5440 ;; Activate before-change-function
5441 (setq-local org-table-may-need-update t)
5442 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5443 ;; Check for running clock before killing a buffer
5444 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5445 ;; Initialize macros templates.
5446 (org-macro-initialize-templates)
5447 ;; Initialize radio targets.
5448 (org-update-radio-target-regexp)
5449 ;; Indentation.
5450 (setq-local indent-line-function 'org-indent-line)
5451 (setq-local indent-region-function 'org-indent-region)
5452 ;; Filling and auto-filling.
5453 (org-setup-filling)
5454 ;; Comments.
5455 (org-setup-comments-handling)
5456 ;; Initialize cache.
5457 (org-element-cache-reset)
5458 ;; Beginning/end of defun
5459 (setq-local beginning-of-defun-function 'org-backward-element)
5460 (setq-local end-of-defun-function
5461 (lambda ()
5462 (if (not (org-at-heading-p))
5463 (org-forward-element)
5464 (org-forward-element)
5465 (forward-char -1))))
5466 ;; Next error for sparse trees
5467 (setq-local next-error-function 'org-occur-next-match)
5468 ;; Make sure dependence stuff works reliably, even for users who set it
5469 ;; too late :-(
5470 (if org-enforce-todo-dependencies
5471 (add-hook 'org-blocker-hook
5472 'org-block-todo-from-children-or-siblings-or-parent)
5473 (remove-hook 'org-blocker-hook
5474 'org-block-todo-from-children-or-siblings-or-parent))
5475 (if org-enforce-todo-checkbox-dependencies
5476 (add-hook 'org-blocker-hook
5477 'org-block-todo-from-checkboxes)
5478 (remove-hook 'org-blocker-hook
5479 'org-block-todo-from-checkboxes))
5481 ;; Align options lines
5482 (setq-local
5483 align-mode-rules-list
5484 '((org-in-buffer-settings
5485 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5486 (modes . '(org-mode)))))
5488 ;; Imenu
5489 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5491 ;; Make isearch reveal context
5492 (setq-local outline-isearch-open-invisible-function
5493 (lambda (&rest _) (org-show-context 'isearch)))
5495 ;; Setup the pcomplete hooks
5496 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5497 (setq-local pcomplete-command-name-function 'org-command-at-point)
5498 (setq-local pcomplete-default-completion-function 'ignore)
5499 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5500 (setq-local pcomplete-termination-string "")
5501 (setq-local buffer-face-mode-face 'org-default)
5503 ;; If empty file that did not turn on Org mode automatically, make
5504 ;; it to.
5505 (when (and org-insert-mode-line-in-empty-file
5506 (called-interactively-p 'any)
5507 (= (point-min) (point-max)))
5508 (insert "# -*- mode: org -*-\n\n"))
5509 (unless org-inhibit-startup
5510 (org-unmodified
5511 (when org-startup-with-beamer-mode (org-beamer-mode))
5512 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5513 (org-table-map-tables
5514 (cond ((and org-startup-align-all-tables
5515 org-startup-shrink-all-tables)
5516 (lambda () (org-table-align) (org-table-shrink)))
5517 (org-startup-align-all-tables #'org-table-align)
5518 (t #'org-table-shrink))
5520 (when org-startup-with-inline-images (org-display-inline-images))
5521 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5522 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5523 (when org-startup-truncated (setq truncate-lines t))
5524 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5525 (org-refresh-effort-properties)))
5526 ;; Try to set `org-hide' face correctly.
5527 (let ((foreground (org-find-invisible-foreground)))
5528 (when foreground
5529 (set-face-foreground 'org-hide foreground))))
5531 ;; Update `customize-package-emacs-version-alist'
5532 (add-to-list 'customize-package-emacs-version-alist
5533 '(Org ("8.0" . "24.4")
5534 ("8.1" . "24.4")
5535 ("8.2" . "24.4")
5536 ("8.2.7" . "24.4")
5537 ("8.3" . "26.1")
5538 ("9.0" . "26.1")
5539 ("9.1" . "26.1")
5540 ("9.2" . "27.1")))
5542 (defvar org-mode-transpose-word-syntax-table
5543 (let ((st (make-syntax-table text-mode-syntax-table)))
5544 (dolist (c org-emphasis-alist st)
5545 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5547 (when (fboundp 'abbrev-table-put)
5548 (abbrev-table-put org-mode-abbrev-table
5549 :parents (list text-mode-abbrev-table)))
5551 (defun org-find-invisible-foreground ()
5552 (let ((candidates (remove
5553 "unspecified-bg"
5554 (nconc
5555 (list (face-background 'default)
5556 (face-background 'org-default))
5557 (mapcar
5558 (lambda (alist)
5559 (when (boundp alist)
5560 (cdr (assq 'background-color (symbol-value alist)))))
5561 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5562 (list (face-foreground 'org-hide))))))
5563 (car (remove nil candidates))))
5565 (defun org-current-time (&optional rounding-minutes past)
5566 "Current time, possibly rounded to ROUNDING-MINUTES.
5567 When ROUNDING-MINUTES is not an integer, fall back on the car of
5568 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5569 the rounding returns a past time."
5570 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5571 (car org-time-stamp-rounding-minutes)))
5572 (time (decode-time)) res)
5573 (if (< r 1)
5574 (current-time)
5575 (setq res
5576 (apply 'encode-time
5577 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5578 (nthcdr 2 time))))
5579 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5580 (seconds-to-time (- (float-time res) (* r 60)))
5581 res))))
5583 (defun org-today ()
5584 "Return today date, considering `org-extend-today-until'."
5585 (time-to-days
5586 (time-subtract (current-time)
5587 (list 0 (* 3600 org-extend-today-until) 0))))
5589 ;;;; Font-Lock stuff, including the activators
5591 (defvar org-mouse-map (make-sparse-keymap))
5592 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5593 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5594 (when org-mouse-1-follows-link
5595 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5596 (when org-tab-follows-link
5597 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5598 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5600 (require 'font-lock)
5602 (defconst org-non-link-chars "]\t\n\r<>")
5603 (defvar org-link-types-re nil
5604 "Matches a link that has a url-like prefix like \"http:\"")
5605 (defvar org-link-re-with-space nil
5606 "Matches a link with spaces, optional angular brackets around it.")
5607 (defvar org-link-re-with-space2 nil
5608 "Matches a link with spaces, optional angular brackets around it.")
5609 (defvar org-link-re-with-space3 nil
5610 "Matches a link with spaces, only for internal part in bracket links.")
5611 (defvar org-angle-link-re nil
5612 "Matches link with angular brackets, spaces are allowed.")
5613 (defvar org-plain-link-re nil
5614 "Matches plain link, without spaces.")
5615 (defvar org-bracket-link-regexp nil
5616 "Matches a link in double brackets.")
5617 (defvar org-bracket-link-analytic-regexp nil
5618 "Regular expression used to analyze links.
5619 Here is what the match groups contain after a match:
5620 1: http:
5621 2: http
5622 3: path
5623 4: [desc]
5624 5: desc")
5625 (defvar org-bracket-link-analytic-regexp++ nil
5626 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5627 (defvar org-any-link-re nil
5628 "Regular expression matching any link.")
5630 (defconst org-match-sexp-depth 3
5631 "Number of stacked braces for sub/superscript matching.")
5633 (defun org-create-multibrace-regexp (left right n)
5634 "Create a regular expression which will match a balanced sexp.
5635 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5636 as single character strings.
5637 The regexp returned will match the entire expression including the
5638 delimiters. It will also define a single group which contains the
5639 match except for the outermost delimiters. The maximum depth of
5640 stacked delimiters is N. Escaping delimiters is not possible."
5641 (let* ((nothing (concat "[^" left right "]*?"))
5642 (or "\\|")
5643 (re nothing)
5644 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5645 (while (> n 1)
5646 (setq n (1- n)
5647 re (concat re or next)
5648 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5649 (concat left "\\(" re "\\)" right)))
5651 (defconst org-match-substring-regexp
5652 (concat
5653 "\\(\\S-\\)\\([_^]\\)\\("
5654 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5655 "\\|"
5656 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5657 "\\|"
5658 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5659 "The regular expression matching a sub- or superscript.")
5661 (defconst org-match-substring-with-braces-regexp
5662 (concat
5663 "\\(\\S-\\)\\([_^]\\)"
5664 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5665 "The regular expression matching a sub- or superscript, forcing braces.")
5667 (defun org-make-link-regexps ()
5668 "Update the link regular expressions.
5669 This should be called after the variable `org-link-parameters' has changed."
5670 (let ((types-re (regexp-opt (org-link-types) t)))
5671 (setq org-link-types-re
5672 (concat "\\`" types-re ":")
5673 org-link-re-with-space
5674 (concat "<?" types-re ":"
5675 "\\([^" org-non-link-chars " ]"
5676 "[^" org-non-link-chars "]*"
5677 "[^" org-non-link-chars " ]\\)>?")
5678 org-link-re-with-space2
5679 (concat "<?" types-re ":"
5680 "\\([^" org-non-link-chars " ]"
5681 "[^\t\n\r]*"
5682 "[^" org-non-link-chars " ]\\)>?")
5683 org-link-re-with-space3
5684 (concat "<?" types-re ":"
5685 "\\([^" org-non-link-chars " ]"
5686 "[^\t\n\r]*\\)")
5687 org-angle-link-re
5688 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5689 types-re)
5690 org-plain-link-re
5691 (concat
5692 "\\<" types-re ":"
5693 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5694 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5695 org-bracket-link-regexp
5696 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5697 org-bracket-link-analytic-regexp
5698 (concat
5699 "\\[\\["
5700 "\\(" types-re ":\\)?"
5701 "\\([^]]+\\)"
5702 "\\]"
5703 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5704 "\\]")
5705 org-bracket-link-analytic-regexp++
5706 (concat
5707 "\\[\\["
5708 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5709 "\\([^]]+\\)"
5710 "\\]"
5711 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5712 "\\]")
5713 org-any-link-re
5714 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5715 org-angle-link-re "\\)\\|\\("
5716 org-plain-link-re "\\)"))))
5718 (org-make-link-regexps)
5720 (defvar org-emph-face nil)
5722 (defun org-do-emphasis-faces (limit)
5723 "Run through the buffer and emphasize strings."
5724 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5725 (car org-emphasis-regexp-components))))
5726 (catch :exit
5727 (while (re-search-forward quick-re limit t)
5728 (let* ((marker (match-string 2))
5729 (verbatim? (member marker '("~" "="))))
5730 (when (save-excursion
5731 (goto-char (match-beginning 0))
5732 (and
5733 ;; Do not match table hlines.
5734 (not (and (equal marker "+")
5735 (org-match-line
5736 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5737 ;; Do not match headline stars. Do not consider
5738 ;; stars of a headline as closing marker for bold
5739 ;; markup either.
5740 (not (and (equal marker "*")
5741 (save-excursion
5742 (forward-char)
5743 (skip-chars-backward "*")
5744 (looking-at-p org-outline-regexp-bol))))
5745 ;; Match full emphasis markup regexp.
5746 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5747 ;; Do not span over paragraph boundaries.
5748 (not (string-match-p org-element-paragraph-separate
5749 (match-string 2)))
5750 ;; Do not span over cells in table rows.
5751 (not (and (save-match-data (org-match-line "[ \t]*|"))
5752 (string-match-p "|" (match-string 4))))))
5753 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5754 (font-lock-prepend-text-property
5755 (match-beginning 2) (match-end 2) 'face face)
5756 (when verbatim?
5757 (org-remove-flyspell-overlays-in
5758 (match-beginning 0) (match-end 0)))
5759 (add-text-properties (match-beginning 2) (match-end 2)
5760 '(font-lock-multiline t org-emphasis t))
5761 (when org-hide-emphasis-markers
5762 (add-text-properties (match-end 4) (match-beginning 5)
5763 '(invisible org-link))
5764 (add-text-properties (match-beginning 3) (match-end 3)
5765 '(invisible org-link)))
5766 (throw :exit t))))))))
5768 (defun org-emphasize (&optional char)
5769 "Insert or change an emphasis, i.e. a font like bold or italic.
5770 If there is an active region, change that region to a new emphasis.
5771 If there is no region, just insert the marker characters and position
5772 the cursor between them.
5773 CHAR should be the marker character. If it is a space, it means to
5774 remove the emphasis of the selected region.
5775 If CHAR is not given (for example in an interactive call) it will be
5776 prompted for."
5777 (interactive)
5778 (let ((erc org-emphasis-regexp-components)
5779 (string "") beg end move s)
5780 (if (org-region-active-p)
5781 (setq beg (region-beginning)
5782 end (region-end)
5783 string (buffer-substring beg end))
5784 (setq move t))
5786 (unless char
5787 (message "Emphasis marker or tag: [%s]"
5788 (mapconcat #'car org-emphasis-alist ""))
5789 (setq char (read-char-exclusive)))
5790 (if (equal char ?\s)
5791 (setq s ""
5792 move nil)
5793 (unless (assoc (char-to-string char) org-emphasis-alist)
5794 (user-error "No such emphasis marker: \"%c\"" char))
5795 (setq s (char-to-string char)))
5796 (while (and (> (length string) 1)
5797 (equal (substring string 0 1) (substring string -1))
5798 (assoc (substring string 0 1) org-emphasis-alist))
5799 (setq string (substring string 1 -1)))
5800 (setq string (concat s string s))
5801 (when beg (delete-region beg end))
5802 (unless (or (bolp)
5803 (string-match (concat "[" (nth 0 erc) "\n]")
5804 (char-to-string (char-before (point)))))
5805 (insert " "))
5806 (unless (or (eobp)
5807 (string-match (concat "[" (nth 1 erc) "\n]")
5808 (char-to-string (char-after (point)))))
5809 (insert " ") (backward-char 1))
5810 (insert string)
5811 (and move (backward-char 1))))
5813 (defconst org-nonsticky-props
5814 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5816 (defsubst org-rear-nonsticky-at (pos)
5817 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5819 (defun org-activate-links (limit)
5820 "Add link properties to links.
5821 This includes angle, plain, and bracket links."
5822 (catch :exit
5823 (while (re-search-forward org-any-link-re limit t)
5824 (let* ((start (match-beginning 0))
5825 (end (match-end 0))
5826 (style (cond ((eq ?< (char-after start)) 'angle)
5827 ((eq ?\[ (char-after (1+ start))) 'bracket)
5828 (t 'plain))))
5829 (when (and (memq style org-highlight-links)
5830 ;; Do not confuse plain links with tags.
5831 (not (and (eq style 'plain)
5832 (let ((face (get-text-property
5833 (max (1- start) (point-min)) 'face)))
5834 (if (consp face) (memq 'org-tag face)
5835 (eq 'org-tag face))))))
5836 (let* ((link-object (save-excursion
5837 (goto-char start)
5838 (save-match-data (org-element-link-parser))))
5839 (link (org-element-property :raw-link link-object))
5840 (type (org-element-property :type link-object))
5841 (path (org-element-property :path link-object))
5842 (properties ;for link's visible part
5843 (list
5844 'face (pcase (org-link-get-parameter type :face)
5845 ((and (pred functionp) face) (funcall face path))
5846 ((and (pred facep) face) face)
5847 ((and (pred consp) face) face) ;anonymous
5848 (_ 'org-link))
5849 'mouse-face (or (org-link-get-parameter type :mouse-face)
5850 'highlight)
5851 'keymap (or (org-link-get-parameter type :keymap)
5852 org-mouse-map)
5853 'help-echo (pcase (org-link-get-parameter type :help-echo)
5854 ((and (pred stringp) echo) echo)
5855 ((and (pred functionp) echo) echo)
5856 (_ (concat "LINK: " link)))
5857 'htmlize-link (pcase (org-link-get-parameter type
5858 :htmlize-link)
5859 ((and (pred functionp) f) (funcall f))
5860 (_ `(:uri ,link)))
5861 'font-lock-multiline t)))
5862 (org-remove-flyspell-overlays-in start end)
5863 (org-rear-nonsticky-at end)
5864 (if (not (eq 'bracket style))
5865 (add-text-properties start end properties)
5866 ;; Handle invisible parts in bracket links.
5867 (remove-text-properties start end '(invisible nil))
5868 (let ((hidden
5869 (append `(invisible
5870 ,(or (org-link-get-parameter type :display)
5871 'org-link))
5872 properties))
5873 (visible-start (or (match-beginning 4) (match-beginning 2)))
5874 (visible-end (or (match-end 4) (match-end 2))))
5875 (add-text-properties start visible-start hidden)
5876 (add-text-properties visible-start visible-end properties)
5877 (add-text-properties visible-end end hidden)
5878 (org-rear-nonsticky-at visible-start)
5879 (org-rear-nonsticky-at visible-end)))
5880 (let ((f (org-link-get-parameter type :activate-func)))
5881 (when (functionp f)
5882 (funcall f start end path (eq style 'bracket))))
5883 (throw :exit t))))) ;signal success
5884 nil))
5886 (defun org-activate-code (limit)
5887 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5888 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5889 (remove-text-properties (match-beginning 0) (match-end 0)
5890 '(display t invisible t intangible t))
5893 (defcustom org-src-fontify-natively t
5894 "When non-nil, fontify code in code blocks.
5895 See also the `org-block' face."
5896 :type 'boolean
5897 :version "26.1"
5898 :package-version '(Org . "8.3")
5899 :group 'org-appearance
5900 :group 'org-babel)
5902 (defcustom org-allow-promoting-top-level-subtree nil
5903 "When non-nil, allow promoting a top level subtree.
5904 The leading star of the top level headline will be replaced
5905 by a #."
5906 :type 'boolean
5907 :version "24.1"
5908 :group 'org-appearance)
5910 (defun org-fontify-meta-lines-and-blocks (limit)
5911 (condition-case nil
5912 (org-fontify-meta-lines-and-blocks-1 limit)
5913 (error (message "Org mode fontification error in %S at %d"
5914 (current-buffer)
5915 (line-number-at-pos)))))
5917 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5918 "Fontify #+ lines and blocks."
5919 (let ((case-fold-search t))
5920 (when (re-search-forward
5921 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5922 limit t)
5923 (let ((beg (match-beginning 0))
5924 (block-start (match-end 0))
5925 (block-end nil)
5926 (lang (match-string 7))
5927 (beg1 (line-beginning-position 2))
5928 (dc1 (downcase (match-string 2)))
5929 (dc3 (downcase (match-string 3)))
5930 end end1 quoting block-type)
5931 (cond
5932 ((and (match-end 4) (equal dc3 "+begin"))
5933 ;; Truly a block
5934 (setq block-type (downcase (match-string 5))
5935 quoting (member block-type org-protecting-blocks))
5936 (when (re-search-forward
5937 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5938 nil t) ;; on purpose, we look further than LIMIT
5939 (setq end (min (point-max) (match-end 0))
5940 end1 (min (point-max) (1- (match-beginning 0))))
5941 (setq block-end (match-beginning 0))
5942 (when quoting
5943 (org-remove-flyspell-overlays-in beg1 end1)
5944 (remove-text-properties beg end
5945 '(display t invisible t intangible t)))
5946 (add-text-properties
5947 beg end '(font-lock-fontified t font-lock-multiline t))
5948 (add-text-properties beg beg1 '(face org-meta-line))
5949 (org-remove-flyspell-overlays-in beg beg1)
5950 (add-text-properties ; For end_src
5951 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5952 (org-remove-flyspell-overlays-in end1 end)
5953 (cond
5954 ((and lang (not (string= lang "")) org-src-fontify-natively)
5955 (org-src-font-lock-fontify-block lang block-start block-end)
5956 (add-text-properties beg1 block-end '(src-block t)))
5957 (quoting
5958 (add-text-properties beg1 (min (point-max) (1+ end1))
5959 (list 'face
5960 (list :inherit
5961 (let ((face-name
5962 (intern (format "org-block-%s" lang))))
5963 (append (and (facep face-name) (list face-name))
5964 '(org-block))))))) ; end of source block
5965 ((not org-fontify-quote-and-verse-blocks))
5966 ((string= block-type "quote")
5967 (add-face-text-property
5968 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5969 ((string= block-type "verse")
5970 (add-face-text-property
5971 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5972 (add-text-properties beg beg1 '(face org-block-begin-line))
5973 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5974 '(face org-block-end-line))
5976 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5977 (org-remove-flyspell-overlays-in
5978 (match-beginning 0)
5979 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5980 (add-text-properties
5981 beg (match-end 3)
5982 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5983 '(font-lock-fontified t invisible t)
5984 '(font-lock-fontified t face org-document-info-keyword)))
5985 (add-text-properties
5986 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5987 (if (string-equal dc1 "+title:")
5988 '(font-lock-fontified t face org-document-title)
5989 '(font-lock-fontified t face org-document-info))))
5990 ((string-prefix-p "+caption" dc1)
5991 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5992 (remove-text-properties (match-beginning 0) (match-end 0)
5993 '(display t invisible t intangible t))
5994 ;; Handle short captions.
5995 (save-excursion
5996 (beginning-of-line)
5997 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5998 (add-text-properties (line-beginning-position) (match-end 1)
5999 '(font-lock-fontified t face org-meta-line))
6000 (add-text-properties (match-end 0) (line-end-position)
6001 '(font-lock-fontified t face org-block))
6003 ((member dc3 '(" " ""))
6004 (org-remove-flyspell-overlays-in beg (match-end 0))
6005 (add-text-properties
6006 beg (match-end 0)
6007 '(font-lock-fontified t face font-lock-comment-face)))
6008 (t ;; just any other in-buffer setting, but not indented
6009 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6010 (remove-text-properties (match-beginning 0) (match-end 0)
6011 '(display t invisible t intangible t))
6012 (add-text-properties beg (match-end 0)
6013 '(font-lock-fontified t face org-meta-line))
6014 t))))))
6016 (defun org-fontify-drawers (limit)
6017 "Fontify drawers."
6018 (when (re-search-forward org-drawer-regexp limit t)
6019 (add-text-properties
6020 (match-beginning 0) (match-end 0)
6021 '(font-lock-fontified t face org-special-keyword))
6022 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6025 (defun org-fontify-macros (limit)
6026 "Fontify macros."
6027 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6028 (let ((begin (match-beginning 0))
6029 (opening-end (match-beginning 1)))
6030 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6031 (match-string 1))
6032 (let ((end (match-end 1))
6033 (closing-start (match-beginning 1)))
6034 (add-text-properties
6035 begin end
6036 '(font-lock-multiline t font-lock-fontified t face org-macro))
6037 (org-remove-flyspell-overlays-in begin end)
6038 (when org-hide-macro-markers
6039 (add-text-properties begin opening-end '(invisible t))
6040 (add-text-properties closing-start end '(invisible t)))
6041 t)))))
6043 (defun org-activate-footnote-links (limit)
6044 "Add text properties for footnotes."
6045 (let ((fn (org-footnote-next-reference-or-definition limit)))
6046 (when fn
6047 (let* ((beg (nth 1 fn))
6048 (end (nth 2 fn))
6049 (label (car fn))
6050 (referencep (/= (line-beginning-position) beg)))
6051 (when (and referencep (nth 3 fn))
6052 (save-excursion
6053 (goto-char beg)
6054 (search-forward (or label "fn:"))
6055 (org-remove-flyspell-overlays-in beg (match-end 0))))
6056 (add-text-properties beg end
6057 (list 'mouse-face 'highlight
6058 'keymap org-mouse-map
6059 'help-echo
6060 (if referencep "Footnote reference"
6061 "Footnote definition")
6062 'font-lock-fontified t
6063 'font-lock-multiline t
6064 'face 'org-footnote))))))
6066 (defun org-activate-dates (limit)
6067 "Add text properties for dates."
6068 (when (and (re-search-forward org-tsr-regexp-both limit t)
6069 (not (equal (char-before (match-beginning 0)) 91)))
6070 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6071 (add-text-properties (match-beginning 0) (match-end 0)
6072 (list 'mouse-face 'highlight
6073 'keymap org-mouse-map))
6074 (org-rear-nonsticky-at (match-end 0))
6075 (when org-display-custom-times
6076 ;; If it's a date range, activate custom time for second date.
6077 (when (match-end 3)
6078 (org-display-custom-time (match-beginning 3) (match-end 3)))
6079 (org-display-custom-time (match-beginning 1) (match-end 1)))
6082 (defvar-local org-target-link-regexp nil
6083 "Regular expression matching radio targets in plain text.")
6085 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6086 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6087 border border border))
6088 "Regular expression matching a link target.")
6090 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6091 "Regular expression matching a radio target.")
6093 (defconst org-any-target-regexp
6094 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6095 "Regular expression matching any target.")
6097 (defun org-activate-target-links (limit)
6098 "Add text properties for target matches."
6099 (when org-target-link-regexp
6100 (let ((case-fold-search t))
6101 (when (re-search-forward org-target-link-regexp limit t)
6102 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6103 (add-text-properties (match-beginning 1) (match-end 1)
6104 (list 'mouse-face 'highlight
6105 'keymap org-mouse-map
6106 'help-echo "Radio target link"
6107 'org-linked-text t))
6108 (org-rear-nonsticky-at (match-end 1))
6109 t))))
6111 (defun org-update-radio-target-regexp ()
6112 "Find all radio targets in this file and update the regular expression.
6113 Also refresh fontification if needed."
6114 (interactive)
6115 (let ((old-regexp org-target-link-regexp)
6116 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6117 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6118 (targets
6119 (org-with-wide-buffer
6120 (goto-char (point-min))
6121 (let (rtn)
6122 (while (re-search-forward org-radio-target-regexp nil t)
6123 ;; Make sure point is really within the object.
6124 (backward-char)
6125 (let ((obj (org-element-context)))
6126 (when (eq (org-element-type obj) 'radio-target)
6127 (cl-pushnew (org-element-property :value obj) rtn
6128 :test #'equal))))
6129 rtn))))
6130 (setq org-target-link-regexp
6131 (and targets
6132 (concat before-re
6133 (mapconcat
6134 (lambda (x)
6135 (replace-regexp-in-string
6136 " +" "\\s-+" (regexp-quote x) t t))
6137 targets
6138 "\\|")
6139 after-re)))
6140 (unless (equal old-regexp org-target-link-regexp)
6141 ;; Clean-up cache.
6142 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6143 ((not org-target-link-regexp) old-regexp)
6145 (concat before-re
6146 (mapconcat
6147 (lambda (re)
6148 (substring re (length before-re)
6149 (- (length after-re))))
6150 (list old-regexp org-target-link-regexp)
6151 "\\|")
6152 after-re)))))
6153 (org-with-wide-buffer
6154 (goto-char (point-min))
6155 (while (re-search-forward regexp nil t)
6156 (org-element-cache-refresh (match-beginning 1)))))
6157 ;; Re fontify buffer.
6158 (when (memq 'radio org-highlight-links)
6159 (org-restart-font-lock)))))
6161 (defvar org-latex-and-related-regexp nil
6162 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6164 (defun org-compute-latex-and-related-regexp ()
6165 "Compute regular expression for LaTeX, entities and sub/superscript.
6166 Result depends on variable `org-highlight-latex-and-related'."
6167 (setq-local
6168 org-latex-and-related-regexp
6169 (let* ((re-sub
6170 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6171 ((eq org-use-sub-superscripts '{})
6172 (list org-match-substring-with-braces-regexp))
6173 (org-use-sub-superscripts (list org-match-substring-regexp))))
6174 (re-latex
6175 (when (memq 'latex org-highlight-latex-and-related)
6176 (let ((matchers (plist-get org-format-latex-options :matchers)))
6177 (delq nil
6178 (mapcar (lambda (x)
6179 (and (member (car x) matchers) (nth 1 x)))
6180 org-latex-regexps)))))
6181 (re-entities
6182 (when (memq 'entities org-highlight-latex-and-related)
6183 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6184 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6186 (defun org-do-latex-and-related (limit)
6187 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6188 LIMIT bounds the search for syntax to highlight. Stop at first
6189 highlighted object, if any. Return t if some highlighting was
6190 done, nil otherwise."
6191 (when (org-string-nw-p org-latex-and-related-regexp)
6192 (catch 'found
6193 (while (re-search-forward org-latex-and-related-regexp limit t)
6194 (unless
6195 (cl-some
6196 (lambda (f)
6197 (memq f '(org-code org-verbatim underline org-special-keyword)))
6198 (save-excursion
6199 (goto-char (1+ (match-beginning 0)))
6200 (face-at-point nil t)))
6201 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6202 '(?_ ?^))
6204 0)))
6205 (font-lock-prepend-text-property
6206 (+ offset (match-beginning 0)) (match-end 0)
6207 'face 'org-latex-and-related)
6208 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6209 '(font-lock-multiline t)))
6210 (throw 'found t)))
6211 nil)))
6213 (defun org-restart-font-lock ()
6214 "Restart `font-lock-mode', to force refontification."
6215 (when (and (boundp 'font-lock-mode) font-lock-mode)
6216 (font-lock-mode -1)
6217 (font-lock-mode 1)))
6219 (defun org-activate-tags (limit)
6220 (when (re-search-forward org-tag-line-re limit t)
6221 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6222 (add-text-properties (match-beginning 1) (match-end 1)
6223 (list 'mouse-face 'highlight
6224 'keymap org-mouse-map))
6225 (org-rear-nonsticky-at (match-end 1))
6228 (defun org-outline-level ()
6229 "Compute the outline level of the heading at point.
6231 If this is called at a normal headline, the level is the number
6232 of stars. Use `org-reduced-level' to remove the effect of
6233 `org-odd-levels'. Unlike to `org-current-level', this function
6234 takes into consideration inlinetasks."
6235 (org-with-wide-buffer
6236 (end-of-line)
6237 (if (re-search-backward org-outline-regexp-bol nil t)
6238 (1- (- (match-end 0) (match-beginning 0)))
6239 0)))
6241 (defvar org-font-lock-keywords nil)
6243 (defsubst org-re-property (property &optional literal allow-null value)
6244 "Return a regexp matching a PROPERTY line.
6246 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6247 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6248 non-nil, match properties even without a value.
6250 Match group 3 is set to the value when it exists. If there is no
6251 value and ALLOW-NULL is non-nil, it is set to the empty string.
6253 With optional argument VALUE, match only property lines with
6254 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6255 unless LITERAL is non-nil."
6256 (concat
6257 "^\\(?4:[ \t]*\\)"
6258 (format "\\(?1::\\(?2:%s\\):\\)"
6259 (if literal property (regexp-quote property)))
6260 (cond (value
6261 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6262 (if literal value (regexp-quote value))))
6263 (allow-null
6264 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6266 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6268 (defconst org-property-re
6269 (org-re-property "\\S-+" 'literal t)
6270 "Regular expression matching a property line.
6271 There are four matching groups:
6272 1: :PROPKEY: including the leading and trailing colon,
6273 2: PROPKEY without the leading and trailing colon,
6274 3: PROPVAL without leading or trailing spaces,
6275 4: the indentation of the current line,
6276 5: trailing whitespace.")
6278 (defvar org-font-lock-hook nil
6279 "Functions to be called for special font lock stuff.")
6281 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6283 (defvar org-font-lock-set-keywords-hook nil
6284 "Functions that can manipulate `org-font-lock-extra-keywords'.
6285 This is called after `org-font-lock-extra-keywords' is defined, but before
6286 it is installed to be used by font lock. This can be useful if something
6287 needs to be inserted at a specific position in the font-lock sequence.")
6289 (defun org-font-lock-hook (limit)
6290 "Run `org-font-lock-hook' within LIMIT."
6291 (run-hook-with-args 'org-font-lock-hook limit))
6293 (defun org-set-font-lock-defaults ()
6294 "Set font lock defaults for the current buffer."
6295 (let* ((em org-fontify-emphasized-text)
6296 (lk org-highlight-links)
6297 (org-font-lock-extra-keywords
6298 (list
6299 ;; Call the hook
6300 '(org-font-lock-hook)
6301 ;; Headlines
6302 `(,(if org-fontify-whole-heading-line
6303 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6304 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6305 (1 (org-get-level-face 1))
6306 (2 (org-get-level-face 2))
6307 (3 (org-get-level-face 3)))
6308 ;; Table lines
6309 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6310 (1 'org-table t))
6311 ;; Table internals
6312 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6313 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6314 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6315 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6316 ;; Drawers
6317 '(org-fontify-drawers)
6318 ;; Properties
6319 (list org-property-re
6320 '(1 'org-special-keyword t)
6321 '(3 'org-property-value t))
6322 ;; Link related fontification.
6323 '(org-activate-links)
6324 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6325 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6326 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6327 (when (memq 'footnote lk) '(org-activate-footnote-links))
6328 ;; Targets.
6329 (list org-any-target-regexp '(0 'org-target t))
6330 ;; Diary sexps.
6331 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6332 ;; Macro
6333 '(org-fontify-macros)
6334 ;; TODO keyword
6335 (list (format org-heading-keyword-regexp-format
6336 org-todo-regexp)
6337 '(2 (org-get-todo-face 2) t))
6338 ;; DONE
6339 (if org-fontify-done-headline
6340 (list (format org-heading-keyword-regexp-format
6341 (concat
6342 "\\(?:"
6343 (mapconcat 'regexp-quote org-done-keywords "\\|")
6344 "\\)"))
6345 '(2 'org-headline-done t))
6346 nil)
6347 ;; Priorities
6348 '(org-font-lock-add-priority-faces)
6349 ;; Tags
6350 '(org-font-lock-add-tag-faces)
6351 ;; Tags groups
6352 (when (and org-group-tags org-tag-groups-alist)
6353 (list (concat org-outline-regexp-bol ".+\\(:"
6354 (regexp-opt (mapcar 'car org-tag-groups-alist))
6355 ":\\).*$")
6356 '(1 'org-tag-group prepend)))
6357 ;; Special keywords
6358 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6359 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6360 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6361 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6362 ;; Emphasis
6363 (when em '(org-do-emphasis-faces))
6364 ;; Checkboxes
6365 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6366 1 'org-checkbox prepend)
6367 (when (cdr (assq 'checkbox org-list-automatic-rules))
6368 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6369 (0 (org-get-checkbox-statistics-face) t)))
6370 ;; Description list items
6371 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6372 1 'org-list-dt prepend)
6373 ;; ARCHIVEd headings
6374 (list (concat
6375 org-outline-regexp-bol
6376 "\\(.*:" org-archive-tag ":.*\\)")
6377 '(1 'org-archived prepend))
6378 ;; Specials
6379 '(org-do-latex-and-related)
6380 '(org-fontify-entities)
6381 '(org-raise-scripts)
6382 ;; Code
6383 '(org-activate-code (1 'org-code t))
6384 ;; COMMENT
6385 (list (format
6386 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6387 org-todo-regexp
6388 org-comment-string)
6389 '(9 'org-special-keyword t))
6390 ;; Blocks and meta lines
6391 '(org-fontify-meta-lines-and-blocks))))
6392 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6393 (run-hooks 'org-font-lock-set-keywords-hook)
6394 ;; Now set the full font-lock-keywords
6395 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6396 (setq-local font-lock-defaults
6397 '(org-font-lock-keywords t nil nil backward-paragraph))
6398 (kill-local-variable 'font-lock-keywords)
6399 nil))
6401 (defun org-toggle-pretty-entities ()
6402 "Toggle the composition display of entities as UTF8 characters."
6403 (interactive)
6404 (setq-local org-pretty-entities (not org-pretty-entities))
6405 (org-restart-font-lock)
6406 (if org-pretty-entities
6407 (message "Entities are now displayed as UTF8 characters")
6408 (save-restriction
6409 (widen)
6410 (decompose-region (point-min) (point-max))
6411 (message "Entities are now displayed as plain text"))))
6413 (defvar-local org-custom-properties-overlays nil
6414 "List of overlays used for custom properties.")
6416 (defun org-toggle-custom-properties-visibility ()
6417 "Display or hide properties in `org-custom-properties'."
6418 (interactive)
6419 (if org-custom-properties-overlays
6420 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6421 (setq org-custom-properties-overlays nil))
6422 (when org-custom-properties
6423 (org-with-wide-buffer
6424 (goto-char (point-min))
6425 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6426 (while (re-search-forward regexp nil t)
6427 (let ((end (cdr (save-match-data (org-get-property-block)))))
6428 (when (and end (< (point) end))
6429 ;; Hide first custom property in current drawer.
6430 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6431 (overlay-put o 'invisible t)
6432 (overlay-put o 'org-custom-property t)
6433 (push o org-custom-properties-overlays))
6434 ;; Hide additional custom properties in the same drawer.
6435 (while (re-search-forward regexp end t)
6436 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6437 (overlay-put o 'invisible t)
6438 (overlay-put o 'org-custom-property t)
6439 (push o org-custom-properties-overlays)))))
6440 ;; Each entry is limited to a single property drawer.
6441 (outline-next-heading)))))))
6443 (defun org-fontify-entities (limit)
6444 "Find an entity to fontify."
6445 (let (ee)
6446 (when org-pretty-entities
6447 (catch 'match
6448 ;; "\_ "-family is left out on purpose. Only the first one,
6449 ;; i.e., "\_ ", could be fontified anyway, and it would be
6450 ;; confusing when adding a second white space character.
6451 (while (re-search-forward
6452 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6453 limit t)
6454 (when (and (not (org-at-comment-p))
6455 (setq ee (org-entity-get (match-string 1)))
6456 (= (length (nth 6 ee)) 1))
6457 (let* ((end (if (equal (match-string 2) "{}")
6458 (match-end 2)
6459 (match-end 1))))
6460 (add-text-properties
6461 (match-beginning 0) end
6462 (list 'font-lock-fontified t))
6463 (compose-region (match-beginning 0) end
6464 (nth 6 ee) nil)
6465 (backward-char 1)
6466 (throw 'match t))))
6467 nil))))
6469 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6470 "Fontify string S like in Org mode."
6471 (with-temp-buffer
6472 (insert s)
6473 (let ((org-odd-levels-only odd-levels))
6474 (org-mode)
6475 (org-font-lock-ensure)
6476 (buffer-string))))
6478 (defvar org-m nil)
6479 (defvar org-l nil)
6480 (defvar org-f nil)
6481 (defun org-get-level-face (n)
6482 "Get the right face for match N in font-lock matching of headlines."
6483 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6484 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6485 (if org-cycle-level-faces
6486 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6487 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6488 (cond
6489 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6490 ((eq n 2) org-f)
6491 (t (unless org-level-color-stars-only org-f))))
6493 (defun org-face-from-face-or-color (context inherit face-or-color)
6494 "Create a face list that inherits INHERIT, but sets the foreground color.
6495 When FACE-OR-COLOR is not a string, just return it."
6496 (if (stringp face-or-color)
6497 (list :inherit inherit
6498 (cdr (assoc context org-faces-easy-properties))
6499 face-or-color)
6500 face-or-color))
6502 (defun org-get-todo-face (kwd)
6503 "Get the right face for a TODO keyword KWD.
6504 If KWD is a number, get the corresponding match group."
6505 (when (numberp kwd) (setq kwd (match-string kwd)))
6506 (or (org-face-from-face-or-color
6507 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6508 (and (member kwd org-done-keywords) 'org-done)
6509 'org-todo))
6511 (defun org-get-priority-face (priority)
6512 "Get the right face for PRIORITY.
6513 PRIORITY is a character."
6514 (or (org-face-from-face-or-color
6515 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6516 'org-priority))
6518 (defun org-get-tag-face (tag)
6519 "Get the right face for TAG.
6520 If TAG is a number, get the corresponding match group."
6521 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6522 (or (org-face-from-face-or-color
6523 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6524 'org-tag)))
6526 (defun org-font-lock-add-priority-faces (limit)
6527 "Add the special priority faces."
6528 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6529 (add-text-properties
6530 (match-beginning 1) (match-end 1)
6531 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6532 'font-lock-fontified t))))
6534 (defun org-font-lock-add-tag-faces (limit)
6535 "Add the special tag faces."
6536 (when (and org-tag-faces org-tags-special-faces-re)
6537 (while (re-search-forward org-tags-special-faces-re limit t)
6538 (add-text-properties (match-beginning 1) (match-end 1)
6539 (list 'face (org-get-tag-face 1)
6540 'font-lock-fontified t))
6541 (backward-char 1))))
6543 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6544 "Remove fontification and activation overlays from links."
6545 (font-lock-default-unfontify-region beg end)
6546 (let* ((buffer-undo-list t)
6547 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6548 (inhibit-modification-hooks t)
6549 deactivate-mark buffer-file-name buffer-file-truename)
6550 (decompose-region beg end)
6551 (remove-text-properties beg end
6552 '(mouse-face t keymap t org-linked-text t
6553 invisible t intangible t
6554 org-emphasis t))
6555 (org-remove-font-lock-display-properties beg end)))
6557 (defconst org-script-display '(((raise -0.3) (height 0.7))
6558 ((raise 0.3) (height 0.7))
6559 ((raise -0.5))
6560 ((raise 0.5)))
6561 "Display properties for showing superscripts and subscripts.")
6563 (defun org-remove-font-lock-display-properties (beg end)
6564 "Remove specific display properties that have been added by font lock.
6565 The will remove the raise properties that are used to show superscripts
6566 and subscripts."
6567 (let (next prop)
6568 (while (< beg end)
6569 (setq next (next-single-property-change beg 'display nil end)
6570 prop (get-text-property beg 'display))
6571 (when (member prop org-script-display)
6572 (put-text-property beg next 'display nil))
6573 (setq beg next))))
6575 (defun org-raise-scripts (limit)
6576 "Add raise properties to sub/superscripts."
6577 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6578 (re-search-forward
6579 (if (eq org-use-sub-superscripts t)
6580 org-match-substring-regexp
6581 org-match-substring-with-braces-regexp)
6582 limit t))
6583 (let* ((pos (point)) table-p comment-p
6584 (mpos (match-beginning 3))
6585 (emph-p (get-text-property mpos 'org-emphasis))
6586 (link-p (get-text-property mpos 'mouse-face))
6587 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6588 (goto-char (point-at-bol))
6589 (setq table-p (looking-at-p org-table-dataline-regexp)
6590 comment-p (looking-at-p "^[ \t]*#[ +]"))
6591 (goto-char pos)
6592 ;; Handle a_b^c
6593 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6594 (unless (or comment-p emph-p link-p keyw-p)
6595 (put-text-property (match-beginning 3) (match-end 0)
6596 'display
6597 (if (equal (char-after (match-beginning 2)) ?^)
6598 (nth (if table-p 3 1) org-script-display)
6599 (nth (if table-p 2 0) org-script-display)))
6600 (add-text-properties (match-beginning 2) (match-end 2)
6601 (list 'invisible t))
6602 (when (and (eq (char-after (match-beginning 3)) ?{)
6603 (eq (char-before (match-end 3)) ?}))
6604 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6605 (list 'invisible t))
6606 (add-text-properties (1- (match-end 3)) (match-end 3)
6607 (list 'invisible t))))
6608 t)))
6610 (defun org-remove-empty-overlays-at (pos)
6611 "Remove outline overlays that do not contain non-white stuff."
6612 (dolist (o (overlays-at pos))
6613 (and (eq 'outline (overlay-get o 'invisible))
6614 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6615 (overlay-end o))))
6616 (delete-overlay o))))
6618 (defun org-show-empty-lines-in-parent ()
6619 "Move to the parent and re-show empty lines before visible headlines."
6620 (save-excursion
6621 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6622 (org-cycle-show-empty-lines context))))
6624 (defun org-files-list ()
6625 "Return `org-agenda-files' list, plus all open Org files.
6626 This is useful for operations that need to scan all of a user's
6627 open and agenda-wise Org files."
6628 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6629 (dolist (buf (buffer-list))
6630 (with-current-buffer buf
6631 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6632 (cl-pushnew (expand-file-name (buffer-file-name)) files
6633 :test #'equal))))
6634 files))
6636 (defsubst org-entry-beginning-position ()
6637 "Return the beginning position of the current entry."
6638 (save-excursion (org-back-to-heading t) (point)))
6640 (defsubst org-entry-end-position ()
6641 "Return the end position of the current entry."
6642 (save-excursion (outline-next-heading) (point)))
6644 (defun org-subtree-end-visible-p ()
6645 "Is the end of the current subtree visible?"
6646 (pos-visible-in-window-p
6647 (save-excursion (org-end-of-subtree t) (point))))
6649 (defun org-first-headline-recenter ()
6650 "Move cursor to the first headline and recenter the headline."
6651 (let ((window (get-buffer-window)))
6652 (when window
6653 (goto-char (point-min))
6654 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6655 (set-window-start window (line-beginning-position))))))
6658 ;;; Visibility (headlines, blocks, drawers)
6660 ;;;; Headlines visibility
6662 (defun org-show-entry ()
6663 "Show the body directly following this heading.
6664 Show the heading too, if it is currently invisible."
6665 (interactive)
6666 (save-excursion
6667 (ignore-errors
6668 (org-back-to-heading t)
6669 (org-flag-region
6670 (line-end-position 0)
6671 (save-excursion
6672 (if (re-search-forward
6673 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6674 (match-beginning 1)
6675 (point-max)))
6677 'outline))))
6679 (defun org-show-children (&optional level)
6680 "Show all direct subheadings of this heading.
6681 Prefix arg LEVEL is how many levels below the current level
6682 should be shown. Default is enough to cause the following
6683 heading to appear."
6684 (interactive "p")
6685 (save-excursion
6686 (org-back-to-heading t)
6687 (let* ((current-level (funcall outline-level))
6688 (max-level (org-get-valid-level
6689 current-level
6690 (if level (prefix-numeric-value level) 1)))
6691 (end (save-excursion (org-end-of-subtree t t)))
6692 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6693 (past-first-child nil)
6694 ;; Make sure to skip inlinetasks.
6695 (re (format regexp-fmt
6696 current-level
6697 (cond
6698 ((not (featurep 'org-inlinetask)) "")
6699 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6701 (t (1- org-inlinetask-min-level))))))
6702 ;; Display parent heading.
6703 (org-flag-heading nil)
6704 (forward-line)
6705 ;; Display children. First child may be deeper than expected
6706 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6707 ;; MAX-LEVEL accordingly.
6708 (while (re-search-forward re end t)
6709 (unless past-first-child
6710 (setq re (format regexp-fmt
6711 current-level
6712 (max (funcall outline-level) max-level)))
6713 (setq past-first-child t))
6714 (org-flag-heading nil)))))
6716 (defun org-show-subtree ()
6717 "Show everything after this heading at deeper levels."
6718 (interactive)
6719 (org-flag-region
6720 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6722 ;;;; Blocks visibility
6724 (defun org-hide-block-toggle-maybe ()
6725 "Toggle visibility of block at point.
6726 Unlike to `org-hide-block-toggle', this function does not throw
6727 an error. Return a non-nil value when toggling is successful."
6728 (interactive)
6729 (ignore-errors (org-hide-block-toggle)))
6731 (defun org-hide-block-toggle (&optional force)
6732 "Toggle the visibility of the current block.
6733 When optional argument FORCE is `off', make block visible. If it
6734 is non-nil, hide it unconditionally. Throw an error when not at
6735 a block. Return a non-nil value when toggling is successful."
6736 (interactive)
6737 (let ((element (org-element-at-point)))
6738 (unless (memq (org-element-type element)
6739 '(center-block comment-block dynamic-block example-block
6740 export-block quote-block special-block
6741 src-block verse-block))
6742 (user-error "Not at a block"))
6743 (let* ((post (org-element-property :post-affiliated element))
6744 (start (save-excursion
6745 (goto-char post)
6746 (line-end-position)))
6747 (end (save-excursion
6748 (goto-char (org-element-property :end element))
6749 (skip-chars-backward " \t\n")
6750 (line-end-position))))
6751 ;; Do nothing when not before or at the block opening line or at
6752 ;; the block closing line.
6753 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6754 (cond ((eq force 'off)
6755 (org-flag-region start end nil 'org-hide-block))
6756 (force
6757 (org-flag-region start end t 'org-hide-block))
6758 ((eq (get-char-property start 'invisible) 'org-hide-block)
6759 (org-flag-region start end nil 'org-hide-block))
6761 (org-flag-region start end t 'org-hide-block)))
6762 ;; When the block is hidden away, make sure point is left in
6763 ;; a visible part of the buffer.
6764 (when (invisible-p (max (1- (point)) (point-min)))
6765 (goto-char post))
6766 ;; Signal success.
6767 t))))
6769 (defun org-hide-block-toggle-all ()
6770 "Toggle the visibility of all blocks in the current buffer."
6771 (org-block-map 'org-hide-block-toggle))
6773 (defun org-hide-block-all ()
6774 "Fold all blocks in the current buffer."
6775 (interactive)
6776 (org-show-all '(blocks))
6777 (org-block-map 'org-hide-block-toggle-maybe))
6779 ;;;; Drawers visibility
6781 (defun org-cycle-hide-drawers (state &optional exceptions)
6782 "Re-hide all drawers after a visibility state change.
6783 STATE should be one of the symbols listed in the docstring of
6784 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6785 a list of strings specifying which drawers should not be hidden."
6786 (when (and (derived-mode-p 'org-mode)
6787 (not (memq state '(overview folded contents))))
6788 (save-excursion
6789 (let* ((globalp (eq state 'all))
6790 (beg (if globalp (point-min) (point)))
6791 (end (if globalp (point-max)
6792 (if (eq state 'children)
6793 (save-excursion (outline-next-heading) (point))
6794 (org-end-of-subtree t)))))
6795 (goto-char beg)
6796 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6797 (unless (member-ignore-case (match-string 1) exceptions)
6798 (let ((drawer (org-element-at-point)))
6799 (when (memq (org-element-type drawer) '(drawer property-drawer))
6800 (org-flag-drawer t drawer)
6801 ;; Make sure to skip drawer entirely or we might flag
6802 ;; it another time when matching its ending line with
6803 ;; `org-drawer-regexp'.
6804 (goto-char (org-element-property :end drawer))))))))))
6806 (defun org-flag-drawer (flag &optional element)
6807 "When FLAG is non-nil, hide the drawer we are at.
6808 Otherwise make it visible. When optional argument ELEMENT is
6809 a parsed drawer, as returned by `org-element-at-point', hide or
6810 show that drawer instead."
6811 (let ((drawer (or element
6812 (and (save-excursion
6813 (beginning-of-line)
6814 (looking-at-p org-drawer-regexp))
6815 (org-element-at-point)))))
6816 (when (memq (org-element-type drawer) '(drawer property-drawer))
6817 (let ((post (org-element-property :post-affiliated drawer)))
6818 (org-flag-region
6819 (save-excursion (goto-char post) (line-end-position))
6820 (save-excursion (goto-char (org-element-property :end drawer))
6821 (skip-chars-backward " \t\n")
6822 (line-end-position))
6823 flag 'org-hide-drawer)
6824 ;; When the drawer is hidden away, make sure point lies in
6825 ;; a visible part of the buffer.
6826 (when (invisible-p (max (1- (point)) (point-min)))
6827 (goto-char post))))))
6829 ;;;; Visibility cycling
6831 (defvar-local org-cycle-global-status nil)
6832 (put 'org-cycle-global-status 'org-state t)
6833 (defvar-local org-cycle-subtree-status nil)
6834 (put 'org-cycle-subtree-status 'org-state t)
6836 (defun org-show-all (&optional types)
6837 "Show all contents in the visible part of the buffer.
6838 By default, the function expands headings, blocks and drawers.
6839 When optional argument TYPE is a list of symbols among `blocks',
6840 `drawers' and `headings', to only expand one specific type."
6841 (dolist (type (or types '(blocks drawers headings)))
6842 (org-flag-region (point-min) (point-max) nil
6843 (pcase type
6844 (`blocks 'org-hide-block)
6845 (`drawers 'org-hide-drawer)
6846 (`headings 'outline)
6847 (_ (error "Invalid type: %S" type))))))
6849 ;;;###autoload
6850 (defun org-cycle (&optional arg)
6851 "TAB-action and visibility cycling for Org mode.
6853 This is the command invoked in Org mode by the `TAB' key. Its main
6854 purpose is outline visibility cycling, but it also invokes other actions
6855 in special contexts.
6857 When this function is called with a `\\[universal-argument]' prefix, rotate \
6858 the entire
6859 buffer through 3 states (global cycling)
6860 1. OVERVIEW: Show only top-level headlines.
6861 2. CONTENTS: Show all headlines of all levels, but no body text.
6862 3. SHOW ALL: Show everything.
6864 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6865 switch to the startup visibility,
6866 determined by the variable `org-startup-folded', and by any VISIBILITY
6867 properties in the buffer.
6869 With a `\\[universal-argument] \\[universal-argument] \
6870 \\[universal-argument]' prefix argument, show the entire buffer, including
6871 any drawers.
6873 When inside a table, re-align the table and move to the next field.
6875 When point is at the beginning of a headline, rotate the subtree started
6876 by this line through 3 different states (local cycling)
6877 1. FOLDED: Only the main headline is shown.
6878 2. CHILDREN: The main headline and the direct children are shown.
6879 From this state, you can move to one of the children
6880 and zoom in further.
6881 3. SUBTREE: Show the entire subtree, including body text.
6882 If there is no subtree, switch directly from CHILDREN to FOLDED.
6884 When point is at the beginning of an empty headline and the variable
6885 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6886 of the headline by demoting and promoting it to likely levels. This
6887 speeds up creation document structure by pressing `TAB' once or several
6888 times right after creating a new headline.
6890 When there is a numeric prefix, go up to a heading with level ARG, do
6891 a `show-subtree' and return to the previous cursor position. If ARG
6892 is negative, go up that many levels.
6894 When point is not at the beginning of a headline, execute the global
6895 binding for `TAB', which is re-indenting the line. See the option
6896 `org-cycle-emulate-tab' for details.
6898 As a special case, if point is at the beginning of the buffer and there is
6899 no headline in line 1, this function will act as if called with prefix arg
6900 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6901 prefix arg, but only
6902 if the variable `org-cycle-global-at-bob' is t."
6903 (interactive "P")
6904 (org-load-modules-maybe)
6905 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6906 (and org-cycle-level-after-item/entry-creation
6907 (or (org-cycle-level)
6908 (org-cycle-item-indentation))))
6909 (let* ((limit-level
6910 (or org-cycle-max-level
6911 (and (boundp 'org-inlinetask-min-level)
6912 org-inlinetask-min-level
6913 (1- org-inlinetask-min-level))))
6914 (nstars (and limit-level
6915 (if org-odd-levels-only
6916 (and limit-level (1- (* limit-level 2)))
6917 limit-level)))
6918 (org-outline-regexp
6919 (if (not (derived-mode-p 'org-mode))
6920 outline-regexp
6921 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6922 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6923 (not (looking-at org-outline-regexp))))
6924 (org-cycle-hook
6925 (if bob-special
6926 (delq 'org-optimize-window-after-visibility-change
6927 (copy-sequence org-cycle-hook))
6928 org-cycle-hook))
6929 (pos (point)))
6931 (cond
6933 ((equal arg '(16))
6934 (setq last-command 'dummy)
6935 (org-set-startup-visibility)
6936 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6938 ((equal arg '(64))
6939 (org-show-all)
6940 (org-unlogged-message "Entire buffer visible, including drawers"))
6942 ((equal arg '(4)) (org-cycle-internal-global))
6944 ;; Try hiding block at point.
6945 ((org-hide-block-toggle-maybe))
6947 ;; Try cdlatex TAB completion
6948 ((org-try-cdlatex-tab))
6950 ;; Table: enter it or move to the next field.
6951 ((org-at-table-p 'any)
6952 (if (org-at-table.el-p)
6953 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6954 Use `\\[org-edit-special]' to edit table.el tables"))
6955 (if arg (org-table-edit-field t)
6956 (org-table-justify-field-maybe)
6957 (call-interactively 'org-table-next-field))))
6959 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6961 ;; Global cycling: delegate to `org-cycle-internal-global'.
6962 (bob-special (org-cycle-internal-global))
6964 ;; Drawers: delegate to `org-flag-drawer'.
6965 ((save-excursion
6966 (beginning-of-line 1)
6967 (looking-at org-drawer-regexp))
6968 (org-flag-drawer ; toggle block visibility
6969 (not (get-char-property (match-end 0) 'invisible))))
6971 ;; Show-subtree, ARG levels up from here.
6972 ((integerp arg)
6973 (save-excursion
6974 (org-back-to-heading)
6975 (outline-up-heading (if (< arg 0) (- arg)
6976 (- (funcall outline-level) arg)))
6977 (org-show-subtree)))
6979 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6980 ((and (featurep 'org-inlinetask)
6981 (org-inlinetask-at-task-p)
6982 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6983 (org-inlinetask-toggle-visibility))
6985 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6986 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6987 (save-excursion (move-beginning-of-line 1)
6988 (looking-at org-outline-regexp)))
6989 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6990 (org-cycle-internal-local))
6992 ;; From there: TAB emulation and template completion.
6993 (buffer-read-only (org-back-to-heading))
6995 ((run-hook-with-args-until-success
6996 'org-tab-after-check-for-cycling-hook))
6998 ((run-hook-with-args-until-success
6999 'org-tab-before-tab-emulation-hook))
7001 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7002 (or (not (bolp))
7003 (not (looking-at org-outline-regexp))))
7004 (call-interactively (global-key-binding "\t")))
7006 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7007 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7008 (or (and (eq org-cycle-emulate-tab 'white)
7009 (= (match-end 0) (point-at-eol)))
7010 (and (eq org-cycle-emulate-tab 'whitestart)
7011 (>= (match-end 0) pos))))
7013 (eq org-cycle-emulate-tab t))
7014 (call-interactively (global-key-binding "\t")))
7016 (t (save-excursion
7017 (org-back-to-heading)
7018 (org-cycle)))))))
7020 (defun org-cycle-internal-global ()
7021 "Do the global cycling action."
7022 ;; Hack to avoid display of messages for .org attachments in Gnus
7023 (let ((ga (string-match "\\*fontification" (buffer-name))))
7024 (cond
7025 ((and (eq last-command this-command)
7026 (eq org-cycle-global-status 'overview))
7027 ;; We just created the overview - now do table of contents
7028 ;; This can be slow in very large buffers, so indicate action
7029 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7030 (unless ga (org-unlogged-message "CONTENTS..."))
7031 (org-content)
7032 (unless ga (org-unlogged-message "CONTENTS...done"))
7033 (setq org-cycle-global-status 'contents)
7034 (run-hook-with-args 'org-cycle-hook 'contents))
7036 ((and (eq last-command this-command)
7037 (eq org-cycle-global-status 'contents))
7038 ;; We just showed the table of contents - now show everything
7039 (run-hook-with-args 'org-pre-cycle-hook 'all)
7040 (org-show-all '(headings blocks))
7041 (unless ga (org-unlogged-message "SHOW ALL"))
7042 (setq org-cycle-global-status 'all)
7043 (run-hook-with-args 'org-cycle-hook 'all))
7046 ;; Default action: go to overview
7047 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7048 (org-overview)
7049 (unless ga (org-unlogged-message "OVERVIEW"))
7050 (setq org-cycle-global-status 'overview)
7051 (run-hook-with-args 'org-cycle-hook 'overview)))))
7053 (defvar org-called-with-limited-levels nil
7054 "Non-nil when `org-with-limited-levels' is currently active.")
7056 (defun org-cycle-internal-local ()
7057 "Do the local cycling action."
7058 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7059 ;; First, determine end of headline (EOH), end of subtree or item
7060 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7061 (save-excursion
7062 (if (org-at-item-p)
7063 (progn
7064 (beginning-of-line)
7065 (setq struct (org-list-struct))
7066 (setq eoh (point-at-eol))
7067 (setq eos (org-list-get-item-end-before-blank (point) struct))
7068 (setq has-children (org-list-has-child-p (point) struct)))
7069 (org-back-to-heading)
7070 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7071 (setq eos (save-excursion (org-end-of-subtree t t)
7072 (when (bolp) (backward-char)) (point)))
7073 (setq has-children
7074 (or (save-excursion
7075 (let ((level (funcall outline-level)))
7076 (outline-next-heading)
7077 (and (org-at-heading-p t)
7078 (> (funcall outline-level) level))))
7079 (save-excursion
7080 (org-list-search-forward (org-item-beginning-re) eos t)))))
7081 ;; Determine end invisible part of buffer (EOL)
7082 (beginning-of-line 2)
7083 (while (and (not (eobp)) ;This is like `next-line'.
7084 (get-char-property (1- (point)) 'invisible))
7085 (goto-char (next-single-char-property-change (point) 'invisible))
7086 (and (eolp) (beginning-of-line 2)))
7087 (setq eol (point)))
7088 ;; Find out what to do next and set `this-command'
7089 (cond
7090 ((= eos eoh)
7091 ;; Nothing is hidden behind this heading
7092 (unless (org-before-first-heading-p)
7093 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7094 (org-unlogged-message "EMPTY ENTRY")
7095 (setq org-cycle-subtree-status nil)
7096 (save-excursion
7097 (goto-char eos)
7098 (outline-next-heading)
7099 (when (org-invisible-p) (org-flag-heading nil))))
7100 ((and (or (>= eol eos)
7101 (not (string-match "\\S-" (buffer-substring eol eos))))
7102 (or has-children
7103 (not (setq children-skipped
7104 org-cycle-skip-children-state-if-no-children))))
7105 ;; Entire subtree is hidden in one line: children view
7106 (unless (org-before-first-heading-p)
7107 (run-hook-with-args 'org-pre-cycle-hook 'children))
7108 (if (org-at-item-p)
7109 (org-list-set-item-visibility (point-at-bol) struct 'children)
7110 (org-show-entry)
7111 (org-with-limited-levels (org-show-children))
7112 (org-show-set-visibility 'canonical)
7113 ;; Fold every list in subtree to top-level items.
7114 (when (eq org-cycle-include-plain-lists 'integrate)
7115 (save-excursion
7116 (org-back-to-heading)
7117 (while (org-list-search-forward (org-item-beginning-re) eos t)
7118 (beginning-of-line 1)
7119 (let* ((struct (org-list-struct))
7120 (prevs (org-list-prevs-alist struct))
7121 (end (org-list-get-bottom-point struct)))
7122 (dolist (e (org-list-get-all-items (point) struct prevs))
7123 (org-list-set-item-visibility e struct 'folded))
7124 (goto-char (if (< end eos) end eos)))))))
7125 (org-unlogged-message "CHILDREN")
7126 (save-excursion
7127 (goto-char eos)
7128 (outline-next-heading)
7129 (when (org-invisible-p) (org-flag-heading nil)))
7130 (setq org-cycle-subtree-status 'children)
7131 (unless (org-before-first-heading-p)
7132 (run-hook-with-args 'org-cycle-hook 'children)))
7133 ((or children-skipped
7134 (and (eq last-command this-command)
7135 (eq org-cycle-subtree-status 'children)))
7136 ;; We just showed the children, or no children are there,
7137 ;; now show everything.
7138 (unless (org-before-first-heading-p)
7139 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7140 (org-flag-region eoh eos nil 'outline)
7141 (org-unlogged-message
7142 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7143 (setq org-cycle-subtree-status 'subtree)
7144 (unless (org-before-first-heading-p)
7145 (run-hook-with-args 'org-cycle-hook 'subtree)))
7147 ;; Default action: hide the subtree.
7148 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7149 (org-flag-region eoh eos t 'outline)
7150 (org-unlogged-message "FOLDED")
7151 (setq org-cycle-subtree-status 'folded)
7152 (unless (org-before-first-heading-p)
7153 (run-hook-with-args 'org-cycle-hook 'folded))))))
7155 ;;;###autoload
7156 (defun org-global-cycle (&optional arg)
7157 "Cycle the global visibility. For details see `org-cycle'.
7158 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7159 With a numeric prefix, show all headlines up to that level."
7160 (interactive "P")
7161 (let ((org-cycle-include-plain-lists
7162 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7163 (cond
7164 ((integerp arg)
7165 (org-show-all '(headings blocks))
7166 (outline-hide-sublevels arg)
7167 (setq org-cycle-global-status 'contents))
7168 ((equal arg '(4))
7169 (org-set-startup-visibility)
7170 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7172 (org-cycle '(4))))))
7174 (defun org-set-startup-visibility ()
7175 "Set the visibility required by startup options and properties."
7176 (cond
7177 ((eq org-startup-folded t)
7178 (org-overview))
7179 ((eq org-startup-folded 'content)
7180 (org-content))
7181 ((or (eq org-startup-folded 'showeverything)
7182 (eq org-startup-folded nil))
7183 (org-show-all)))
7184 (unless (eq org-startup-folded 'showeverything)
7185 (when org-hide-block-startup (org-hide-block-all))
7186 (org-set-visibility-according-to-property)
7187 (org-cycle-hide-archived-subtrees 'all)
7188 (org-cycle-hide-drawers 'all)
7189 (org-cycle-show-empty-lines t)))
7191 (defun org-set-visibility-according-to-property ()
7192 "Switch subtree visibilities according to :VISIBILITY: property."
7193 (interactive)
7194 (org-with-wide-buffer
7195 (goto-char (point-min))
7196 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7197 (if (not (org-at-property-p)) (outline-next-heading)
7198 (let ((state (match-string 3)))
7199 (save-excursion
7200 (org-back-to-heading t)
7201 (outline-hide-subtree)
7202 (org-reveal)
7203 (cond
7204 ((equal state "folded")
7205 (outline-hide-subtree))
7206 ((equal state "children")
7207 (org-show-hidden-entry)
7208 (org-show-children))
7209 ((equal state "content")
7210 (save-excursion
7211 (save-restriction
7212 (org-narrow-to-subtree)
7213 (org-content))))
7214 ((member state '("all" "showall"))
7215 (outline-show-subtree)))))))))
7217 (defun org-overview ()
7218 "Switch to overview mode, showing only top-level headlines.
7219 This shows all headlines with a level equal or greater than the level
7220 of the first headline in the buffer. This is important, because if the
7221 first headline is not level one, then (hide-sublevels 1) gives confusing
7222 results."
7223 (interactive)
7224 (save-excursion
7225 (let ((level
7226 (save-excursion
7227 (goto-char (point-min))
7228 (when (re-search-forward org-outline-regexp-bol nil t)
7229 (goto-char (match-beginning 0))
7230 (funcall outline-level)))))
7231 (and level (outline-hide-sublevels level)))))
7233 (defun org-content (&optional arg)
7234 "Show all headlines in the buffer, like a table of contents.
7235 With numerical argument N, show content up to level N."
7236 (interactive "P")
7237 (org-overview)
7238 (save-excursion
7239 ;; Visit all headings and show their offspring
7240 (and (integerp arg) (org-overview))
7241 (goto-char (point-max))
7242 (catch 'exit
7243 (while (and (progn (condition-case nil
7244 (outline-previous-visible-heading 1)
7245 (error (goto-char (point-min))))
7247 (looking-at org-outline-regexp))
7248 (if (integerp arg)
7249 (org-show-children (1- arg))
7250 (outline-show-branches))
7251 (when (bobp) (throw 'exit nil))))))
7253 (defun org-optimize-window-after-visibility-change (state)
7254 "Adjust the window after a change in outline visibility.
7255 This function is the default value of the hook `org-cycle-hook'."
7256 (when (get-buffer-window (current-buffer))
7257 (cond
7258 ((eq state 'content) nil)
7259 ((eq state 'all) nil)
7260 ((eq state 'folded) nil)
7261 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7262 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7264 (defun org-clean-visibility-after-subtree-move ()
7265 "Fix visibility issues after moving a subtree."
7266 ;; First, find a reasonable region to look at:
7267 ;; Start two siblings above, end three below
7268 (let* ((beg (save-excursion
7269 (and (org-get-last-sibling)
7270 (org-get-last-sibling))
7271 (point)))
7272 (end (save-excursion
7273 (and (org-get-next-sibling)
7274 (org-get-next-sibling)
7275 (org-get-next-sibling))
7276 (if (org-at-heading-p)
7277 (point-at-eol)
7278 (point))))
7279 (level (looking-at "\\*+"))
7280 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7281 (save-excursion
7282 (save-restriction
7283 (narrow-to-region beg end)
7284 (when re
7285 ;; Properly fold already folded siblings
7286 (goto-char (point-min))
7287 (while (re-search-forward re nil t)
7288 (when (and (not (org-invisible-p))
7289 (org-invisible-p (line-end-position)))
7290 (outline-hide-entry))))
7291 (org-cycle-hide-drawers 'all)
7292 (org-cycle-show-empty-lines 'overview)))))
7294 (defun org-cycle-show-empty-lines (state)
7295 "Show empty lines above all visible headlines.
7296 The region to be covered depends on STATE when called through
7297 `org-cycle-hook'. Lisp program can use t for STATE to get the
7298 entire buffer covered. Note that an empty line is only shown if there
7299 are at least `org-cycle-separator-lines' empty lines before the headline."
7300 (when (/= org-cycle-separator-lines 0)
7301 (save-excursion
7302 (let* ((n (abs org-cycle-separator-lines))
7303 (re (cond
7304 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7305 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7306 (t (let ((ns (number-to-string (- n 2))))
7307 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7308 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7309 beg end)
7310 (cond
7311 ((memq state '(overview contents t))
7312 (setq beg (point-min) end (point-max)))
7313 ((memq state '(children folded))
7314 (setq beg (point)
7315 end (progn (org-end-of-subtree t t)
7316 (line-beginning-position 2)))))
7317 (when beg
7318 (goto-char beg)
7319 (while (re-search-forward re end t)
7320 (unless (get-char-property (match-end 1) 'invisible)
7321 (let ((e (match-end 1))
7322 (b (if (>= org-cycle-separator-lines 0)
7323 (match-beginning 1)
7324 (save-excursion
7325 (goto-char (match-beginning 0))
7326 (skip-chars-backward " \t\n")
7327 (line-end-position)))))
7328 (org-flag-region b e nil 'outline))))))))
7329 ;; Never hide empty lines at the end of the file.
7330 (save-excursion
7331 (goto-char (point-max))
7332 (outline-previous-heading)
7333 (outline-end-of-heading)
7334 (when (and (looking-at "[ \t\n]+")
7335 (= (match-end 0) (point-max)))
7336 (org-flag-region (point) (match-end 0) nil 'outline))))
7338 ;;;; Reveal point location
7340 (defun org-show-context (&optional key)
7341 "Make sure point and context are visible.
7342 Optional argument KEY, when non-nil, is a symbol. See
7343 `org-show-context-detail' for allowed values and how much is to
7344 be shown."
7345 (org-show-set-visibility
7346 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7347 ((cdr (assq key org-show-context-detail)))
7348 (t (cdr (assq 'default org-show-context-detail))))))
7350 (defun org-show-set-visibility (detail)
7351 "Set visibility around point according to DETAIL.
7352 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7353 `tree', `canonical' or t. See `org-show-context-detail' for more
7354 information."
7355 ;; Show current heading and possibly its entry, following headline
7356 ;; or all children.
7357 (if (and (org-at-heading-p) (not (eq detail 'local)))
7358 (org-flag-heading nil)
7359 (org-show-entry)
7360 ;; If point is hidden within a drawer or a block, make sure to
7361 ;; expose it.
7362 (dolist (o (overlays-at (point)))
7363 (when (memq (overlay-get o 'invisible)
7364 '(org-hide-block org-hide-drawer outline))
7365 (delete-overlay o)))
7366 (unless (org-before-first-heading-p)
7367 (org-with-limited-levels
7368 (cl-case detail
7369 ((tree canonical t) (org-show-children))
7370 ((nil minimal ancestors))
7371 (t (save-excursion
7372 (outline-next-heading)
7373 (org-flag-heading nil)))))))
7374 ;; Show all siblings.
7375 (when (eq detail 'lineage) (org-show-siblings))
7376 ;; Show ancestors, possibly with their children.
7377 (when (memq detail '(ancestors lineage tree canonical t))
7378 (save-excursion
7379 (while (org-up-heading-safe)
7380 (org-flag-heading nil)
7381 (when (memq detail '(canonical t)) (org-show-entry))
7382 (when (memq detail '(tree canonical t)) (org-show-children))))))
7384 (defvar org-reveal-start-hook nil
7385 "Hook run before revealing a location.")
7387 (defun org-reveal (&optional siblings)
7388 "Show current entry, hierarchy above it, and the following headline.
7390 This can be used to show a consistent set of context around
7391 locations exposed with `org-show-context'.
7393 With optional argument SIBLINGS, on each level of the hierarchy all
7394 siblings are shown. This repairs the tree structure to what it would
7395 look like when opened with hierarchical calls to `org-cycle'.
7397 With a \\[universal-argument] \\[universal-argument] prefix, \
7398 go to the parent and show the entire tree."
7399 (interactive "P")
7400 (run-hooks 'org-reveal-start-hook)
7401 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7402 ((equal siblings '(16))
7403 (save-excursion
7404 (when (org-up-heading-safe)
7405 (org-show-subtree)
7406 (run-hook-with-args 'org-cycle-hook 'subtree))))
7407 (t (org-show-set-visibility 'lineage))))
7410 ;;; Indirect buffer display of subtrees
7412 (defvar org-indirect-dedicated-frame nil
7413 "This is the frame being used for indirect tree display.")
7414 (defvar org-last-indirect-buffer nil)
7416 (defun org-tree-to-indirect-buffer (&optional arg)
7417 "Create indirect buffer and narrow it to current subtree.
7419 With a numerical prefix ARG, go up to this level and then take that tree.
7420 If ARG is negative, go up that many levels.
7422 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7423 indirect buffer previously made with this command, to avoid proliferation of
7424 indirect buffers. However, when you call the command with a \
7425 `\\[universal-argument]' prefix, or
7426 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7427 so that you can work with several indirect buffers at the same time. If
7428 `org-indirect-buffer-display' is `dedicated-frame', the \
7429 `\\[universal-argument]' prefix also
7430 requests that a new frame be made for the new buffer, so that the dedicated
7431 frame is not changed."
7432 (interactive "P")
7433 (let ((cbuf (current-buffer))
7434 (cwin (selected-window))
7435 (pos (point))
7436 beg end level heading ibuf)
7437 (save-excursion
7438 (org-back-to-heading t)
7439 (when (numberp arg)
7440 (setq level (org-outline-level))
7441 (when (< arg 0) (setq arg (+ level arg)))
7442 (while (> (setq level (org-outline-level)) arg)
7443 (org-up-heading-safe)))
7444 (setq beg (point)
7445 heading (org-get-heading 'no-tags))
7446 (org-end-of-subtree t t)
7447 (when (org-at-heading-p) (backward-char 1))
7448 (setq end (point)))
7449 (when (and (buffer-live-p org-last-indirect-buffer)
7450 (not (eq org-indirect-buffer-display 'new-frame))
7451 (not arg))
7452 (kill-buffer org-last-indirect-buffer))
7453 (setq ibuf (org-get-indirect-buffer cbuf heading)
7454 org-last-indirect-buffer ibuf)
7455 (cond
7456 ((or (eq org-indirect-buffer-display 'new-frame)
7457 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7458 (select-frame (make-frame))
7459 (delete-other-windows)
7460 (pop-to-buffer-same-window ibuf)
7461 (org-set-frame-title heading))
7462 ((eq org-indirect-buffer-display 'dedicated-frame)
7463 (raise-frame
7464 (select-frame (or (and org-indirect-dedicated-frame
7465 (frame-live-p org-indirect-dedicated-frame)
7466 org-indirect-dedicated-frame)
7467 (setq org-indirect-dedicated-frame (make-frame)))))
7468 (delete-other-windows)
7469 (pop-to-buffer-same-window ibuf)
7470 (org-set-frame-title (concat "Indirect: " heading)))
7471 ((eq org-indirect-buffer-display 'current-window)
7472 (pop-to-buffer-same-window ibuf))
7473 ((eq org-indirect-buffer-display 'other-window)
7474 (pop-to-buffer ibuf))
7475 (t (error "Invalid value")))
7476 (narrow-to-region beg end)
7477 (org-show-all '(headings blocks))
7478 (goto-char pos)
7479 (run-hook-with-args 'org-cycle-hook 'all)
7480 (and (window-live-p cwin) (select-window cwin))))
7482 (defun org-get-indirect-buffer (&optional buffer heading)
7483 (setq buffer (or buffer (current-buffer)))
7484 (let ((n 1) (base (buffer-name buffer)) bname)
7485 (while (buffer-live-p
7486 (get-buffer
7487 (setq bname
7488 (concat base "-"
7489 (if heading (concat heading "-" (number-to-string n))
7490 (number-to-string n))))))
7491 (setq n (1+ n)))
7492 (condition-case nil
7493 (make-indirect-buffer buffer bname 'clone)
7494 (error (make-indirect-buffer buffer bname)))))
7496 (defun org-set-frame-title (title)
7497 "Set the title of the current frame to the string TITLE."
7498 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7500 ;;;; Structure editing
7502 ;;; Inserting headlines
7504 (defun org--line-empty-p (n)
7505 "Is the Nth next line empty?
7507 Counts the current line as N = 1 and the previous line as N = 0;
7508 see `beginning-of-line'."
7509 (save-excursion
7510 (and (not (bobp))
7511 (or (beginning-of-line n) t)
7512 (save-match-data
7513 (looking-at "[ \t]*$")))))
7515 (defun org-previous-line-empty-p ()
7516 "Is the previous line a blank line?
7517 When NEXT is non-nil, check the next line instead."
7518 (org--line-empty-p 0))
7520 (defun org-next-line-empty-p ()
7521 "Is the previous line a blank line?
7522 When NEXT is non-nil, check the next line instead."
7523 (org--line-empty-p 2))
7525 (defun org--blank-before-heading-p (&optional parent)
7526 "Non-nil when an empty line should precede a new heading here.
7527 When optional argument PARENT is non-nil, consider parent
7528 headline instead of current one."
7529 (pcase (assq 'heading org-blank-before-new-entry)
7530 (`(heading . auto)
7531 (save-excursion
7532 (org-with-limited-levels
7533 (unless (and (org-before-first-heading-p)
7534 (not (outline-next-heading)))
7535 (org-back-to-heading t)
7536 (when parent (org-up-heading-safe))
7537 (cond ((not (bobp))
7538 (org-previous-line-empty-p))
7539 ((outline-next-heading)
7540 (org-previous-line-empty-p))
7541 ;; Ignore trailing spaces on last buffer line.
7542 ((progn (skip-chars-backward " \t") (bolp))
7543 (org-previous-line-empty-p))
7544 (t nil))))))
7545 (`(heading . ,value) value)
7546 (_ nil)))
7548 (defun org-insert-heading (&optional arg invisible-ok top)
7549 "Insert a new heading or an item with the same depth at point.
7551 If point is at the beginning of a heading, insert a new heading
7552 or a new headline above the current one. When at the beginning
7553 of a regular line of text, turn it into a heading.
7555 If point is in the middle of a line, split it and create a new
7556 headline with the text in the current line after point (see
7557 `org-M-RET-may-split-line' on how to modify this behavior). As
7558 a special case, on a headline, splitting can only happen on the
7559 title itself. E.g., this excludes breaking stars or tags.
7561 With a `\\[universal-argument]' prefix, set \
7562 `org-insert-heading-respect-content' to
7563 a non-nil value for the duration of the command. This forces the
7564 insertion of a heading after the current subtree, independently
7565 on the location of point.
7567 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7568 insert the heading at the end of the tree
7569 above the current heading. For example, if point is within a
7570 2nd-level heading, then it will insert a 2nd-level heading at
7571 the end of the 1st-level parent subtree.
7573 When INVISIBLE-OK is set, stop at invisible headlines when going
7574 back. This is important for non-interactive uses of the
7575 command.
7577 When optional argument TOP is non-nil, insert a level 1 heading,
7578 unconditionally."
7579 (interactive "P")
7580 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7581 (level (org-current-level))
7582 (stars (make-string (if (and level (not top)) level 1) ?*)))
7583 (cond
7584 ((or org-insert-heading-respect-content
7585 (member arg '((4) (16)))
7586 (and (not invisible-ok)
7587 (invisible-p (max (1- (point)) (point-min)))))
7588 ;; Position point at the location of insertion.
7589 (if (not level) ;before first headline
7590 (org-with-limited-levels (outline-next-heading))
7591 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7592 ;; is nil.
7593 (org-with-limited-levels (org-back-to-heading invisible-ok))
7594 (cond ((equal arg '(16))
7595 (org-up-heading-safe)
7596 (org-end-of-subtree t t))
7598 (org-end-of-subtree t t))))
7599 (unless (bolp) (insert "\n")) ;ensure final newline
7600 (unless (and blank? (org-previous-line-empty-p))
7601 (org-N-empty-lines-before-current (if blank? 1 0)))
7602 (insert stars " \n")
7603 (forward-char -1))
7604 ;; At a headline...
7605 ((org-at-heading-p)
7606 (cond ((bolp)
7607 (when blank? (save-excursion (insert "\n")))
7608 (save-excursion (insert stars " \n"))
7609 (unless (and blank? (org-previous-line-empty-p))
7610 (org-N-empty-lines-before-current (if blank? 1 0)))
7611 (end-of-line))
7612 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7613 (org-match-line org-complex-heading-regexp)
7614 (org-pos-in-match-range (point) 4))
7615 ;; Grab the text that should moved to the new headline.
7616 ;; Preserve tags.
7617 (let ((split (delete-and-extract-region (point) (match-end 4))))
7618 (if (looking-at "[ \t]*$") (replace-match "")
7619 (org-align-tags))
7620 (end-of-line)
7621 (when blank? (insert "\n"))
7622 (insert "\n" stars " ")
7623 (when (org-string-nw-p split) (insert split))
7624 (when (eobp) (save-excursion (insert "\n")))))
7626 (end-of-line)
7627 (when blank? (insert "\n"))
7628 (insert "\n" stars " ")
7629 (when (eobp) (save-excursion (insert "\n"))))))
7630 ;; On regular text, turn line into a headline or split, if
7631 ;; appropriate.
7632 ((bolp)
7633 (insert stars " ")
7634 (unless (and blank? (org-previous-line-empty-p))
7635 (org-N-empty-lines-before-current (if blank? 1 0))))
7637 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7638 (end-of-line))
7639 (insert "\n" stars " ")
7640 (unless (and blank? (org-previous-line-empty-p))
7641 (org-N-empty-lines-before-current (if blank? 1 0))))))
7642 (run-hooks 'org-insert-heading-hook))
7644 (defun org-N-empty-lines-before-current (n)
7645 "Make the number of empty lines before current exactly N.
7646 So this will delete or add empty lines."
7647 (let ((column (current-column)))
7648 (beginning-of-line)
7649 (unless (bobp)
7650 (let ((start (save-excursion
7651 (skip-chars-backward " \r\t\n")
7652 (line-end-position))))
7653 (delete-region start (line-end-position 0))))
7654 (insert (make-string n ?\n))
7655 (move-to-column column)))
7657 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7658 "Return the heading of the current entry, without the stars.
7659 When NO-TAGS is non-nil, don't include tags.
7660 When NO-TODO is non-nil, don't include TODO keywords.
7661 When NO-PRIORITY is non-nil, don't include priority cookie.
7662 When NO-COMMENT is non-nil, don't include COMMENT string."
7663 (save-excursion
7664 (org-back-to-heading t)
7665 (let ((case-fold-search nil))
7666 (looking-at org-complex-heading-regexp)
7667 (let ((todo (and (not no-todo) (match-string 2)))
7668 (priority (and (not no-priority) (match-string 3)))
7669 (headline (pcase (match-string 4)
7670 (`nil "")
7671 ((and (guard no-comment) h)
7672 (replace-regexp-in-string
7673 (eval-when-compile
7674 (format "\\`%s[ \t]+" org-comment-string))
7675 "" h))
7676 (h h)))
7677 (tags (and (not no-tags) (match-string 5))))
7678 (mapconcat #'identity
7679 (delq nil (list todo priority headline tags))
7680 " ")))))
7682 (defun org-heading-components ()
7683 "Return the components of the current heading.
7684 This is a list with the following elements:
7685 - the level as an integer
7686 - the reduced level, different if `org-odd-levels-only' is set.
7687 - the TODO keyword, or nil
7688 - the priority character, like ?A, or nil if no priority is given
7689 - the headline text itself, or the tags string if no headline text
7690 - the tags string, or nil."
7691 (save-excursion
7692 (org-back-to-heading t)
7693 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7694 (list (length (match-string 1))
7695 (org-reduced-level (length (match-string 1)))
7696 (match-string-no-properties 2)
7697 (and (match-end 3) (aref (match-string 3) 2))
7698 (match-string-no-properties 4)
7699 (match-string-no-properties 5)))))
7701 (defun org-get-entry ()
7702 "Get the entry text, after heading, entire subtree."
7703 (save-excursion
7704 (org-back-to-heading t)
7705 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7707 (defun org-edit-headline (&optional heading)
7708 "Edit the current headline.
7709 Set it to HEADING when provided."
7710 (interactive)
7711 (org-with-wide-buffer
7712 (org-back-to-heading t)
7713 (let ((case-fold-search nil))
7714 (when (looking-at org-complex-heading-regexp)
7715 (let* ((old (match-string-no-properties 4))
7716 (new (save-match-data
7717 (org-trim (or heading (read-string "Edit: " old))))))
7718 (unless (equal old new)
7719 (if old (replace-match new t t nil 4)
7720 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7721 (insert " " new))
7722 (org-align-tags)
7723 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7725 (defun org-insert-heading-after-current ()
7726 "Insert a new heading with same level as current, after current subtree."
7727 (interactive)
7728 (org-back-to-heading)
7729 (org-insert-heading)
7730 (org-move-subtree-down)
7731 (end-of-line 1))
7733 (defun org-insert-heading-respect-content (&optional invisible-ok)
7734 "Insert heading with `org-insert-heading-respect-content' set to t."
7735 (interactive)
7736 (org-insert-heading '(4) invisible-ok))
7738 (defun org-insert-todo-heading-respect-content (&optional force-state)
7739 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7740 (interactive)
7741 (org-insert-todo-heading force-state '(4)))
7743 (defun org-insert-todo-heading (arg &optional force-heading)
7744 "Insert a new heading with the same level and TODO state as current heading.
7746 If the heading has no TODO state, or if the state is DONE, use
7747 the first state (TODO by default). Also with one prefix arg,
7748 force first state. With two prefix args, force inserting at the
7749 end of the parent subtree.
7751 When called at a plain list item, insert a new item with an
7752 unchecked check box."
7753 (interactive "P")
7754 (when (or force-heading (not (org-insert-item 'checkbox)))
7755 (org-insert-heading (or (and (equal arg '(16)) '(16))
7756 force-heading))
7757 (save-excursion
7758 (org-forward-heading-same-level -1)
7759 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7760 (let* ((new-mark-x
7761 (if (or (equal arg '(4))
7762 (not (match-beginning 2))
7763 (member (match-string 2) org-done-keywords))
7764 (car org-todo-keywords-1)
7765 (match-string 2)))
7766 (new-mark
7768 (run-hook-with-args-until-success
7769 'org-todo-get-default-hook new-mark-x nil)
7770 new-mark-x)))
7771 (beginning-of-line 1)
7772 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7773 (if org-treat-insert-todo-heading-as-state-change
7774 (org-todo new-mark)
7775 (insert new-mark " "))))
7776 (when org-provide-todo-statistics
7777 (org-update-parent-todo-statistics))))
7779 (defun org-insert-subheading (arg)
7780 "Insert a new subheading and demote it.
7781 Works for outline headings and for plain lists alike."
7782 (interactive "P")
7783 (org-insert-heading arg)
7784 (cond
7785 ((org-at-heading-p) (org-do-demote))
7786 ((org-at-item-p) (org-indent-item))))
7788 (defun org-insert-todo-subheading (arg)
7789 "Insert a new subheading with TODO keyword or checkbox and demote it.
7790 Works for outline headings and for plain lists alike."
7791 (interactive "P")
7792 (org-insert-todo-heading arg)
7793 (cond
7794 ((org-at-heading-p) (org-do-demote))
7795 ((org-at-item-p) (org-indent-item))))
7797 ;;; Promotion and Demotion
7799 (defvar org-after-demote-entry-hook nil
7800 "Hook run after an entry has been demoted.
7801 The cursor will be at the beginning of the entry.
7802 When a subtree is being demoted, the hook will be called for each node.")
7804 (defvar org-after-promote-entry-hook nil
7805 "Hook run after an entry has been promoted.
7806 The cursor will be at the beginning of the entry.
7807 When a subtree is being promoted, the hook will be called for each node.")
7809 (defun org-promote-subtree ()
7810 "Promote the entire subtree.
7811 See also `org-promote'."
7812 (interactive)
7813 (save-excursion
7814 (org-with-limited-levels (org-map-tree 'org-promote)))
7815 (org-fix-position-after-promote))
7817 (defun org-demote-subtree ()
7818 "Demote the entire subtree.
7819 See `org-demote' and `org-promote'."
7820 (interactive)
7821 (save-excursion
7822 (org-with-limited-levels (org-map-tree 'org-demote)))
7823 (org-fix-position-after-promote))
7825 (defun org-do-promote ()
7826 "Promote the current heading higher up the tree.
7827 If the region is active in `transient-mark-mode', promote all
7828 headings in the region."
7829 (interactive)
7830 (save-excursion
7831 (if (org-region-active-p)
7832 (org-map-region 'org-promote (region-beginning) (region-end))
7833 (org-promote)))
7834 (org-fix-position-after-promote))
7836 (defun org-do-demote ()
7837 "Demote the current heading lower down the tree.
7838 If the region is active in `transient-mark-mode', demote all
7839 headings in the region."
7840 (interactive)
7841 (save-excursion
7842 (if (org-region-active-p)
7843 (org-map-region 'org-demote (region-beginning) (region-end))
7844 (org-demote)))
7845 (org-fix-position-after-promote))
7847 (defun org-fix-position-after-promote ()
7848 "Fix cursor position and indentation after demoting/promoting."
7849 (let ((pos (point)))
7850 (when (save-excursion
7851 (beginning-of-line)
7852 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7853 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7854 (cond ((eobp) (insert " "))
7855 ((eolp) (insert " "))
7856 ((equal (char-after) ?\s) (forward-char 1))))))
7858 (defun org-current-level ()
7859 "Return the level of the current entry, or nil if before the first headline.
7860 The level is the number of stars at the beginning of the
7861 headline. Use `org-reduced-level' to remove the effect of
7862 `org-odd-levels'. Unlike to `org-outline-level', this function
7863 ignores inlinetasks."
7864 (let ((level (org-with-limited-levels (org-outline-level))))
7865 (and (> level 0) level)))
7867 (defun org-get-previous-line-level ()
7868 "Return the outline depth of the last headline before the current line.
7869 Returns 0 for the first headline in the buffer, and nil if before the
7870 first headline."
7871 (and (org-current-level)
7872 (or (and (/= (line-beginning-position) (point-min))
7873 (save-excursion (beginning-of-line 0) (org-current-level)))
7874 0)))
7876 (defun org-reduced-level (l)
7877 "Compute the effective level of a heading.
7878 This takes into account the setting of `org-odd-levels-only'."
7879 (cond
7880 ((zerop l) 0)
7881 (org-odd-levels-only (1+ (floor (/ l 2))))
7882 (t l)))
7884 (defun org-level-increment ()
7885 "Return the number of stars that will be added or removed at a
7886 time to headlines when structure editing, based on the value of
7887 `org-odd-levels-only'."
7888 (if org-odd-levels-only 2 1))
7890 (defun org-get-valid-level (level &optional change)
7891 "Rectify a level change under the influence of `org-odd-levels-only'.
7892 LEVEL is a current level, CHANGE is by how much the level should
7893 be modified. Even if CHANGE is nil, LEVEL may be returned
7894 modified because even level numbers will become the next higher
7895 odd number. Returns values greater than 0."
7896 (if org-odd-levels-only
7897 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7898 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7899 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7900 (max 1 (+ level (or change 0)))))
7902 (defun org-promote ()
7903 "Promote the current heading higher up the tree."
7904 (org-with-wide-buffer
7905 (org-back-to-heading t)
7906 (let* ((after-change-functions (remq 'flyspell-after-change-function
7907 after-change-functions))
7908 (level (save-match-data (funcall outline-level)))
7909 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7910 (diff (abs (- level (length up-head) -1))))
7911 (cond
7912 ((and (= level 1) org-allow-promoting-top-level-subtree)
7913 (replace-match "# " nil t))
7914 ((= level 1)
7915 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7916 (t (replace-match up-head nil t)))
7917 (unless (= level 1)
7918 (when org-auto-align-tags (org-align-tags))
7919 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7920 (run-hooks 'org-after-promote-entry-hook))))
7922 (defun org-demote ()
7923 "Demote the current heading lower down the tree."
7924 (org-with-wide-buffer
7925 (org-back-to-heading t)
7926 (let* ((after-change-functions (remq 'flyspell-after-change-function
7927 after-change-functions))
7928 (level (save-match-data (funcall outline-level)))
7929 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7930 (diff (abs (- level (length down-head) -1))))
7931 (replace-match down-head nil t)
7932 (when org-auto-align-tags (org-align-tags))
7933 (when org-adapt-indentation (org-fixup-indentation diff))
7934 (run-hooks 'org-after-demote-entry-hook))))
7936 (defun org-cycle-level ()
7937 "Cycle the level of an empty headline through possible states.
7938 This goes first to child, then to parent, level, then up the hierarchy.
7939 After top level, it switches back to sibling level."
7940 (interactive)
7941 (let ((org-adapt-indentation nil))
7942 (when (org-point-at-end-of-empty-headline)
7943 (setq this-command 'org-cycle-level) ; Only needed for caching
7944 (let ((cur-level (org-current-level))
7945 (prev-level (org-get-previous-line-level)))
7946 (cond
7947 ;; If first headline in file, promote to top-level.
7948 ((= prev-level 0)
7949 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7950 do (org-do-promote)))
7951 ;; If same level as prev, demote one.
7952 ((= prev-level cur-level)
7953 (org-do-demote))
7954 ;; If parent is top-level, promote to top level if not already.
7955 ((= prev-level 1)
7956 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7957 do (org-do-promote)))
7958 ;; If top-level, return to prev-level.
7959 ((= cur-level 1)
7960 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7961 do (org-do-demote)))
7962 ;; If less than prev-level, promote one.
7963 ((< cur-level prev-level)
7964 (org-do-promote))
7965 ;; If deeper than prev-level, promote until higher than
7966 ;; prev-level.
7967 ((> cur-level prev-level)
7968 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7969 do (org-do-promote))))
7970 t))))
7972 (defun org-map-tree (fun)
7973 "Call FUN for every heading underneath the current one."
7974 (org-back-to-heading t)
7975 (let ((level (funcall outline-level)))
7976 (save-excursion
7977 (funcall fun)
7978 (while (and (progn
7979 (outline-next-heading)
7980 (> (funcall outline-level) level))
7981 (not (eobp)))
7982 (funcall fun)))))
7984 (defun org-map-region (fun beg end)
7985 "Call FUN for every heading between BEG and END."
7986 (let ((org-ignore-region t))
7987 (save-excursion
7988 (setq end (copy-marker end))
7989 (goto-char beg)
7990 (when (and (re-search-forward org-outline-regexp-bol nil t)
7991 (< (point) end))
7992 (funcall fun))
7993 (while (and (progn
7994 (outline-next-heading)
7995 (< (point) end))
7996 (not (eobp)))
7997 (funcall fun)))))
7999 (defun org-fixup-indentation (diff)
8000 "Change the indentation in the current entry by DIFF.
8002 DIFF is an integer. Indentation is done according to the
8003 following rules:
8005 - Planning information and property drawers are always indented
8006 according to the new level of the headline;
8008 - Footnote definitions and their contents are ignored;
8010 - Inlinetasks' boundaries are not shifted;
8012 - Empty lines are ignored;
8014 - Other lines' indentation are shifted by DIFF columns, unless
8015 it would introduce a structural change in the document, in
8016 which case no shifting is done at all.
8018 Assume point is at a heading or an inlinetask beginning."
8019 (org-with-wide-buffer
8020 (narrow-to-region (line-beginning-position)
8021 (save-excursion
8022 (if (org-with-limited-levels (org-at-heading-p))
8023 (org-with-limited-levels (outline-next-heading))
8024 (org-inlinetask-goto-end))
8025 (point)))
8026 (forward-line)
8027 ;; Indent properly planning info and property drawer.
8028 (when (looking-at-p org-planning-line-re)
8029 (org-indent-line)
8030 (forward-line))
8031 (when (looking-at org-property-drawer-re)
8032 (goto-char (match-end 0))
8033 (forward-line)
8034 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8035 (catch 'no-shift
8036 (when (zerop diff) (throw 'no-shift nil))
8037 ;; If DIFF is negative, first check if a shift is possible at all
8038 ;; (e.g., it doesn't break structure). This can only happen if
8039 ;; some contents are not properly indented.
8040 (let ((case-fold-search t))
8041 (when (< diff 0)
8042 (let ((diff (- diff))
8043 (forbidden-re (concat org-outline-regexp
8044 "\\|"
8045 (substring org-footnote-definition-re 1))))
8046 (save-excursion
8047 (while (not (eobp))
8048 (cond
8049 ((looking-at-p "[ \t]*$") (forward-line))
8050 ((and (looking-at-p org-footnote-definition-re)
8051 (let ((e (org-element-at-point)))
8052 (and (eq (org-element-type e) 'footnote-definition)
8053 (goto-char (org-element-property :end e))))))
8054 ((looking-at-p org-outline-regexp) (forward-line))
8055 ;; Give up if shifting would move before column 0 or
8056 ;; if it would introduce a headline or a footnote
8057 ;; definition.
8059 (skip-chars-forward " \t")
8060 (let ((ind (current-column)))
8061 (when (or (< ind diff)
8062 (and (= ind diff) (looking-at-p forbidden-re)))
8063 (throw 'no-shift nil)))
8064 ;; Ignore contents of example blocks and source
8065 ;; blocks if their indentation is meant to be
8066 ;; preserved. Jump to block's closing line.
8067 (beginning-of-line)
8068 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8069 (let ((e (org-element-at-point)))
8070 (and (memq (org-element-type e)
8071 '(example-block src-block))
8072 (or org-src-preserve-indentation
8073 (org-element-property :preserve-indent e))
8074 (goto-char (org-element-property :end e))
8075 (progn (skip-chars-backward " \r\t\n")
8076 (beginning-of-line)
8077 t))))
8078 (forward-line))))))))
8079 ;; Shift lines but footnote definitions, inlinetasks boundaries
8080 ;; by DIFF. Also skip contents of source or example blocks
8081 ;; when indentation is meant to be preserved.
8082 (while (not (eobp))
8083 (cond
8084 ((and (looking-at-p org-footnote-definition-re)
8085 (let ((e (org-element-at-point)))
8086 (and (eq (org-element-type e) 'footnote-definition)
8087 (goto-char (org-element-property :end e))))))
8088 ((looking-at-p org-outline-regexp) (forward-line))
8089 ((looking-at-p "[ \t]*$") (forward-line))
8091 (indent-line-to (+ (org-get-indentation) diff))
8092 (beginning-of-line)
8093 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8094 (let ((e (org-element-at-point)))
8095 (and (memq (org-element-type e)
8096 '(example-block src-block))
8097 (or org-src-preserve-indentation
8098 (org-element-property :preserve-indent e))
8099 (goto-char (org-element-property :end e))
8100 (progn (skip-chars-backward " \r\t\n")
8101 (beginning-of-line)
8102 t))))
8103 (forward-line)))))))))
8105 (defun org-convert-to-odd-levels ()
8106 "Convert an Org file with all levels allowed to one with odd levels.
8107 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8108 level 5 etc."
8109 (interactive)
8110 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8111 (let ((outline-level 'org-outline-level)
8112 (org-odd-levels-only nil) n)
8113 (save-excursion
8114 (goto-char (point-min))
8115 (while (re-search-forward "^\\*\\*+ " nil t)
8116 (setq n (- (length (match-string 0)) 2))
8117 (while (>= (setq n (1- n)) 0)
8118 (org-demote))
8119 (end-of-line 1))))))
8121 (defun org-convert-to-oddeven-levels ()
8122 "Convert an Org file with only odd levels to one with odd/even levels.
8123 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8124 file contains a section with an even level, conversion would
8125 destroy the structure of the file. An error is signaled in this
8126 case."
8127 (interactive)
8128 (goto-char (point-min))
8129 ;; First check if there are no even levels
8130 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8131 (org-show-set-visibility 'canonical)
8132 (error "Not all levels are odd in this file. Conversion not possible"))
8133 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8134 (let ((outline-regexp org-outline-regexp)
8135 (outline-level 'org-outline-level)
8136 (org-odd-levels-only nil) n)
8137 (save-excursion
8138 (goto-char (point-min))
8139 (while (re-search-forward "^\\*\\*+ " nil t)
8140 (setq n (/ (1- (length (match-string 0))) 2))
8141 (while (>= (setq n (1- n)) 0)
8142 (org-promote))
8143 (end-of-line 1))))))
8145 (defun org-tr-level (n)
8146 "Make N odd if required."
8147 (if org-odd-levels-only (1+ (/ n 2)) n))
8149 ;;; Vertical tree motion, cutting and pasting of subtrees
8151 (defun org-move-subtree-up (&optional arg)
8152 "Move the current subtree up past ARG headlines of the same level."
8153 (interactive "p")
8154 (org-move-subtree-down (- (prefix-numeric-value arg))))
8156 (defun org-move-subtree-down (&optional arg)
8157 "Move the current subtree down past ARG headlines of the same level."
8158 (interactive "p")
8159 (setq arg (prefix-numeric-value arg))
8160 (org-preserve-local-variables
8161 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8162 'org-get-last-sibling))
8163 (ins-point (make-marker))
8164 (cnt (abs arg))
8165 (col (current-column))
8166 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8167 ;; Select the tree
8168 (org-back-to-heading)
8169 (setq beg0 (point))
8170 (save-excursion
8171 (setq ne-beg (org-back-over-empty-lines))
8172 (setq beg (point)))
8173 (save-match-data
8174 (save-excursion (outline-end-of-heading)
8175 (setq folded (org-invisible-p)))
8176 (progn (org-end-of-subtree nil t)
8177 (unless (eobp) (backward-char))))
8178 (outline-next-heading)
8179 (setq ne-end (org-back-over-empty-lines))
8180 (setq end (point))
8181 (goto-char beg0)
8182 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8183 ;; include less whitespace
8184 (save-excursion
8185 (goto-char beg)
8186 (forward-line (- ne-beg ne-end))
8187 (setq beg (point))))
8188 ;; Find insertion point, with error handling
8189 (while (> cnt 0)
8190 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8191 (goto-char beg0)
8192 (user-error "Cannot move past superior level or buffer limit"))
8193 (setq cnt (1- cnt)))
8194 (when (> arg 0)
8195 ;; Moving forward - still need to move over subtree
8196 (org-end-of-subtree t t)
8197 (save-excursion
8198 (org-back-over-empty-lines)
8199 (or (bolp) (newline))))
8200 (setq ne-ins (org-back-over-empty-lines))
8201 (move-marker ins-point (point))
8202 (setq txt (buffer-substring beg end))
8203 (org-save-markers-in-region beg end)
8204 (delete-region beg end)
8205 (org-remove-empty-overlays-at beg)
8206 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8207 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8208 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8209 (let ((bbb (point)))
8210 (insert-before-markers txt)
8211 (org-reinstall-markers-in-region bbb)
8212 (move-marker ins-point bbb))
8213 (or (bolp) (insert "\n"))
8214 (setq ins-end (point))
8215 (goto-char ins-point)
8216 (org-skip-whitespace)
8217 (when (and (< arg 0)
8218 (org-first-sibling-p)
8219 (> ne-ins ne-beg))
8220 ;; Move whitespace back to beginning
8221 (save-excursion
8222 (goto-char ins-end)
8223 (let ((kill-whole-line t))
8224 (kill-line (- ne-ins ne-beg)) (point)))
8225 (insert (make-string (- ne-ins ne-beg) ?\n)))
8226 (move-marker ins-point nil)
8227 (if folded
8228 (outline-hide-subtree)
8229 (org-show-entry)
8230 (org-show-children))
8231 (org-clean-visibility-after-subtree-move)
8232 ;; move back to the initial column we were at
8233 (move-to-column col))))
8235 (defvar org-subtree-clip ""
8236 "Clipboard for cut and paste of subtrees.
8237 This is actually only a copy of the kill, because we use the normal kill
8238 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8240 (defvar org-subtree-clip-folded nil
8241 "Was the last copied subtree folded?
8242 This is used to fold the tree back after pasting.")
8244 (defun org-cut-subtree (&optional n)
8245 "Cut the current subtree into the clipboard.
8246 With prefix arg N, cut this many sequential subtrees.
8247 This is a short-hand for marking the subtree and then cutting it."
8248 (interactive "p")
8249 (org-copy-subtree n 'cut))
8251 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8252 "Copy the current subtree into the clipboard.
8253 With prefix arg N, copy this many sequential subtrees.
8254 This is a short-hand for marking the subtree and then copying it.
8255 If CUT is non-nil, actually cut the subtree.
8256 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8257 of some markers in the region, even if CUT is non-nil. This is
8258 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8259 (interactive "p")
8260 (org-preserve-local-variables
8261 (let (beg end folded (beg0 (point)))
8262 (if (called-interactively-p 'any)
8263 (org-back-to-heading nil) ; take what looks like a subtree
8264 (org-back-to-heading t)) ; take what is really there
8265 (setq beg (point))
8266 (skip-chars-forward " \t\r\n")
8267 (save-match-data
8268 (if nosubtrees
8269 (outline-next-heading)
8270 (save-excursion (outline-end-of-heading)
8271 (setq folded (org-invisible-p)))
8272 (ignore-errors (org-forward-heading-same-level (1- n) t))
8273 (org-end-of-subtree t t)))
8274 ;; Include the end of an inlinetask
8275 (when (and (featurep 'org-inlinetask)
8276 (looking-at-p (concat (org-inlinetask-outline-regexp)
8277 "END[ \t]*$")))
8278 (end-of-line))
8279 (setq end (point))
8280 (goto-char beg0)
8281 (when (> end beg)
8282 (setq org-subtree-clip-folded folded)
8283 (when (or cut force-store-markers)
8284 (org-save-markers-in-region beg end))
8285 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8286 (setq org-subtree-clip (current-kill 0))
8287 (message "%s: Subtree(s) with %d characters"
8288 (if cut "Cut" "Copied")
8289 (length org-subtree-clip))))))
8291 (defun org-paste-subtree (&optional level tree for-yank remove)
8292 "Paste the clipboard as a subtree, with modification of headline level.
8294 The entire subtree is promoted or demoted in order to match a new headline
8295 level.
8297 If the cursor is at the beginning of a headline, the same level as
8298 that headline is used to paste the tree.
8300 If not, the new level is derived from the *visible* headings
8301 before and after the insertion point, and taken to be the inferior headline
8302 level of the two. So if the previous visible heading is level 3 and the
8303 next is level 4 (or vice versa), level 4 will be used for insertion.
8304 This makes sure that the subtree remains an independent subtree and does
8305 not swallow low level entries.
8307 You can also force a different level, either by using a numeric prefix
8308 argument, or by inserting the heading marker by hand. For example, if the
8309 cursor is after \"*****\", then the tree will be shifted to level 5.
8311 If optional TREE is given, use this text instead of the kill ring.
8313 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8314 move back over whitespace before inserting, and move point to the end of
8315 the inserted text when done.
8317 When REMOVE is non-nil, remove the subtree from the clipboard."
8318 (interactive "P")
8319 (setq tree (or tree (and kill-ring (current-kill 0))))
8320 (unless (org-kill-is-subtree-p tree)
8321 (user-error
8322 (substitute-command-keys
8323 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8324 (org-with-limited-levels
8325 (let* ((visp (not (org-invisible-p)))
8326 (txt tree)
8327 (old-level (if (string-match org-outline-regexp-bol txt)
8328 (- (match-end 0) (match-beginning 0) 1)
8329 -1))
8330 (force-level
8331 (cond
8332 (level (prefix-numeric-value level))
8333 ;; When point is right after the stars in an otherwise
8334 ;; empty headline, use stars as the forced level.
8335 ((and (looking-at-p "[ \t]*$")
8336 (string-match-p "^\\*+ *"
8337 (buffer-substring (line-beginning-position)
8338 (point))))
8339 (org-outline-level))
8340 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8341 (previous-level
8342 (save-excursion
8343 (org-previous-visible-heading 1)
8344 (if (org-at-heading-p) (org-outline-level) 1)))
8345 (next-level
8346 (save-excursion
8347 (if (org-at-heading-p) (org-outline-level)
8348 (org-next-visible-heading 1)
8349 (if (org-at-heading-p) (org-outline-level) 1))))
8350 (new-level (or force-level (max previous-level next-level)))
8351 (shift (if (or (= old-level -1)
8352 (= new-level -1)
8353 (= old-level new-level))
8355 (- new-level old-level)))
8356 (delta (if (> shift 0) -1 1))
8357 (func (if (> shift 0) #'org-demote #'org-promote))
8358 (org-odd-levels-only nil)
8359 beg end newend)
8360 ;; Remove the forced level indicator.
8361 (when (and force-level (not level))
8362 (delete-region (line-beginning-position) (point)))
8363 ;; Paste before the next visible heading or at end of buffer,
8364 ;; unless point is at the beginning of a headline.
8365 (unless (and (bolp) (org-at-heading-p))
8366 (org-next-visible-heading 1)
8367 (unless (bolp) (insert "\n")))
8368 (setq beg (point))
8369 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8370 (insert-before-markers txt)
8371 (unless (string-suffix-p "\n" txt) (insert "\n"))
8372 (setq newend (point))
8373 (org-reinstall-markers-in-region beg)
8374 (setq end (point))
8375 (goto-char beg)
8376 (skip-chars-forward " \t\n\r")
8377 (setq beg (point))
8378 (when (and (org-invisible-p) visp)
8379 (save-excursion (outline-show-heading)))
8380 ;; Shift if necessary.
8381 (unless (= shift 0)
8382 (save-restriction
8383 (narrow-to-region beg end)
8384 (while (not (= shift 0))
8385 (org-map-region func (point-min) (point-max))
8386 (setq shift (+ delta shift)))
8387 (goto-char (point-min))
8388 (setq newend (point-max))))
8389 (when (or for-yank (called-interactively-p 'interactive))
8390 (message "Clipboard pasted as level %d subtree" new-level))
8391 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8392 kill-ring
8393 (equal org-subtree-clip (current-kill 0))
8394 org-subtree-clip-folded)
8395 ;; The tree was folded before it was killed/copied
8396 (outline-hide-subtree))
8397 (when for-yank (goto-char newend))
8398 (when remove (pop kill-ring)))))
8400 (defun org-kill-is-subtree-p (&optional txt)
8401 "Check if the current kill is an outline subtree, or a set of trees.
8402 Returns nil if kill does not start with a headline, or if the first
8403 headline level is not the largest headline level in the tree.
8404 So this will actually accept several entries of equal levels as well,
8405 which is OK for `org-paste-subtree'.
8406 If optional TXT is given, check this string instead of the current kill."
8407 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8408 (re (org-get-limited-outline-regexp))
8409 (^re (concat "^" re))
8410 (start-level (and kill
8411 (string-match
8412 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8413 kill)
8414 (- (match-end 2) (match-beginning 2) 1)))
8415 (start (1+ (or (match-beginning 2) -1))))
8416 (if (not start-level)
8417 (progn
8418 nil) ;; does not even start with a heading
8419 (catch 'exit
8420 (while (setq start (string-match ^re kill (1+ start)))
8421 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8422 (throw 'exit nil)))
8423 t))))
8425 (defvar org-markers-to-move nil
8426 "Markers that should be moved with a cut-and-paste operation.
8427 Those markers are stored together with their positions relative to
8428 the start of the region.")
8430 (defun org-save-markers-in-region (beg end)
8431 "Check markers in region.
8432 If these markers are between BEG and END, record their position relative
8433 to BEG, so that after moving the block of text, we can put the markers back
8434 into place.
8435 This function gets called just before an entry or tree gets cut from the
8436 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8437 called immediately, to move the markers with the entries."
8438 (setq org-markers-to-move nil)
8439 (when (featurep 'org-clock)
8440 (org-clock-save-markers-for-cut-and-paste beg end))
8441 (when (featurep 'org-agenda)
8442 (org-agenda-save-markers-for-cut-and-paste beg end)))
8444 (defun org-check-and-save-marker (marker beg end)
8445 "Check if MARKER is between BEG and END.
8446 If yes, remember the marker and the distance to BEG."
8447 (when (and (marker-buffer marker)
8448 (equal (marker-buffer marker) (current-buffer))
8449 (>= marker beg) (< marker end))
8450 (push (cons marker (- marker beg)) org-markers-to-move)))
8452 (defun org-reinstall-markers-in-region (beg)
8453 "Move all remembered markers to their position relative to BEG."
8454 (dolist (x org-markers-to-move)
8455 (move-marker (car x) (+ beg (cdr x))))
8456 (setq org-markers-to-move nil))
8458 (defun org-narrow-to-subtree ()
8459 "Narrow buffer to the current subtree."
8460 (interactive)
8461 (save-excursion
8462 (save-match-data
8463 (org-with-limited-levels
8464 (narrow-to-region
8465 (progn (org-back-to-heading t) (point))
8466 (progn (org-end-of-subtree t t)
8467 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8468 (point)))))))
8470 (defun org-narrow-to-block ()
8471 "Narrow buffer to the current block."
8472 (interactive)
8473 (let* ((case-fold-search t)
8474 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8475 "^[ \t]*#\\+end_.*")))
8476 (if blockp
8477 (narrow-to-region (car blockp) (cdr blockp))
8478 (user-error "Not in a block"))))
8480 (defun org-clone-subtree-with-time-shift (n &optional shift)
8481 "Clone the task (subtree) at point N times.
8482 The clones will be inserted as siblings.
8484 In interactive use, the user will be prompted for the number of
8485 clones to be produced. If the entry has a timestamp, the user
8486 will also be prompted for a time shift, which may be a repeater
8487 as used in time stamps, for example `+3d'. To disable this,
8488 you can call the function with a universal prefix argument.
8490 When a valid repeater is given and the entry contains any time
8491 stamps, the clones will become a sequence in time, with time
8492 stamps in the subtree shifted for each clone produced. If SHIFT
8493 is nil or the empty string, time stamps will be left alone. The
8494 ID property of the original subtree is removed.
8496 In each clone, all the CLOCK entries will be removed. This
8497 prevents Org from considering that the clocked times overlap.
8499 If the original subtree did contain time stamps with a repeater,
8500 the following will happen:
8501 - the repeater will be removed in each clone
8502 - an additional clone will be produced, with the current, unshifted
8503 date(s) in the entry.
8504 - the original entry will be placed *after* all the clones, with
8505 repeater intact.
8506 - the start days in the repeater in the original entry will be shifted
8507 to past the last clone.
8508 In this way you can spell out a number of instances of a repeating task,
8509 and still retain the repeater to cover future instances of the task.
8511 As described above, N+1 clones are produced when the original
8512 subtree has a repeater. Setting N to 0, then, can be used to
8513 remove the repeater from a subtree and create a shifted clone
8514 with the original repeater."
8515 (interactive "nNumber of clones to produce: ")
8516 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8517 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8518 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8519 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8520 (shift
8521 (or shift
8522 (if (and (not (equal current-prefix-arg '(4)))
8523 (save-excursion
8524 (goto-char beg)
8525 (re-search-forward org-ts-regexp-both end-of-tree t)))
8526 (read-from-minibuffer
8527 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8528 ""))) ;No time shift
8529 (doshift
8530 (and (org-string-nw-p shift)
8531 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8532 shift)
8533 (user-error "Invalid shift specification %s" shift)))))
8534 (goto-char end-of-tree)
8535 (unless (bolp) (insert "\n"))
8536 (let* ((end (point))
8537 (template (buffer-substring beg end))
8538 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8539 (shift-what (pcase (and doshift (match-string 2 shift))
8540 (`nil nil)
8541 ("d" 'day)
8542 ("w" (setq shift-n (* 7 shift-n)) 'day)
8543 ("m" 'month)
8544 ("y" 'year)
8545 (_ (error "Unsupported time unit"))))
8546 (nmin 1)
8547 (nmax n)
8548 (n-no-remove -1)
8549 (idprop (org-entry-get nil "ID")))
8550 (when (and doshift
8551 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8552 template))
8553 (delete-region beg end)
8554 (setq end beg)
8555 (setq nmin 0)
8556 (setq nmax (1+ nmax))
8557 (setq n-no-remove nmax))
8558 (goto-char end)
8559 (cl-loop for n from nmin to nmax do
8560 (insert
8561 ;; Prepare clone.
8562 (with-temp-buffer
8563 (insert template)
8564 (org-mode)
8565 (goto-char (point-min))
8566 (org-show-subtree)
8567 (and idprop (if org-clone-delete-id
8568 (org-entry-delete nil "ID")
8569 (org-id-get-create t)))
8570 (unless (= n 0)
8571 (while (re-search-forward org-clock-line-re nil t)
8572 (delete-region (line-beginning-position)
8573 (line-beginning-position 2)))
8574 (goto-char (point-min))
8575 (while (re-search-forward org-drawer-regexp nil t)
8576 (org-remove-empty-drawer-at (point))))
8577 (goto-char (point-min))
8578 (when doshift
8579 (while (re-search-forward org-ts-regexp-both nil t)
8580 (org-timestamp-change (* n shift-n) shift-what))
8581 (unless (= n n-no-remove)
8582 (goto-char (point-min))
8583 (while (re-search-forward org-ts-regexp nil t)
8584 (save-excursion
8585 (goto-char (match-beginning 0))
8586 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8587 (delete-region (match-beginning 1) (match-end 1)))))))
8588 (buffer-string)))))
8589 (goto-char beg)))
8591 ;;; Outline Sorting
8593 (defun org-sort (&optional with-case)
8594 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8595 Optional argument WITH-CASE means sort case-sensitively."
8596 (interactive "P")
8597 (org-call-with-arg
8598 (cond ((org-at-table-p) #'org-table-sort-lines)
8599 ((org-at-item-p) #'org-sort-list)
8600 (t #'org-sort-entries))
8601 with-case))
8603 (defun org-sort-remove-invisible (s)
8604 "Remove invisible part of links and emphasis markers from string S."
8605 (remove-text-properties 0 (length s) org-rm-props s)
8606 (replace-regexp-in-string
8607 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8608 (replace-regexp-in-string
8609 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8610 (org-link-display-format s)
8611 t t) t t))
8613 (defvar org-priority-regexp) ; defined later in the file
8615 (defvar org-after-sorting-entries-or-items-hook nil
8616 "Hook that is run after a bunch of entries or items have been sorted.
8617 When children are sorted, the cursor is in the parent line when this
8618 hook gets called. When a region or a plain list is sorted, the cursor
8619 will be in the first entry of the sorted region/list.")
8621 (defun org-sort-entries
8622 (&optional with-case sorting-type getkey-func compare-func property
8623 interactive?)
8624 "Sort entries on a certain level of an outline tree.
8625 If there is an active region, the entries in the region are sorted.
8626 Else, if the cursor is before the first entry, sort the top-level items.
8627 Else, the children of the entry at point are sorted.
8629 Sorting can be alphabetically, numerically, by date/time as given by
8630 a time stamp, by a property, by priority order, or by a custom function.
8632 The command prompts for the sorting type unless it has been given to the
8633 function through the SORTING-TYPE argument, which needs to be a character,
8634 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8635 the precise meaning of each character:
8637 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8638 c By creation time, which is assumed to be the first inactive time stamp
8639 at the beginning of a line.
8640 d By deadline date/time.
8641 k By clocking time.
8642 n Numerically, by converting the beginning of the entry/item to a number.
8643 o By order of TODO keywords.
8644 p By priority according to the cookie.
8645 r By the value of a property.
8646 s By scheduled date/time.
8647 t By date/time, either the first active time stamp in the entry, or, if
8648 none exist, by the first inactive one.
8650 Capital letters will reverse the sort order.
8652 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8653 called with point at the beginning of the record. It must return a
8654 value that is compatible with COMPARE-FUNC, the function used to
8655 compare entries.
8657 Comparing entries ignores case by default. However, with an optional argument
8658 WITH-CASE, the sorting considers case as well.
8660 Sorting is done against the visible part of the headlines, it ignores hidden
8661 links.
8663 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8665 A non-nil value for INTERACTIVE? is used to signal that this
8666 function is being called interactively."
8667 (interactive (list current-prefix-arg nil nil nil nil t))
8668 (let ((case-func (if with-case 'identity 'downcase))
8669 start beg end stars re re2
8670 txt what tmp)
8671 ;; Find beginning and end of region to sort
8672 (cond
8673 ((org-region-active-p)
8674 ;; we will sort the region
8675 (setq end (region-end)
8676 what "region")
8677 (goto-char (region-beginning))
8678 (unless (org-at-heading-p) (outline-next-heading))
8679 (setq start (point)))
8680 ((or (org-at-heading-p)
8681 (ignore-errors (progn (org-back-to-heading) t)))
8682 ;; we will sort the children of the current headline
8683 (org-back-to-heading)
8684 (setq start (point)
8685 end (progn (org-end-of-subtree t t)
8686 (or (bolp) (insert "\n"))
8687 (when (>= (org-back-over-empty-lines) 1)
8688 (forward-line 1))
8689 (point))
8690 what "children")
8691 (goto-char start)
8692 (outline-show-subtree)
8693 (outline-next-heading))
8695 ;; we will sort the top-level entries in this file
8696 (goto-char (point-min))
8697 (or (org-at-heading-p) (outline-next-heading))
8698 (setq start (point))
8699 (goto-char (point-max))
8700 (beginning-of-line 1)
8701 (when (looking-at ".*?\\S-")
8702 ;; File ends in a non-white line
8703 (end-of-line 1)
8704 (insert "\n"))
8705 (setq end (point-max))
8706 (setq what "top-level")
8707 (goto-char start)
8708 (org-show-all '(headings blocks))))
8710 (setq beg (point))
8711 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8713 (looking-at "\\(\\*+\\)")
8714 (setq stars (match-string 1)
8715 re (concat "^" (regexp-quote stars) " +")
8716 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8717 txt (buffer-substring beg end))
8718 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8719 (when (and (not (equal stars "*")) (string-match re2 txt))
8720 (user-error "Region to sort contains a level above the first entry"))
8722 (unless sorting-type
8723 (message
8724 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8725 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8726 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8727 what)
8728 (setq sorting-type (read-char-exclusive)))
8730 (unless getkey-func
8731 (and (= (downcase sorting-type) ?f)
8732 (setq getkey-func
8733 (or (and interactive?
8734 (org-read-function
8735 "Function for extracting keys: "))
8736 (error "Missing key extractor")))))
8738 (and (= (downcase sorting-type) ?r)
8739 (not property)
8740 (setq property
8741 (completing-read "Property: "
8742 (mapcar #'list (org-buffer-property-keys t))
8743 nil t)))
8745 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8746 (message "Sorting entries...")
8748 (save-restriction
8749 (narrow-to-region start end)
8750 (let ((restore-clock?
8751 ;; The clock marker is lost when using `sort-subr'; mark
8752 ;; the clock with temporary `:org-clock-marker-backup'
8753 ;; text property.
8754 (when (and (eq (org-clock-is-active) (current-buffer))
8755 (<= start (marker-position org-clock-marker))
8756 (>= end (marker-position org-clock-marker)))
8757 (org-with-silent-modifications
8758 (put-text-property (1- org-clock-marker) org-clock-marker
8759 :org-clock-marker-backup t))
8761 (dcst (downcase sorting-type))
8762 (case-fold-search nil)
8763 (now (current-time)))
8764 (org-preserve-local-variables
8765 (sort-subr
8766 (/= dcst sorting-type)
8767 ;; This function moves to the beginning character of the
8768 ;; "record" to be sorted.
8769 (lambda nil
8770 (if (re-search-forward re nil t)
8771 (goto-char (match-beginning 0))
8772 (goto-char (point-max))))
8773 ;; This function moves to the last character of the "record" being
8774 ;; sorted.
8775 (lambda nil
8776 (save-match-data
8777 (condition-case nil
8778 (outline-forward-same-level 1)
8779 (error
8780 (goto-char (point-max))))))
8781 ;; This function returns the value that gets sorted against.
8782 (lambda ()
8783 (cond
8784 ((= dcst ?n)
8785 (string-to-number
8786 (org-sort-remove-invisible (org-get-heading t t t t))))
8787 ((= dcst ?a)
8788 (funcall case-func
8789 (org-sort-remove-invisible (org-get-heading t t t t))))
8790 ((= dcst ?k)
8791 (or (get-text-property (point) :org-clock-minutes) 0))
8792 ((= dcst ?t)
8793 (let ((end (save-excursion (outline-next-heading) (point))))
8794 (if (or (re-search-forward org-ts-regexp end t)
8795 (re-search-forward org-ts-regexp-both end t))
8796 (org-time-string-to-seconds (match-string 0))
8797 (float-time now))))
8798 ((= dcst ?c)
8799 (let ((end (save-excursion (outline-next-heading) (point))))
8800 (if (re-search-forward
8801 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8802 end t)
8803 (org-time-string-to-seconds (match-string 0))
8804 (float-time now))))
8805 ((= dcst ?s)
8806 (let ((end (save-excursion (outline-next-heading) (point))))
8807 (if (re-search-forward org-scheduled-time-regexp end t)
8808 (org-time-string-to-seconds (match-string 1))
8809 (float-time now))))
8810 ((= dcst ?d)
8811 (let ((end (save-excursion (outline-next-heading) (point))))
8812 (if (re-search-forward org-deadline-time-regexp end t)
8813 (org-time-string-to-seconds (match-string 1))
8814 (float-time now))))
8815 ((= dcst ?p)
8816 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8817 (string-to-char (match-string 2))
8818 org-default-priority))
8819 ((= dcst ?r)
8820 (or (org-entry-get nil property) ""))
8821 ((= dcst ?o)
8822 (when (looking-at org-complex-heading-regexp)
8823 (let* ((m (match-string 2))
8824 (s (if (member m org-done-keywords) '- '+)))
8825 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8826 ((= dcst ?f)
8827 (if getkey-func
8828 (progn
8829 (setq tmp (funcall getkey-func))
8830 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8831 tmp)
8832 (error "Invalid key function `%s'" getkey-func)))
8833 (t (error "Invalid sorting type `%c'" sorting-type))))
8835 (cond
8836 ((= dcst ?a) 'org-string-collate-lessp)
8837 ((= dcst ?f)
8838 (or compare-func
8839 (and interactive?
8840 (org-read-function
8841 (concat "Function for comparing keys "
8842 "(empty for default `sort-subr' predicate): ")
8843 'allow-empty))))
8844 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8845 (when restore-clock?
8846 (move-marker org-clock-marker
8847 (1+ (next-single-property-change
8848 start :org-clock-marker-backup)))
8849 (remove-text-properties (1- org-clock-marker) org-clock-marker
8850 '(:org-clock-marker-backup t)))))
8851 (run-hooks 'org-after-sorting-entries-or-items-hook)
8852 (message "Sorting entries...done")))
8854 (defun org-contextualize-keys (alist contexts)
8855 "Return valid elements in ALIST depending on CONTEXTS.
8857 `org-agenda-custom-commands' or `org-capture-templates' are the
8858 values used for ALIST, and `org-agenda-custom-commands-contexts'
8859 or `org-capture-templates-contexts' are the associated contexts
8860 definitions."
8861 (let ((contexts
8862 ;; normalize contexts
8863 (mapcar
8864 (lambda(c) (cond ((listp (cadr c))
8865 (list (car c) (car c) (nth 1 c)))
8866 ((string= "" (cadr c))
8867 (list (car c) (car c) (nth 2 c)))
8868 (t c)))
8869 contexts))
8870 (a alist) r s)
8871 ;; loop over all commands or templates
8872 (dolist (c a)
8873 (let (vrules repl)
8874 (cond
8875 ((not (assoc (car c) contexts))
8876 (push c r))
8877 ((and (assoc (car c) contexts)
8878 (setq vrules (org-contextualize-validate-key
8879 (car c) contexts)))
8880 (mapc (lambda (vr)
8881 (unless (equal (car vr) (cadr vr))
8882 (setq repl vr)))
8883 vrules)
8884 (if (not repl) (push c r)
8885 (push (cadr repl) s)
8886 (push
8887 (cons (car c)
8888 (cdr (or (assoc (cadr repl) alist)
8889 (error "Undefined key `%s' as contextual replacement for `%s'"
8890 (cadr repl) (car c)))))
8891 r))))))
8892 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8893 (delq
8895 (delete-dups
8896 (mapcar (lambda (x)
8897 (let ((tpl (car x)))
8898 (unless (delq
8900 (mapcar (lambda (y)
8901 (equal y tpl))
8903 x)))
8904 (reverse r))))))
8906 (defun org-contextualize-validate-key (key contexts)
8907 "Check CONTEXTS for agenda or capture KEY."
8908 (let (res)
8909 (dolist (r contexts)
8910 (dolist (rr (car (last r)))
8911 (when
8912 (and (equal key (car r))
8913 (if (functionp rr) (funcall rr)
8914 (or (and (eq (car rr) 'in-file)
8915 (buffer-file-name)
8916 (string-match (cdr rr) (buffer-file-name)))
8917 (and (eq (car rr) 'in-mode)
8918 (string-match (cdr rr) (symbol-name major-mode)))
8919 (and (eq (car rr) 'in-buffer)
8920 (string-match (cdr rr) (buffer-name)))
8921 (when (and (eq (car rr) 'not-in-file)
8922 (buffer-file-name))
8923 (not (string-match (cdr rr) (buffer-file-name))))
8924 (when (eq (car rr) 'not-in-mode)
8925 (not (string-match (cdr rr) (symbol-name major-mode))))
8926 (when (eq (car rr) 'not-in-buffer)
8927 (not (string-match (cdr rr) (buffer-name)))))))
8928 (push r res))))
8929 (delete-dups (delq nil res))))
8931 ;; Defined to provide a value for defcustom, since there is no
8932 ;; string-collate-greaterp in Emacs.
8933 (defun org-string-collate-greaterp (s1 s2)
8934 "Return non-nil if S1 is greater than S2 in collation order."
8935 (not (org-string-collate-lessp s1 s2)))
8937 ;;;###autoload
8938 (defun org-run-like-in-org-mode (cmd)
8939 "Run a command, pretending that the current buffer is in Org mode.
8940 This will temporarily bind local variables that are typically bound in
8941 Org mode to the values they have in Org mode, and then interactively
8942 call CMD."
8943 (org-load-modules-maybe)
8944 (let (binds)
8945 (dolist (var (org-get-local-variables))
8946 (when (or (not (boundp (car var)))
8947 (eq (symbol-value (car var))
8948 (default-value (car var))))
8949 (push (list (car var) `(quote ,(cadr var))) binds)))
8950 (eval `(let ,binds
8951 (call-interactively (quote ,cmd))))))
8953 (defun org-get-category (&optional pos force-refresh)
8954 "Get the category applying to position POS."
8955 (save-match-data
8956 (when force-refresh (org-refresh-category-properties))
8957 (let ((pos (or pos (point))))
8958 (or (get-text-property pos 'org-category)
8959 (progn (org-refresh-category-properties)
8960 (get-text-property pos 'org-category))))))
8962 ;;; Refresh properties
8964 (defun org-refresh-properties (dprop tprop)
8965 "Refresh buffer text properties.
8966 DPROP is the drawer property and TPROP is either the
8967 corresponding text property to set, or an alist with each element
8968 being a text property (as a symbol) and a function to apply to
8969 the value of the drawer property."
8970 (let* ((case-fold-search t)
8971 (inhibit-read-only t)
8972 (inherit? (org-property-inherit-p dprop))
8973 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8974 (global (and inherit? (org--property-global-value dprop nil))))
8975 (org-with-silent-modifications
8976 (org-with-point-at 1
8977 ;; Set global values (e.g., values defined through
8978 ;; "#+PROPERTY:" keywords) to the whole buffer.
8979 (when global (put-text-property (point-min) (point-max) tprop global))
8980 ;; Set local values.
8981 (while (re-search-forward property-re nil t)
8982 (when (org-at-property-p)
8983 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8984 (outline-next-heading))))))
8986 (defun org-refresh-property (tprop p &optional inherit)
8987 "Refresh the buffer text property TPROP from the drawer property P.
8988 The refresh happens only for the current headline, or the whole
8989 sub-tree if optional argument INHERIT is non-nil."
8990 (unless (org-before-first-heading-p)
8991 (save-excursion
8992 (org-back-to-heading t)
8993 (let ((start (point))
8994 (end (save-excursion
8995 (if inherit (org-end-of-subtree t t)
8996 (or (outline-next-heading) (point-max))))))
8997 (if (symbolp tprop)
8998 ;; TPROP is a text property symbol.
8999 (put-text-property start end tprop p)
9000 ;; TPROP is an alist with (property . function) elements.
9001 (pcase-dolist (`(,prop . ,f) tprop)
9002 (put-text-property start end prop (funcall f p))))))))
9004 (defun org-refresh-category-properties ()
9005 "Refresh category text properties in the buffer."
9006 (let ((case-fold-search t)
9007 (inhibit-read-only t)
9008 (default-category
9009 (cond ((null org-category)
9010 (if buffer-file-name
9011 (file-name-sans-extension
9012 (file-name-nondirectory buffer-file-name))
9013 "???"))
9014 ((symbolp org-category) (symbol-name org-category))
9015 (t org-category))))
9016 (org-with-silent-modifications
9017 (org-with-wide-buffer
9018 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9019 ;; This is the default category for the buffer. If none is
9020 ;; found, fall-back to `org-category' or buffer file name.
9021 (put-text-property
9022 (point-min) (point-max)
9023 'org-category
9024 (catch 'buffer-category
9025 (goto-char (point-max))
9026 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9027 (let ((element (org-element-at-point)))
9028 (when (eq (org-element-type element) 'keyword)
9029 (throw 'buffer-category
9030 (org-element-property :value element)))))
9031 default-category))
9032 ;; Set sub-tree specific categories.
9033 (goto-char (point-min))
9034 (let ((regexp (org-re-property "CATEGORY")))
9035 (while (re-search-forward regexp nil t)
9036 (let ((value (match-string-no-properties 3)))
9037 (when (org-at-property-p)
9038 (put-text-property
9039 (save-excursion (org-back-to-heading t) (point))
9040 (save-excursion (org-end-of-subtree t t) (point))
9041 'org-category
9042 value)))))))))
9044 (defun org-refresh-stats-properties ()
9045 "Refresh stats text properties in the buffer."
9046 (org-with-silent-modifications
9047 (org-with-point-at 1
9048 (let ((regexp (concat org-outline-regexp-bol
9049 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9050 (while (re-search-forward regexp nil t)
9051 (let* ((numerator (string-to-number (match-string 1)))
9052 (denominator (and (match-end 2)
9053 (string-to-number (match-string 2))))
9054 (stats (cond ((not denominator) numerator) ;percent
9055 ((= denominator 0) 0)
9056 (t (/ (* numerator 100) denominator)))))
9057 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9058 'org-stats stats)))))))
9060 (defun org-refresh-effort-properties ()
9061 "Refresh effort properties"
9062 (org-refresh-properties
9063 org-effort-property
9064 '((effort . identity)
9065 (effort-minutes . org-duration-to-minutes))))
9067 ;;;; Link Stuff
9069 ;;; Link abbreviations
9071 (defun org-link-expand-abbrev (link)
9072 "Apply replacements as defined in `org-link-abbrev-alist'."
9073 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9074 (let* ((key (match-string 1 link))
9075 (as (or (assoc key org-link-abbrev-alist-local)
9076 (assoc key org-link-abbrev-alist)))
9077 (tag (and (match-end 2) (match-string 3 link)))
9078 rpl)
9079 (if (not as)
9080 link
9081 (setq rpl (cdr as))
9082 (cond
9083 ((symbolp rpl) (funcall rpl tag))
9084 ((string-match "%(\\([^)]+\\))" rpl)
9085 (replace-match
9086 (save-match-data
9087 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9088 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9089 ((string-match "%h" rpl)
9090 (replace-match (url-hexify-string (or tag "")) t t rpl))
9091 (t (concat rpl tag)))))
9092 link))
9094 ;;; Storing and inserting links
9096 (defvar org-insert-link-history nil
9097 "Minibuffer history for links inserted with `org-insert-link'.")
9099 (defvar org-stored-links nil
9100 "Contains the links stored with `org-store-link'.")
9102 (defvar org-store-link-plist nil
9103 "Plist with info about the most recently link created with `org-store-link'.")
9105 (defun org-store-link-functions ()
9106 "Return a list of functions that are called to create and store a link.
9107 The functions defined in the :store property of
9108 `org-link-parameters'.
9110 Each function will be called in turn until one returns a non-nil
9111 value. Each function should check if it is responsible for
9112 creating this link (for example by looking at the major mode).
9113 If not, it must exit and return nil. If yes, it should return
9114 a non-nil value after calling `org-store-link-props' with a list
9115 of properties and values. Special properties are:
9117 :type The link prefix, like \"http\". This must be given.
9118 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9119 This is obligatory as well.
9120 :description Optional default description for the second pair
9121 of brackets in an Org mode link. The user can still change
9122 this when inserting this link into an Org mode buffer.
9124 In addition to these, any additional properties can be specified
9125 and then used in capture templates."
9126 (cl-loop for link in org-link-parameters
9127 with store-func
9128 do (setq store-func (org-link-get-parameter (car link) :store))
9129 if store-func
9130 collect store-func))
9132 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9133 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9135 ;;;###autoload
9136 (defun org-store-link (arg &optional interactive?)
9137 "Store an org-link to the current location.
9138 \\<org-mode-map>
9139 This link is added to `org-stored-links' and can later be inserted
9140 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9142 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9143 A single
9144 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9145 `org-gnus-prefer-web-links' for links to Usenet articles.
9147 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9148 skipping storing functions that are not
9149 part of Org core.
9151 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9152 prefix ARG forces storing a link for each line in the
9153 active region.
9155 Assume the function is called interactively if INTERACTIVE? is
9156 non-nil."
9157 (interactive "P\np")
9158 (org-load-modules-maybe)
9159 (if (and (equal arg '(64)) (org-region-active-p))
9160 (save-excursion
9161 (let ((end (region-end)))
9162 (goto-char (region-beginning))
9163 (set-mark (point))
9164 (while (< (point-at-eol) end)
9165 (move-end-of-line 1) (activate-mark)
9166 (let (current-prefix-arg)
9167 (call-interactively 'org-store-link))
9168 (move-beginning-of-line 2)
9169 (set-mark (point)))))
9170 (setq org-store-link-plist nil)
9171 (let (link cpltxt desc description search txt custom-id agenda-link)
9172 (cond
9173 ;; Store a link using an external link type, if any function is
9174 ;; available. If more than one can generate a link from current
9175 ;; location, ask which one to use.
9176 ((and (not (equal arg '(16)))
9177 (let ((results-alist nil))
9178 (dolist (f (org-store-link-functions))
9179 (when (funcall f)
9180 ;; XXX: return value is not link's plist, so we
9181 ;; store the new value before it is modified. It
9182 ;; would be cleaner to ask store link functions to
9183 ;; return the plist instead.
9184 (push (cons f (copy-sequence org-store-link-plist))
9185 results-alist)))
9186 (pcase results-alist
9187 (`nil nil)
9188 (`((,_ . ,_)) t) ;single choice: nothing to do
9189 (`((,name . ,_) . ,_)
9190 ;; Reinstate link plist associated to the chosen
9191 ;; function.
9192 (apply #'org-store-link-props
9193 (cdr (assoc-string
9194 (completing-read
9195 "Which function for creating the link? "
9196 (mapcar #'car results-alist)
9197 nil t (symbol-name name))
9198 results-alist)))
9199 t))))
9200 (setq link (plist-get org-store-link-plist :link))
9201 (setq desc (or (plist-get org-store-link-plist :description)
9202 link)))
9204 ;; Store a link from a source code buffer.
9205 ((org-src-edit-buffer-p)
9206 (let ((coderef-format (org-src-coderef-format)))
9207 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9208 (setq link (format "(%s)" (match-string-no-properties 3))))
9209 (interactive?
9210 (let ((label (read-string "Code line label: ")))
9211 (end-of-line)
9212 (setq link (format coderef-format label))
9213 (let ((gc (- 79 (length link))))
9214 (if (< (current-column) gc)
9215 (org-move-to-column gc t)
9216 (insert " ")))
9217 (insert link)
9218 (setq link (concat "(" label ")"))
9219 (setq desc nil)))
9220 (t (setq link nil)))))
9222 ;; We are in the agenda, link to referenced location
9223 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9224 (let ((m (or (get-text-property (point) 'org-hd-marker)
9225 (get-text-property (point) 'org-marker))))
9226 (when m
9227 (org-with-point-at m
9228 (setq agenda-link (org-store-link nil interactive?))))))
9230 ((eq major-mode 'calendar-mode)
9231 (let ((cd (calendar-cursor-to-date)))
9232 (setq link
9233 (format-time-string
9234 (car org-time-stamp-formats)
9235 (apply 'encode-time
9236 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9237 nil nil nil))))
9238 (org-store-link-props :type "calendar" :date cd)))
9240 ((eq major-mode 'help-mode)
9241 (setq link (concat "help:" (save-excursion
9242 (goto-char (point-min))
9243 (looking-at "^[^ ]+")
9244 (match-string 0))))
9245 (org-store-link-props :type "help"))
9247 ((eq major-mode 'w3-mode)
9248 (setq cpltxt (if (and (buffer-name)
9249 (not (string-match "Untitled" (buffer-name))))
9250 (buffer-name)
9251 (url-view-url t))
9252 link (url-view-url t))
9253 (org-store-link-props :type "w3" :url (url-view-url t)))
9255 ((eq major-mode 'image-mode)
9256 (setq cpltxt (concat "file:"
9257 (abbreviate-file-name buffer-file-name))
9258 link cpltxt)
9259 (org-store-link-props :type "image" :file buffer-file-name))
9261 ;; In dired, store a link to the file of the current line
9262 ((derived-mode-p 'dired-mode)
9263 (let ((file (dired-get-filename nil t)))
9264 (setq file (if file
9265 (abbreviate-file-name
9266 (expand-file-name (dired-get-filename nil t)))
9267 ;; otherwise, no file so use current directory.
9268 default-directory))
9269 (setq cpltxt (concat "file:" file)
9270 link cpltxt)))
9272 ((setq search (run-hook-with-args-until-success
9273 'org-create-file-search-functions))
9274 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9275 "::" search))
9276 (setq cpltxt (or description link)))
9278 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9279 (org-with-limited-levels
9280 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9281 (cond
9282 ;; Store a link using the target at point
9283 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9284 (setq cpltxt
9285 (concat "file:"
9286 (abbreviate-file-name
9287 (buffer-file-name (buffer-base-buffer)))
9288 "::" (match-string 1))
9289 link cpltxt))
9290 ((and (featurep 'org-id)
9291 (or (eq org-id-link-to-org-use-id t)
9292 (and interactive?
9293 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9294 (and (eq org-id-link-to-org-use-id
9295 'create-if-interactive-and-no-custom-id)
9296 (not custom-id))))
9297 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9298 ;; Store a link using the ID at point
9299 (setq link (condition-case nil
9300 (prog1 (org-id-store-link)
9301 (setq desc (or (plist-get org-store-link-plist
9302 :description)
9303 "")))
9304 (error
9305 ;; Probably before first headline, link only to file
9306 (concat "file:"
9307 (abbreviate-file-name
9308 (buffer-file-name (buffer-base-buffer))))))))
9310 ;; Just link to current headline
9311 (setq cpltxt (concat "file:"
9312 (abbreviate-file-name
9313 (buffer-file-name (buffer-base-buffer)))))
9314 ;; Add a context search string
9315 (when (org-xor org-context-in-file-links
9316 (equal arg '(4)))
9317 (let* ((element (org-element-at-point))
9318 (name (org-element-property :name element)))
9319 (setq txt (cond
9320 ((org-at-heading-p) nil)
9321 (name)
9322 ((org-region-active-p)
9323 (buffer-substring (region-beginning) (region-end)))))
9324 (when (or (null txt) (string-match "\\S-" txt))
9325 (setq cpltxt
9326 (concat cpltxt "::"
9327 (condition-case nil
9328 (org-make-org-heading-search-string txt)
9329 (error "")))
9330 desc (or name
9331 (nth 4 (ignore-errors (org-heading-components)))
9332 "NONE")))))
9333 (when (string-match "::\\'" cpltxt)
9334 (setq cpltxt (substring cpltxt 0 -2)))
9335 (setq link cpltxt)))))
9337 ((buffer-file-name (buffer-base-buffer))
9338 ;; Just link to this file here.
9339 (setq cpltxt (concat "file:"
9340 (abbreviate-file-name
9341 (buffer-file-name (buffer-base-buffer)))))
9342 ;; Add a context string.
9343 (when (org-xor org-context-in-file-links
9344 (equal arg '(4)))
9345 (setq txt (if (org-region-active-p)
9346 (buffer-substring (region-beginning) (region-end))
9347 (buffer-substring (point-at-bol) (point-at-eol))))
9348 ;; Only use search option if there is some text.
9349 (when (string-match "\\S-" txt)
9350 (setq cpltxt
9351 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9352 desc "NONE")))
9353 (setq link cpltxt))
9355 (interactive?
9356 (user-error "No method for storing a link from this buffer"))
9358 (t (setq link nil)))
9360 ;; We're done setting link and desc, clean up
9361 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9362 (setq link (or link cpltxt)
9363 desc (or desc cpltxt))
9364 (cond ((not desc))
9365 ((equal desc "NONE") (setq desc nil))
9366 (t (setq desc
9367 (replace-regexp-in-string
9368 org-bracket-link-analytic-regexp
9369 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9370 desc))))
9371 ;; Return the link
9372 (if (not (and interactive? link))
9373 (or agenda-link (and link (org-make-link-string link desc)))
9374 (push (list link desc) org-stored-links)
9375 (message "Stored: %s" (or desc link))
9376 (when custom-id
9377 (setq link (concat "file:" (abbreviate-file-name
9378 (buffer-file-name)) "::#" custom-id))
9379 (push (list link desc) org-stored-links))
9380 (car org-stored-links)))))
9382 (defun org-store-link-props (&rest plist)
9383 "Store link properties.
9384 The properties are pre-processed by extracting names, addresses
9385 and dates."
9386 (let ((x (plist-get plist :from)))
9387 (when x
9388 (let ((adr (mail-extract-address-components x)))
9389 (setq plist (plist-put plist :fromname (car adr)))
9390 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9391 (let ((x (plist-get plist :to)))
9392 (when x
9393 (let ((adr (mail-extract-address-components x)))
9394 (setq plist (plist-put plist :toname (car adr)))
9395 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9396 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9397 (when x
9398 (setq plist (plist-put plist :date-timestamp
9399 (format-time-string
9400 (org-time-stamp-format t) x)))
9401 (setq plist (plist-put plist :date-timestamp-inactive
9402 (format-time-string
9403 (org-time-stamp-format t t) x)))))
9404 (let ((from (plist-get plist :from))
9405 (to (plist-get plist :to)))
9406 (when (and from to org-from-is-user-regexp)
9407 (setq plist
9408 (plist-put plist :fromto
9409 (if (string-match org-from-is-user-regexp from)
9410 (concat "to %t")
9411 (concat "from %f"))))))
9412 (setq org-store-link-plist plist))
9414 (defun org-add-link-props (&rest plist)
9415 "Add these properties to the link property list."
9416 (let (key value)
9417 (while plist
9418 (setq key (pop plist) value (pop plist))
9419 (setq org-store-link-plist
9420 (plist-put org-store-link-plist key value)))))
9422 (defun org-email-link-description (&optional fmt)
9423 "Return the description part of an email link.
9424 This takes information from `org-store-link-plist' and formats it
9425 according to FMT (default from `org-email-link-description-format')."
9426 (setq fmt (or fmt org-email-link-description-format))
9427 (let* ((p org-store-link-plist)
9428 (to (plist-get p :toaddress))
9429 (from (plist-get p :fromaddress))
9430 (table
9431 (list
9432 (cons "%c" (plist-get p :fromto))
9433 (cons "%F" (plist-get p :from))
9434 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9435 (cons "%T" (plist-get p :to))
9436 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9437 (cons "%s" (plist-get p :subject))
9438 (cons "%d" (plist-get p :date))
9439 (cons "%m" (plist-get p :message-id)))))
9440 (when (string-match "%c" fmt)
9441 ;; Check if the user wrote this message
9442 (if (and org-from-is-user-regexp from to
9443 (save-match-data (string-match org-from-is-user-regexp from)))
9444 (setq fmt (replace-match "to %t" t t fmt))
9445 (setq fmt (replace-match "from %f" t t fmt))))
9446 (org-replace-escapes fmt table)))
9448 (defun org-make-org-heading-search-string (&optional string)
9449 "Make search string for the current headline or STRING."
9450 (let ((s (or string
9451 (and (derived-mode-p 'org-mode)
9452 (save-excursion
9453 (org-back-to-heading t)
9454 (org-element-property :raw-value (org-element-at-point))))))
9455 (lines org-context-in-file-links))
9456 (unless string (setq s (concat "*" s))) ;Add * for headlines
9457 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9458 (when (and string (integerp lines) (> lines 0))
9459 (let ((slines (org-split-string s "\n")))
9460 (when (< lines (length slines))
9461 (setq s (mapconcat
9462 'identity
9463 (reverse (nthcdr (- (length slines) lines)
9464 (reverse slines))) "\n")))))
9465 (mapconcat #'identity (split-string s) " ")))
9467 (defconst org-link-escape-chars
9468 ;;%20 %5B %5D %25
9469 '(?\s ?\[ ?\] ?%)
9470 "List of characters that should be escaped in a link when stored to Org.
9471 This is the list that is used for internal purposes.")
9473 (defun org-make-link-string (link &optional description)
9474 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9475 (unless (org-string-nw-p link) (error "Empty link"))
9476 (let ((uri (cond ((string-match org-link-types-re link)
9477 (concat (match-string 1 link)
9478 (org-link-escape (substring link (match-end 1)))))
9479 ((or (file-name-absolute-p link)
9480 (string-match-p "\\`\\.\\.?/" link))
9481 (org-link-escape link))
9482 ;; For readability, do not encode space characters
9483 ;; in fuzzy links.
9484 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9485 (description
9486 (and (org-string-nw-p description)
9487 ;; Remove brackets from description, as they are fatal.
9488 (replace-regexp-in-string
9489 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9490 (org-trim description)))))
9491 (format "[[%s]%s]"
9493 (if description (format "[%s]" description) ""))))
9495 (defun org-link-escape (text &optional table merge)
9496 "Return percent escaped representation of TEXT.
9497 TEXT is a string with the text to escape.
9498 Optional argument TABLE is a list with characters that should be
9499 escaped. When nil, `org-link-escape-chars' is used.
9500 If optional argument MERGE is set, merge TABLE into
9501 `org-link-escape-chars'."
9502 (let ((characters-to-encode
9503 (cond ((null table) org-link-escape-chars)
9504 (merge (append org-link-escape-chars table))
9505 (t table))))
9506 (mapconcat
9507 (lambda (c)
9508 (if (or (memq c characters-to-encode)
9509 (and org-url-hexify-p (or (< c 32) (> c 126))))
9510 (mapconcat (lambda (e) (format "%%%.2X" e))
9511 (or (encode-coding-char c 'utf-8)
9512 (error "Unable to percent escape character: %c" c))
9514 (char-to-string c)))
9515 text "")))
9517 (defun org-link-unescape (str)
9518 "Unhex hexified Unicode parts in string STR.
9519 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9520 reciprocal of `org-link-escape', which see."
9521 (if (org-string-nw-p str)
9522 (replace-regexp-in-string
9523 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9524 str))
9526 (defun org-link-unescape-compound (hex)
9527 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9528 Note: this function also decodes single byte encodings like
9529 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9530 (save-match-data
9531 (let* ((bytes (cdr (split-string hex "%")))
9532 (ret "")
9533 (eat 0)
9534 (sum 0))
9535 (while bytes
9536 (let* ((val (string-to-number (pop bytes) 16))
9537 (shift-xor
9538 (if (= 0 eat)
9539 (cond
9540 ((>= val 252) (cons 6 252))
9541 ((>= val 248) (cons 5 248))
9542 ((>= val 240) (cons 4 240))
9543 ((>= val 224) (cons 3 224))
9544 ((>= val 192) (cons 2 192))
9545 (t (cons 0 0)))
9546 (cons 6 128))))
9547 (when (>= val 192) (setq eat (car shift-xor)))
9548 (setq val (logxor val (cdr shift-xor)))
9549 (setq sum (+ (lsh sum (car shift-xor)) val))
9550 (when (> eat 0) (setq eat (- eat 1)))
9551 (cond
9552 ((= 0 eat) ;multi byte
9553 (setq ret (concat ret (char-to-string sum)))
9554 (setq sum 0))
9555 ((not bytes) ; single byte(s)
9556 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9557 ret)))
9559 (defun org-link-unescape-single-byte-sequence (hex)
9560 "Unhexify hex-encoded single byte character sequences."
9561 (mapconcat (lambda (byte)
9562 (char-to-string (string-to-number byte 16)))
9563 (cdr (split-string hex "%")) ""))
9565 (defun org-fixup-message-id-for-http (s)
9566 "Replace special characters in a message id, so it can be used in an http query."
9567 (when (string-match "%" s)
9568 (setq s (mapconcat (lambda (c)
9569 (if (eq c ?%)
9570 "%25"
9571 (char-to-string c)))
9572 s "")))
9573 (while (string-match "<" s)
9574 (setq s (replace-match "%3C" t t s)))
9575 (while (string-match ">" s)
9576 (setq s (replace-match "%3E" t t s)))
9577 (while (string-match "@" s)
9578 (setq s (replace-match "%40" t t s)))
9581 (defun org-link-prettify (link)
9582 "Return a human-readable representation of LINK.
9583 The car of LINK must be a raw link.
9584 The cdr of LINK must be either a link description or nil."
9585 (let ((desc (or (cadr link) "<no description>")))
9586 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9587 "<" (car link) ">")))
9589 ;;;###autoload
9590 (defun org-insert-link-global ()
9591 "Insert a link like Org mode does.
9592 This command can be called in any mode to insert a link in Org syntax."
9593 (interactive)
9594 (org-load-modules-maybe)
9595 (org-run-like-in-org-mode 'org-insert-link))
9597 (defun org-insert-all-links (arg &optional pre post)
9598 "Insert all links in `org-stored-links'.
9599 When a universal prefix, do not delete the links from `org-stored-links'.
9600 When `ARG' is a number, insert the last N link(s).
9601 `PRE' and `POST' are optional arguments to define a string to
9602 prepend or to append."
9603 (interactive "P")
9604 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9605 (links (copy-sequence org-stored-links))
9606 (pr (or pre "- "))
9607 (po (or post "\n"))
9608 (cnt 1) l)
9609 (if (null org-stored-links)
9610 (message "No link to insert")
9611 (while (and (or (listp arg) (>= arg cnt))
9612 (setq l (if (listp arg)
9613 (pop links)
9614 (pop org-stored-links))))
9615 (setq cnt (1+ cnt))
9616 (insert pr)
9617 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9618 (insert po)))))
9620 (defun org-insert-last-stored-link (arg)
9621 "Insert the last link stored in `org-stored-links'."
9622 (interactive "p")
9623 (org-insert-all-links arg "" "\n"))
9625 (defun org-link-fontify-links-to-this-file ()
9626 "Fontify links to the current file in `org-stored-links'."
9627 (let ((f (buffer-file-name)) a b)
9628 (setq a (mapcar (lambda(l)
9629 (let ((ll (car l)))
9630 (when (and (string-match "^file:\\(.+\\)::" ll)
9631 (equal f (expand-file-name (match-string 1 ll))))
9632 ll)))
9633 org-stored-links))
9634 (when (featurep 'org-id)
9635 (setq b (mapcar (lambda(l)
9636 (let ((ll (car l)))
9637 (when (and (string-match "^id:\\(.+\\)$" ll)
9638 (equal f (expand-file-name
9639 (or (org-id-find-id-file
9640 (match-string 1 ll)) ""))))
9641 ll)))
9642 org-stored-links)))
9643 (mapcar (lambda(l)
9644 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9645 (delq nil (append a b)))))
9647 (defvar org--links-history nil)
9648 (defun org-insert-link (&optional complete-file link-location default-description)
9649 "Insert a link. At the prompt, enter the link.
9651 Completion can be used to insert any of the link protocol prefixes in use.
9653 The history can be used to select a link previously stored with
9654 `org-store-link'. When the empty string is entered (i.e. if you just
9655 press `RET' at the prompt), the link defaults to the most recently
9656 stored link. As `SPC' triggers completion in the minibuffer, you need to
9657 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9659 You will also be prompted for a description, and if one is given, it will
9660 be displayed in the buffer instead of the link.
9662 If there is already a link at point, this command will allow you to edit
9663 link and description parts.
9665 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9666 file name can be
9667 selected using completion. The path to the file will be relative to the
9668 current directory if the file is in the current directory or a subdirectory.
9669 Otherwise, the link will be the absolute path as completed in the minibuffer
9670 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9671 option `org-link-file-path-type'.
9673 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9674 absolute path even if the file is in
9675 the current directory or below.
9677 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9678 prefix negates `org-keep-stored-link-after-insertion'.
9680 If the LINK-LOCATION parameter is non-nil, this value will be used as
9681 the link location instead of reading one interactively.
9683 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9684 be used as the default description. Otherwise, if
9685 `org-make-link-description-function' is non-nil, this function
9686 will be called with the link target, and the result will be the
9687 default link description. When called non-interactivily, don't
9688 allow to edit the default description."
9689 (interactive "P")
9690 (let* ((wcf (current-window-configuration))
9691 (origbuf (current-buffer))
9692 (region (when (org-region-active-p)
9693 (buffer-substring (region-beginning) (region-end))))
9694 (remove (and region (list (region-beginning) (region-end))))
9695 (desc region)
9696 (link link-location)
9697 (abbrevs org-link-abbrev-alist-local)
9698 entry all-prefixes auto-desc)
9699 (cond
9700 (link-location) ; specified by arg, just use it.
9701 ((org-in-regexp org-bracket-link-regexp 1)
9702 ;; We do have a link at point, and we are going to edit it.
9703 (setq remove (list (match-beginning 0) (match-end 0)))
9704 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9705 (setq link (read-string "Link: "
9706 (org-link-unescape
9707 (match-string-no-properties 1)))))
9708 ((or (org-in-regexp org-angle-link-re)
9709 (org-in-regexp org-plain-link-re))
9710 ;; Convert to bracket link
9711 (setq remove (list (match-beginning 0) (match-end 0))
9712 link (read-string "Link: "
9713 (org-unbracket-string "<" ">" (match-string 0)))))
9714 ((member complete-file '((4) (16)))
9715 ;; Completing read for file names.
9716 (setq link (org-file-complete-link complete-file)))
9718 ;; Read link, with completion for stored links.
9719 (org-link-fontify-links-to-this-file)
9720 (org-switch-to-buffer-other-window "*Org Links*")
9721 (with-current-buffer "*Org Links*"
9722 (erase-buffer)
9723 (insert "Insert a link.
9724 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9725 (when org-stored-links
9726 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9727 (insert (mapconcat 'org-link-prettify
9728 (reverse org-stored-links) "\n")))
9729 (goto-char (point-min)))
9730 (let ((cw (selected-window)))
9731 (select-window (get-buffer-window "*Org Links*" 'visible))
9732 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9733 (unless (pos-visible-in-window-p (point-max))
9734 (org-fit-window-to-buffer))
9735 (and (window-live-p cw) (select-window cw)))
9736 (setq all-prefixes (append (mapcar 'car abbrevs)
9737 (mapcar 'car org-link-abbrev-alist)
9738 (org-link-types)))
9739 (unwind-protect
9740 ;; Fake a link history, containing the stored links.
9741 (let ((org--links-history
9742 (append (mapcar #'car org-stored-links)
9743 org-insert-link-history)))
9744 (setq link
9745 (org-completing-read
9746 "Link: "
9747 (append
9748 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9749 (mapcar #'car org-stored-links))
9750 nil nil nil
9751 'org--links-history
9752 (caar org-stored-links)))
9753 (unless (org-string-nw-p link) (user-error "No link selected"))
9754 (dolist (l org-stored-links)
9755 (when (equal link (cadr l))
9756 (setq link (car l))
9757 (setq auto-desc t)))
9758 (when (or (member link all-prefixes)
9759 (and (equal ":" (substring link -1))
9760 (member (substring link 0 -1) all-prefixes)
9761 (setq link (substring link 0 -1))))
9762 (setq link (with-current-buffer origbuf
9763 (org-link-try-special-completion link)))))
9764 (set-window-configuration wcf)
9765 (kill-buffer "*Org Links*"))
9766 (setq entry (assoc link org-stored-links))
9767 (or entry (push link org-insert-link-history))
9768 (setq desc (or desc (nth 1 entry)))))
9770 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9771 (not org-keep-stored-link-after-insertion))
9772 (setq org-stored-links (delq (assoc link org-stored-links)
9773 org-stored-links)))
9775 (when (and (string-match org-plain-link-re link)
9776 (not (string-match org-ts-regexp link)))
9777 ;; URL-like link, normalize the use of angular brackets.
9778 (setq link (org-unbracket-string "<" ">" link)))
9780 ;; Check if we are linking to the current file with a search
9781 ;; option If yes, simplify the link by using only the search
9782 ;; option.
9783 (when (and buffer-file-name
9784 (let ((case-fold-search nil))
9785 (string-match "\\`file:\\(.+?\\)::" link)))
9786 (let ((path (match-string-no-properties 1 link))
9787 (search (substring-no-properties link (match-end 0))))
9788 (save-match-data
9789 (when (equal (file-truename buffer-file-name) (file-truename path))
9790 ;; We are linking to this same file, with a search option
9791 (setq link search)))))
9793 ;; Check if we can/should use a relative path. If yes, simplify
9794 ;; the link.
9795 (let ((case-fold-search nil))
9796 (when (string-match "\\`\\(file\\|docview\\):" link)
9797 (let* ((type (match-string-no-properties 0 link))
9798 (path-start (match-end 0))
9799 (search (and (string-match "::\\(.*\\)\\'" link)
9800 (match-string 1 link)))
9801 (path
9802 (if search
9803 (substring-no-properties
9804 link path-start (match-beginning 0))
9805 (substring-no-properties link (match-end 0))))
9806 (origpath path))
9807 (cond
9808 ((or (eq org-link-file-path-type 'absolute)
9809 (equal complete-file '(16)))
9810 (setq path (abbreviate-file-name (expand-file-name path))))
9811 ((eq org-link-file-path-type 'noabbrev)
9812 (setq path (expand-file-name path)))
9813 ((eq org-link-file-path-type 'relative)
9814 (setq path (file-relative-name path)))
9816 (save-match-data
9817 (if (string-match (concat "^" (regexp-quote
9818 (expand-file-name
9819 (file-name-as-directory
9820 default-directory))))
9821 (expand-file-name path))
9822 ;; We are linking a file with relative path name.
9823 (setq path (substring (expand-file-name path)
9824 (match-end 0)))
9825 (setq path (abbreviate-file-name (expand-file-name path)))))))
9826 (setq link (concat type path (and search (concat "::" search))))
9827 (when (equal desc origpath)
9828 (setq desc path)))))
9830 (unless auto-desc
9831 (let ((initial-input
9832 (cond
9833 (default-description)
9834 ((not org-make-link-description-function) desc)
9835 (t (condition-case nil
9836 (funcall org-make-link-description-function link desc)
9837 (error
9838 (message "Can't get link description from `%s'"
9839 (symbol-name org-make-link-description-function))
9840 (sit-for 2)
9841 nil))))))
9842 (setq desc (if (called-interactively-p 'any)
9843 (read-string "Description: " initial-input)
9844 initial-input))))
9846 (unless (string-match "\\S-" desc) (setq desc nil))
9847 (when remove (apply 'delete-region remove))
9848 (insert (org-make-link-string link desc))
9849 ;; Redisplay so as the new link has proper invisible characters.
9850 (sit-for 0)))
9852 (defun org-link-try-special-completion (type)
9853 "If there is completion support for link type TYPE, offer it."
9854 (let ((fun (org-link-get-parameter type :complete)))
9855 (if (functionp fun)
9856 (funcall fun)
9857 (read-string "Link (no completion support): " (concat type ":")))))
9859 (defun org-file-complete-link (&optional arg)
9860 "Create a file link using completion."
9861 (let ((file (read-file-name "File: "))
9862 (pwd (file-name-as-directory (expand-file-name ".")))
9863 (pwd1 (file-name-as-directory (abbreviate-file-name
9864 (expand-file-name ".")))))
9865 (cond ((equal arg '(16))
9866 (concat "file:"
9867 (abbreviate-file-name (expand-file-name file))))
9868 ((string-match
9869 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9870 (concat "file:" (match-string 1 file)))
9871 ((string-match
9872 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9873 (expand-file-name file))
9874 (concat "file:"
9875 (match-string 1 (expand-file-name file))))
9876 (t (concat "file:" file)))))
9879 ;;; Opening/following a link
9881 (defvar org-link-search-failed nil)
9883 (defvar org-open-link-functions nil
9884 "Hook for functions finding a plain text link.
9885 These functions must take a single argument, the link content.
9886 They will be called for links that look like [[link text][description]]
9887 when LINK TEXT does not have a protocol like \"http:\" and does not look
9888 like a filename (e.g. \"./blue.png\").
9890 These functions will be called *before* Org attempts to resolve the
9891 link by doing text searches in the current buffer - so if you want a
9892 link \"[[target]]\" to still find \"<<target>>\", your function should
9893 handle this as a special case.
9895 When the function does handle the link, it must return a non-nil value.
9896 If it decides that it is not responsible for this link, it must return
9897 nil to indicate that that Org can continue with other options like
9898 exact and fuzzy text search.")
9900 (defun org-next-link (&optional search-backward)
9901 "Move forward to the next link.
9902 If the link is in hidden text, expose it."
9903 (interactive "P")
9904 (when (and org-link-search-failed (eq this-command last-command))
9905 (goto-char (point-min))
9906 (message "Link search wrapped back to beginning of buffer"))
9907 (setq org-link-search-failed nil)
9908 (let* ((pos (point))
9909 (ct (org-context))
9910 (a (assq :link ct))
9911 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9912 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9913 ((looking-at org-any-link-re)
9914 ;; Don't stay stuck at link without an org-link face
9915 (forward-char (if search-backward -1 1))))
9916 (if (funcall srch-fun org-any-link-re nil t)
9917 (progn
9918 (goto-char (match-beginning 0))
9919 (when (org-invisible-p) (org-show-context)))
9920 (goto-char pos)
9921 (setq org-link-search-failed t)
9922 (message "No further link found"))))
9924 (defun org-previous-link ()
9925 "Move backward to the previous link.
9926 If the link is in hidden text, expose it."
9927 (interactive)
9928 (funcall 'org-next-link t))
9930 (defun org-translate-link (s)
9931 "Translate a link string if a translation function has been defined."
9932 (with-temp-buffer
9933 (insert (org-trim s))
9934 (org-trim (org-element-interpret-data (org-element-context)))))
9936 (defun org-translate-link-from-planner (type path)
9937 "Translate a link from Emacs Planner syntax so that Org can follow it.
9938 This is still an experimental function, your mileage may vary."
9939 (cond
9940 ((member type '("http" "https" "news" "ftp"))
9941 ;; standard Internet links are the same.
9942 nil)
9943 ((and (equal type "irc") (string-match "^//" path))
9944 ;; Planner has two / at the beginning of an irc link, we have 1.
9945 ;; We should have zero, actually....
9946 (setq path (substring path 1)))
9947 ((and (equal type "lisp") (string-match "^/" path))
9948 ;; Planner has a slash, we do not.
9949 (setq type "elisp" path (substring path 1)))
9950 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9951 ;; A typical message link. Planner has the id after the final slash,
9952 ;; we separate it with a hash mark
9953 (setq path (concat (match-string 1 path) "#"
9954 (org-unbracket-string "<" ">" (match-string 2 path))))))
9955 (cons type path))
9957 (defun org-find-file-at-mouse (ev)
9958 "Open file link or URL at mouse."
9959 (interactive "e")
9960 (mouse-set-point ev)
9961 (org-open-at-point 'in-emacs))
9963 (defun org-open-at-mouse (ev)
9964 "Open file link or URL at mouse.
9965 See the docstring of `org-open-file' for details."
9966 (interactive "e")
9967 (mouse-set-point ev)
9968 (when (eq major-mode 'org-agenda-mode)
9969 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9970 (org-open-at-point))
9972 (defvar org-window-config-before-follow-link nil
9973 "The window configuration before following a link.
9974 This is saved in case the need arises to restore it.")
9976 ;;;###autoload
9977 (defun org-open-at-point-global ()
9978 "Follow a link or time-stamp like Org mode does.
9979 This command can be called in any mode to follow an external link
9980 or a time-stamp that has Org mode syntax. Its behavior is
9981 undefined when called on internal links (e.g., fuzzy links).
9982 Raise an error when there is nothing to follow. "
9983 (interactive)
9984 (cond ((org-in-regexp org-any-link-re)
9985 (org-open-link-from-string (match-string-no-properties 0)))
9986 ((or (org-in-regexp org-ts-regexp-both nil t)
9987 (org-in-regexp org-tsr-regexp-both nil t))
9988 (org-follow-timestamp-link))
9989 (t (user-error "No link found"))))
9991 ;;;###autoload
9992 (defun org-open-link-from-string (s &optional arg reference-buffer)
9993 "Open a link in the string S, as if it was in Org mode."
9994 (interactive "sLink: \nP")
9995 (let ((reference-buffer (or reference-buffer (current-buffer))))
9996 (with-temp-buffer
9997 (let ((org-inhibit-startup (not reference-buffer)))
9998 (org-mode)
9999 (insert s)
10000 (goto-char (point-min))
10001 (when reference-buffer
10002 (setq org-link-abbrev-alist-local
10003 (with-current-buffer reference-buffer
10004 org-link-abbrev-alist-local)))
10005 (org-open-at-point arg reference-buffer)))))
10007 (defvar org-open-at-point-functions nil
10008 "Hook that is run when following a link at point.
10010 Functions in this hook must return t if they identify and follow
10011 a link at point. If they don't find anything interesting at point,
10012 they must return nil.")
10014 (defvar org-link-search-inhibit-query nil)
10015 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10016 (defun org--open-doi-link (path)
10017 "Open a \"doi\" type link.
10018 PATH is a the path to search for, as a string."
10019 (browse-url (url-encode-url (concat org-doi-server-url path))))
10021 (defun org--open-elisp-link (path)
10022 "Open a \"elisp\" type link.
10023 PATH is the sexp to evaluate, as a string."
10024 (let ((cmd path))
10025 (if (or (and (org-string-nw-p
10026 org-confirm-elisp-link-not-regexp)
10027 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10028 (not org-confirm-elisp-link-function)
10029 (funcall org-confirm-elisp-link-function
10030 (format "Execute \"%s\" as elisp? "
10031 (org-add-props cmd nil 'face 'org-warning))))
10032 (message "%s => %s" cmd
10033 (if (eq (string-to-char cmd) ?\()
10034 (eval (read cmd))
10035 (call-interactively (read cmd))))
10036 (user-error "Abort"))))
10038 (defun org--open-help-link (path)
10039 "Open a \"help\" type link.
10040 PATH is a symbol name, as a string."
10041 (pcase (intern path)
10042 ((and (pred fboundp) variable) (describe-function variable))
10043 ((and (pred boundp) function) (describe-variable function))
10044 (name (user-error "Unknown function or variable: %s" name))))
10046 (defun org--open-shell-link (path)
10047 "Open a \"shell\" type link.
10048 PATH is the command to execute, as a string."
10049 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10050 (cmd path))
10051 (if (or (and (org-string-nw-p
10052 org-confirm-shell-link-not-regexp)
10053 (string-match
10054 org-confirm-shell-link-not-regexp cmd))
10055 (not org-confirm-shell-link-function)
10056 (funcall org-confirm-shell-link-function
10057 (format "Execute \"%s\" in shell? "
10058 (org-add-props cmd nil
10059 'face 'org-warning))))
10060 (progn
10061 (message "Executing %s" cmd)
10062 (shell-command cmd buf)
10063 (when (featurep 'midnight)
10064 (setq clean-buffer-list-kill-buffer-names
10065 (cons (buffer-name buf)
10066 clean-buffer-list-kill-buffer-names))))
10067 (user-error "Abort"))))
10069 (defun org-open-at-point (&optional arg reference-buffer)
10070 "Open link, timestamp, footnote or tags at point.
10072 When point is on a link, follow it. Normally, files will be
10073 opened by an appropriate application. If the optional prefix
10074 argument ARG is non-nil, Emacs will visit the file. With
10075 a double prefix argument, try to open outside of Emacs, in the
10076 application the system uses for this file type.
10078 When point is on a timestamp, open the agenda at the day
10079 specified.
10081 When point is a footnote definition, move to the first reference
10082 found. If it is on a reference, move to the associated
10083 definition.
10085 When point is on a headline, display a list of every link in the
10086 entry, so it is possible to pick one, or all, of them. If point
10087 is on a tag, call `org-tags-view' instead.
10089 When optional argument REFERENCE-BUFFER is non-nil, it should
10090 specify a buffer from where the link search should happen. This
10091 is used internally by `org-open-link-from-string'.
10093 On top of syntactically correct links, this function will also
10094 try to open links and time-stamps in comments, example
10095 blocks... i.e., whenever point is on something looking like
10096 a timestamp or a link."
10097 (interactive "P")
10098 ;; On a code block, open block's results.
10099 (unless (call-interactively 'org-babel-open-src-block-result)
10100 (org-load-modules-maybe)
10101 (setq org-window-config-before-follow-link (current-window-configuration))
10102 (org-remove-occur-highlights nil nil t)
10103 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10104 (let* ((context
10105 ;; Only consider supported types, even if they are not
10106 ;; the closest one.
10107 (org-element-lineage
10108 (org-element-context)
10109 '(clock footnote-definition footnote-reference headline
10110 inlinetask link timestamp)
10112 (type (org-element-type context))
10113 (value (org-element-property :value context)))
10114 (cond
10115 ;; On a headline or an inlinetask, but not on a timestamp,
10116 ;; a link, a footnote reference.
10117 ((memq type '(headline inlinetask))
10118 (org-match-line org-complex-heading-regexp)
10119 (if (and (match-beginning 5)
10120 (>= (point) (match-beginning 5))
10121 (< (point) (match-end 5)))
10122 ;; On tags.
10123 (org-tags-view arg (substring (match-string 5) 0 -1))
10124 ;; Not on tags.
10125 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10126 (`(nil . ,_)
10127 (require 'org-attach)
10128 (org-attach-reveal 'if-exists))
10129 (`(,links . ,links-end)
10130 (dolist (link (if (stringp links) (list links) links))
10131 (search-forward link nil links-end)
10132 (goto-char (match-beginning 0))
10133 (org-open-at-point))))))
10134 ;; On a footnote reference or at definition's label.
10135 ((or (eq type 'footnote-reference)
10136 (and (eq type 'footnote-definition)
10137 (save-excursion
10138 ;; Do not validate action when point is on the
10139 ;; spaces right after the footnote label, in
10140 ;; order to be on par with behavior on links.
10141 (skip-chars-forward " \t")
10142 (let ((begin
10143 (org-element-property :contents-begin context)))
10144 (if begin (< (point) begin)
10145 (= (org-element-property :post-affiliated context)
10146 (line-beginning-position)))))))
10147 (org-footnote-action))
10148 ;; No valid context. Ignore catch-all types like `headline'.
10149 ;; If point is on something looking like a link or
10150 ;; a time-stamp, try opening it. It may be useful in
10151 ;; comments, example blocks...
10152 ((memq type '(footnote-definition headline inlinetask nil))
10153 (call-interactively #'org-open-at-point-global))
10154 ;; On a clock line, make sure point is on the timestamp
10155 ;; before opening it.
10156 ((and (eq type 'clock)
10157 value
10158 (>= (point) (org-element-property :begin value))
10159 (<= (point) (org-element-property :end value)))
10160 (org-follow-timestamp-link))
10161 ;; Do nothing on white spaces after an object.
10162 ((>= (point)
10163 (save-excursion
10164 (goto-char (org-element-property :end context))
10165 (skip-chars-backward " \t")
10166 (point)))
10167 (user-error "No link found"))
10168 ((eq type 'timestamp) (org-follow-timestamp-link))
10169 ((eq type 'link)
10170 (let ((type (org-element-property :type context))
10171 (path (org-link-unescape (org-element-property :path context))))
10172 ;; Switch back to REFERENCE-BUFFER needed when called in
10173 ;; a temporary buffer through `org-open-link-from-string'.
10174 (with-current-buffer (or reference-buffer (current-buffer))
10175 (cond
10176 ((equal type "file")
10177 (if (string-match "[*?{]" (file-name-nondirectory path))
10178 (dired path)
10179 ;; Look into `org-link-parameters' in order to find
10180 ;; a DEDICATED-FUNCTION to open file. The function
10181 ;; will be applied on raw link instead of parsed
10182 ;; link due to the limitation in `org-add-link-type'
10183 ;; ("open" function called with a single argument).
10184 ;; If no such function is found, fallback to
10185 ;; `org-open-file'.
10186 (let* ((option (org-element-property :search-option context))
10187 (app (org-element-property :application context))
10188 (dedicated-function
10189 (org-link-get-parameter
10190 (if app (concat type "+" app) type)
10191 :follow)))
10192 (if dedicated-function
10193 (funcall dedicated-function
10194 (concat path
10195 (and option (concat "::" option))))
10196 (apply #'org-open-file
10197 path
10198 (cond (arg)
10199 ((equal app "emacs") 'emacs)
10200 ((equal app "sys") 'system))
10201 (cond ((not option) nil)
10202 ((string-match-p "\\`[0-9]+\\'" option)
10203 (list (string-to-number option)))
10204 (t (list nil
10205 (org-link-unescape option)))))))))
10206 ((functionp (org-link-get-parameter type :follow))
10207 (funcall (org-link-get-parameter type :follow) path))
10208 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10209 (unless (run-hook-with-args-until-success
10210 'org-open-link-functions path)
10211 (if (not arg) (org-mark-ring-push)
10212 (switch-to-buffer-other-window
10213 (org-get-buffer-for-internal-link (current-buffer))))
10214 (let ((destination
10215 (org-with-wide-buffer
10216 (if (equal type "radio")
10217 (org-search-radio-target
10218 (org-element-property :path context))
10219 (org-link-search
10220 (if (member type '("custom-id" "coderef"))
10221 (org-element-property :raw-link context)
10222 path)
10223 ;; Prevent fuzzy links from matching
10224 ;; themselves.
10225 (and (equal type "fuzzy")
10226 (+ 2 (org-element-property :begin context)))))
10227 (point))))
10228 (unless (and (<= (point-min) destination)
10229 (>= (point-max) destination))
10230 (widen))
10231 (goto-char destination))))
10232 (t (browse-url-at-point))))))
10233 (t (user-error "No link found")))))
10234 (run-hook-with-args 'org-follow-link-hook)))
10236 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10237 "Offer links in the current entry and return the selected link.
10238 If there is only one link, return it.
10239 If NTH is an integer, return the NTH link found.
10240 If ZERO is a string, check also this string for a link, and if
10241 there is one, return it."
10242 (with-current-buffer buffer
10243 (org-with-wide-buffer
10244 (goto-char marker)
10245 (let ((cnt ?0)
10246 have-zero end links link c)
10247 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10248 (push (match-string 0 zero) links)
10249 (setq cnt (1- cnt) have-zero t))
10250 (save-excursion
10251 (org-back-to-heading t)
10252 (setq end (save-excursion (outline-next-heading) (point)))
10253 (while (re-search-forward org-any-link-re end t)
10254 (push (match-string 0) links))
10255 (setq links (org-uniquify (reverse links))))
10256 (cond
10257 ((null links)
10258 (message "No links"))
10259 ((equal (length links) 1)
10260 (setq link (car links)))
10261 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10262 (setq link (nth (if have-zero nth (1- nth)) links)))
10263 (t ; we have to select a link
10264 (save-excursion
10265 (save-window-excursion
10266 (delete-other-windows)
10267 (with-output-to-temp-buffer "*Select Link*"
10268 (dolist (l links)
10269 (cond
10270 ((not (string-match org-bracket-link-regexp l))
10271 (princ (format "[%c] %s\n" (cl-incf cnt)
10272 (org-unbracket-string "<" ">" l))))
10273 ((match-end 3)
10274 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10275 (match-string 3 l) (match-string 1 l))))
10276 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10277 (match-string 1 l)))))))
10278 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10279 (message "Select link to open, RET to open all:")
10280 (setq c (read-char-exclusive))
10281 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10282 (when (equal c ?q) (user-error "Abort"))
10283 (if (equal c ?\C-m)
10284 (setq link links)
10285 (setq nth (- c ?0))
10286 (when have-zero (setq nth (1+ nth)))
10287 (unless (and (integerp nth) (>= (length links) nth))
10288 (user-error "Invalid link selection"))
10289 (setq link (nth (1- nth) links)))))
10290 (cons link end)))))
10292 ;; TODO: These functions are deprecated since `org-open-at-point'
10293 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10294 (defun org-open-file-with-system (path)
10295 "Open file at PATH using the system way of opening it."
10296 (org-open-file path 'system))
10297 (defun org-open-file-with-emacs (path)
10298 "Open file at PATH in Emacs."
10299 (org-open-file path 'emacs))
10302 ;;; File search
10304 (defvar org-create-file-search-functions nil
10305 "List of functions to construct the right search string for a file link.
10306 These functions are called in turn with point at the location to
10307 which the link should point.
10309 A function in the hook should first test if it would like to
10310 handle this file type, for example by checking the `major-mode'
10311 or the file extension. If it decides not to handle this file, it
10312 should just return nil to give other functions a chance. If it
10313 does handle the file, it must return the search string to be used
10314 when following the link. The search string will be part of the
10315 file link, given after a double colon, and `org-open-at-point'
10316 will automatically search for it. If special measures must be
10317 taken to make the search successful, another function should be
10318 added to the companion hook `org-execute-file-search-functions',
10319 which see.
10321 A function in this hook may also use `setq' to set the variable
10322 `description' to provide a suggestion for the descriptive text to
10323 be used for this link when it gets inserted into an Org buffer
10324 with \\[org-insert-link].")
10326 (defvar org-execute-file-search-functions nil
10327 "List of functions to execute a file search triggered by a link.
10329 Functions added to this hook must accept a single argument, the
10330 search string that was part of the file link, the part after the
10331 double colon. The function must first check if it would like to
10332 handle this search, for example by checking the `major-mode' or
10333 the file extension. If it decides not to handle this search, it
10334 should just return nil to give other functions a chance. If it
10335 does handle the search, it must return a non-nil value to keep
10336 other functions from trying.
10338 Each function can access the current prefix argument through the
10339 variable `current-prefix-arg'. Note that a single prefix is used
10340 to force opening a link in Emacs, so it may be good to only use a
10341 numeric or double prefix to guide the search function.
10343 In case this is needed, a function in this hook can also restore
10344 the window configuration before `org-open-at-point' was called using:
10346 (set-window-configuration org-window-config-before-follow-link)")
10348 (defun org-search-radio-target (target)
10349 "Search a radio target matching TARGET in current buffer.
10350 White spaces are not significant."
10351 (let ((re (format "<<<%s>>>"
10352 (mapconcat #'regexp-quote
10353 (split-string target)
10354 "[ \t]+\\(?:\n[ \t]*\\)?")))
10355 (origin (point)))
10356 (goto-char (point-min))
10357 (catch :radio-match
10358 (while (re-search-forward re nil t)
10359 (backward-char)
10360 (let ((object (org-element-context)))
10361 (when (eq (org-element-type object) 'radio-target)
10362 (goto-char (org-element-property :begin object))
10363 (org-show-context 'link-search)
10364 (throw :radio-match nil))))
10365 (goto-char origin)
10366 (user-error "No match for radio target: %s" target))))
10368 (defun org-link-search (s &optional avoid-pos stealth)
10369 "Search for a search string S.
10371 If S starts with \"#\", it triggers a custom ID search.
10373 If S is enclosed within parenthesis, it initiates a coderef
10374 search.
10376 If S is surrounded by forward slashes, it is interpreted as
10377 a regular expression. In Org mode files, this will create an
10378 `org-occur' sparse tree. In ordinary files, `occur' will be used
10379 to list matches. If the current buffer is in `dired-mode', grep
10380 will be used to search in all files.
10382 When AVOID-POS is given, ignore matches near that position.
10384 When optional argument STEALTH is non-nil, do not modify
10385 visibility around point, thus ignoring `org-show-context-detail'
10386 variable.
10388 Search is case-insensitive and ignores white spaces. Return type
10389 of matched result, which is either `dedicated' or `fuzzy'."
10390 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10391 (let* ((case-fold-search t)
10392 (origin (point))
10393 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10394 (starred (eq (string-to-char normalized) ?*))
10395 (words (split-string (if starred (substring s 1) s)))
10396 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10397 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10398 type)
10399 (cond
10400 ;; Check if there are any special search functions.
10401 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10402 ((eq (string-to-char s) ?#)
10403 ;; Look for a custom ID S if S starts with "#".
10404 (let* ((id (substring normalized 1))
10405 (match (org-find-property "CUSTOM_ID" id)))
10406 (if match (progn (goto-char match) (setf type 'dedicated))
10407 (error "No match for custom ID: %s" id))))
10408 ((string-match "\\`(\\(.*\\))\\'" normalized)
10409 ;; Look for coderef targets if S is enclosed within parenthesis.
10410 (let ((coderef (match-string-no-properties 1 normalized))
10411 (re (substring s-single-re 1 -1)))
10412 (goto-char (point-min))
10413 (catch :coderef-match
10414 (while (re-search-forward re nil t)
10415 (let ((element (org-element-at-point)))
10416 (when (and (memq (org-element-type element)
10417 '(example-block src-block))
10418 ;; Build proper regexp according to current
10419 ;; block's label format.
10420 (let ((label-fmt
10421 (regexp-quote
10422 (or (org-element-property :label-fmt element)
10423 org-coderef-label-format))))
10424 (save-excursion
10425 (beginning-of-line)
10426 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10427 (format label-fmt coderef))))))
10428 (setq type 'dedicated)
10429 (goto-char (match-beginning 1))
10430 (throw :coderef-match nil))))
10431 (goto-char origin)
10432 (error "No match for coderef: %s" coderef))))
10433 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10434 ;; Look for a regular expression.
10435 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10436 (match-string 1 s)))
10437 ;; From here, we handle fuzzy links.
10439 ;; Look for targets, only if not in a headline search.
10440 ((and (not starred)
10441 (let ((target (format "<<%s>>" s-multi-re)))
10442 (catch :target-match
10443 (goto-char (point-min))
10444 (while (re-search-forward target nil t)
10445 (backward-char)
10446 (let ((context (org-element-context)))
10447 (when (eq (org-element-type context) 'target)
10448 (setq type 'dedicated)
10449 (goto-char (org-element-property :begin context))
10450 (throw :target-match t))))
10451 nil))))
10452 ;; Look for elements named after S, only if not in a headline
10453 ;; search.
10454 ((and (not starred)
10455 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10456 (catch :name-match
10457 (goto-char (point-min))
10458 (while (re-search-forward name nil t)
10459 (let ((element (org-element-at-point)))
10460 (when (equal words
10461 (split-string
10462 (org-element-property :name element)))
10463 (setq type 'dedicated)
10464 (beginning-of-line)
10465 (throw :name-match t))))
10466 nil))))
10467 ;; Regular text search. Prefer headlines in Org mode buffers.
10468 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10469 ;; statistics cookies and tags.
10470 ((and (derived-mode-p 'org-mode)
10471 (let ((title-re
10472 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10473 org-outline-regexp-bol
10474 org-comment-string
10475 (mapconcat #'regexp-quote words ".+")))
10476 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10477 (comment-re (eval-when-compile
10478 (format "\\`%s[ \t]+" org-comment-string))))
10479 (goto-char (point-min))
10480 (catch :found
10481 (while (re-search-forward title-re nil t)
10482 (when (equal words
10483 (split-string
10484 (replace-regexp-in-string
10485 cookie-re ""
10486 (replace-regexp-in-string
10487 comment-re "" (org-get-heading t t t)))))
10488 (throw :found t)))
10489 nil)))
10490 (beginning-of-line)
10491 (setq type 'dedicated))
10492 ;; Offer to create non-existent headline depending on
10493 ;; `org-link-search-must-match-exact-headline'.
10494 ((and (derived-mode-p 'org-mode)
10495 (not org-link-search-inhibit-query)
10496 (eq org-link-search-must-match-exact-headline 'query-to-create)
10497 (yes-or-no-p "No match - create this as a new heading? "))
10498 (goto-char (point-max))
10499 (unless (bolp) (newline))
10500 (org-insert-heading nil t t)
10501 (insert s "\n")
10502 (beginning-of-line 0))
10503 ;; Only headlines are looked after. No need to process
10504 ;; further: throw an error.
10505 ((and (derived-mode-p 'org-mode)
10506 (or starred org-link-search-must-match-exact-headline))
10507 (goto-char origin)
10508 (error "No match for fuzzy expression: %s" normalized))
10509 ;; Regular text search.
10510 ((catch :fuzzy-match
10511 (goto-char (point-min))
10512 (while (re-search-forward s-multi-re nil t)
10513 ;; Skip match if it contains AVOID-POS or it is included in
10514 ;; a link with a description but outside the description.
10515 (unless (or (and avoid-pos
10516 (<= (match-beginning 0) avoid-pos)
10517 (> (match-end 0) avoid-pos))
10518 (and (save-match-data
10519 (org-in-regexp org-bracket-link-regexp))
10520 (match-beginning 3)
10521 (or (> (match-beginning 3) (point))
10522 (<= (match-end 3) (point)))
10523 (org-element-lineage
10524 (save-match-data (org-element-context))
10525 '(link) t)))
10526 (goto-char (match-beginning 0))
10527 (setq type 'fuzzy)
10528 (throw :fuzzy-match t)))
10529 nil))
10530 ;; All failed. Throw an error.
10531 (t (goto-char origin)
10532 (error "No match for fuzzy expression: %s" normalized)))
10533 ;; Disclose surroundings of match, if appropriate.
10534 (when (and (derived-mode-p 'org-mode) (not stealth))
10535 (org-show-context 'link-search))
10536 type))
10538 (defun org-get-buffer-for-internal-link (buffer)
10539 "Return a buffer to be used for displaying the link target of internal links."
10540 (cond
10541 ((not org-display-internal-link-with-indirect-buffer)
10542 buffer)
10543 ((string-suffix-p "(Clone)" (buffer-name buffer))
10544 (message "Buffer is already a clone, not making another one")
10545 ;; we also do not modify visibility in this case
10546 buffer)
10547 (t ; make a new indirect buffer for displaying the link
10548 (let* ((bn (buffer-name buffer))
10549 (ibn (concat bn "(Clone)"))
10550 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10551 (with-current-buffer ib (org-overview))
10552 ib))))
10554 (defun org-do-occur (regexp &optional cleanup)
10555 "Call the Emacs command `occur'.
10556 If CLEANUP is non-nil, remove the printout of the regular expression
10557 in the *Occur* buffer. This is useful if the regex is long and not useful
10558 to read."
10559 (occur regexp)
10560 (when cleanup
10561 (let ((cwin (selected-window)) win beg end)
10562 (when (setq win (get-buffer-window "*Occur*"))
10563 (select-window win))
10564 (goto-char (point-min))
10565 (when (re-search-forward "match[a-z]+" nil t)
10566 (setq beg (match-end 0))
10567 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10568 (setq end (1- (match-beginning 0)))))
10569 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10570 (goto-char (point-min))
10571 (select-window cwin))))
10574 ;;; The Mark Ring
10576 (defvar org-mark-ring nil
10577 "Mark ring for positions before jumps in Org mode.")
10579 (defvar org-mark-ring-last-goto nil
10580 "Last position in the mark ring used to go back.")
10582 ;; Fill and close the ring
10583 (setq org-mark-ring nil)
10584 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10586 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10587 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10588 org-mark-ring)
10590 (defun org-mark-ring-push (&optional pos buffer)
10591 "Put the current position into the mark ring and rotate it.
10592 Also push position into the Emacs mark ring. If optional
10593 argument POS and BUFFER are not nil, mark this location instead."
10594 (interactive)
10595 (let ((pos (or pos (point)))
10596 (buffer (or buffer (current-buffer))))
10597 (with-current-buffer buffer
10598 (org-with-point-at pos (push-mark nil t)))
10599 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10600 (move-marker (car org-mark-ring) pos buffer))
10601 (message
10602 (substitute-command-keys
10603 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10605 (defun org-mark-ring-goto (&optional n)
10606 "Jump to the previous position in the mark ring.
10607 With prefix arg N, jump back that many stored positions. When
10608 called several times in succession, walk through the entire ring.
10609 Org mode commands jumping to a different position in the current file,
10610 or to another Org file, automatically push the old position onto the ring."
10611 (interactive "p")
10612 (let (p m)
10613 (if (eq last-command this-command)
10614 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10615 (setq p org-mark-ring))
10616 (setq org-mark-ring-last-goto p)
10617 (setq m (car p))
10618 (pop-to-buffer-same-window (marker-buffer m))
10619 (goto-char m)
10620 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10622 (defun org-add-angle-brackets (s)
10623 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10624 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10627 ;;; Following specific links
10629 (defvar org-agenda-buffer-tmp-name)
10630 (defvar org-agenda-start-on-weekday)
10631 (defun org-follow-timestamp-link ()
10632 "Open an agenda view for the time-stamp date/range at point."
10633 (cond
10634 ((org-at-date-range-p t)
10635 (let ((org-agenda-start-on-weekday)
10636 (t1 (match-string 1))
10637 (t2 (match-string 2)) tt1 tt2)
10638 (setq tt1 (time-to-days (org-time-string-to-time t1))
10639 tt2 (time-to-days (org-time-string-to-time t2)))
10640 (let ((org-agenda-buffer-tmp-name
10641 (format "*Org Agenda(a:%s)"
10642 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10643 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10644 ((org-at-timestamp-p 'lax)
10645 (let ((org-agenda-buffer-tmp-name
10646 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10647 (org-agenda-list nil (time-to-days (org-time-string-to-time
10648 (substring (match-string 1) 0 10)))
10649 1)))
10650 (t (error "This should not happen"))))
10653 ;;; Following file links
10654 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10655 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10656 (declare-function mailcap-mime-info
10657 "mailcap" (string &optional request no-decode))
10658 (defvar org-wait nil)
10659 (defun org-open-file (path &optional in-emacs line search)
10660 "Open the file at PATH.
10661 First, this expands any special file name abbreviations. Then the
10662 configuration variable `org-file-apps' is checked if it contains an
10663 entry for this file type, and if yes, the corresponding command is launched.
10665 If no application is found, Emacs simply visits the file.
10667 With optional prefix argument IN-EMACS, Emacs will visit the file.
10668 With a double \\[universal-argument] \\[universal-argument] \
10669 prefix arg, Org tries to avoid opening in Emacs
10670 and to use an external application to visit the file.
10672 Optional LINE specifies a line to go to, optional SEARCH a string
10673 to search for. If LINE or SEARCH is given, the file will be
10674 opened in Emacs, unless an entry from org-file-apps that makes
10675 use of groups in a regexp matches.
10677 If you want to change the way frames are used when following a
10678 link, please customize `org-link-frame-setup'.
10680 If the file does not exist, an error is thrown."
10681 (let* ((file (if (equal path "")
10682 buffer-file-name
10683 (substitute-in-file-name (expand-file-name path))))
10684 (file-apps (append org-file-apps (org-default-apps)))
10685 (apps (cl-remove-if
10686 'org-file-apps-entry-match-against-dlink-p file-apps))
10687 (apps-dlink (cl-remove-if-not
10688 'org-file-apps-entry-match-against-dlink-p file-apps))
10689 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10690 (dirp (unless remp (file-directory-p file)))
10691 (file (if (and dirp org-open-directory-means-index-dot-org)
10692 (concat (file-name-as-directory file) "index.org")
10693 file))
10694 (a-m-a-p (assq 'auto-mode apps))
10695 (dfile (downcase file))
10696 ;; Reconstruct the original link from the PATH, LINE and
10697 ;; SEARCH args.
10698 (link (cond (line (concat file "::" (number-to-string line)))
10699 (search (concat file "::" search))
10700 (t file)))
10701 (dlink (downcase link))
10702 (ext
10703 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10704 (match-string 1 dfile)))
10705 (save-position-maybe
10706 (let ((old-buffer (current-buffer))
10707 (old-pos (point))
10708 (old-mode major-mode))
10709 (lambda ()
10710 (and (derived-mode-p 'org-mode)
10711 (eq old-mode 'org-mode)
10712 (or (not (eq old-buffer (current-buffer)))
10713 (not (eq old-pos (point))))
10714 (org-mark-ring-push old-pos old-buffer)))))
10715 cmd link-match-data)
10716 (cond
10717 ((member in-emacs '((16) system))
10718 (setq cmd (cdr (assq 'system apps))))
10719 (in-emacs (setq cmd 'emacs))
10721 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10722 (and dirp (cdr (assq 'directory apps)))
10723 ;; First, try matching against apps-dlink if we
10724 ;; get a match here, store the match data for
10725 ;; later.
10726 (let ((match (assoc-default dlink apps-dlink
10727 'string-match)))
10728 (if match
10729 (progn (setq link-match-data (match-data))
10730 match)
10731 (progn (setq in-emacs (or in-emacs line search))
10732 nil))) ; if we have no match in apps-dlink,
10733 ; always open the file in emacs if line or search
10734 ; is given (for backwards compatibility)
10735 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10736 'string-match)
10737 (cdr (assoc ext apps))
10738 (cdr (assq t apps))))))
10739 (when (eq cmd 'system)
10740 (setq cmd (cdr (assq 'system apps))))
10741 (when (eq cmd 'default)
10742 (setq cmd (cdr (assoc t apps))))
10743 (when (eq cmd 'mailcap)
10744 (require 'mailcap)
10745 (mailcap-parse-mailcaps)
10746 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10747 (command (mailcap-mime-info mime-type)))
10748 (if (stringp command)
10749 (setq cmd command)
10750 (setq cmd 'emacs))))
10751 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10752 (not (file-exists-p file))
10753 (not org-open-non-existing-files))
10754 (user-error "No such file: %s" file))
10755 (cond
10756 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10757 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10758 (while (string-match "['\"]%s['\"]" cmd)
10759 (setq cmd (replace-match "%s" t t cmd)))
10760 (setq cmd (replace-regexp-in-string
10761 "%s"
10762 (shell-quote-argument (convert-standard-filename file))
10764 nil t))
10766 ;; Replace "%1", "%2" etc. in command with group matches from regex
10767 (save-match-data
10768 (let ((match-index 1)
10769 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10770 (set-match-data link-match-data)
10771 (while (<= match-index number-of-groups)
10772 (let ((regex (concat "%" (number-to-string match-index)))
10773 (replace-with (match-string match-index dlink)))
10774 (while (string-match regex cmd)
10775 (setq cmd (replace-match replace-with t t cmd))))
10776 (setq match-index (+ match-index 1)))))
10778 (save-window-excursion
10779 (message "Running %s...done" cmd)
10780 (start-process-shell-command cmd nil cmd)
10781 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10782 ((or (stringp cmd)
10783 (eq cmd 'emacs))
10784 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10785 (widen)
10786 (cond (line (org-goto-line line)
10787 (when (derived-mode-p 'org-mode) (org-reveal)))
10788 (search (condition-case err
10789 (org-link-search search)
10790 ;; Save position before error-ing out so user
10791 ;; can easily move back to the original buffer.
10792 (error (funcall save-position-maybe)
10793 (error (nth 1 err)))))))
10794 ((functionp cmd)
10795 (save-match-data
10796 (set-match-data link-match-data)
10797 (condition-case nil
10798 (funcall cmd file link)
10799 ;; FIXME: Remove this check when most default installations
10800 ;; of Emacs have at least Org 9.0.
10801 ((debug wrong-number-of-arguments wrong-type-argument
10802 invalid-function)
10803 (user-error "Please see Org News for version 9.0 about \
10804 `org-file-apps'--Lisp error: %S" cmd)))))
10805 ((consp cmd)
10806 ;; FIXME: Remove this check when most default installations of
10807 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10808 ;; fall back to `org-link-frame-setup' for an old usage of
10809 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10810 (user-error "Please see Org News for version 9.0 about \
10811 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10812 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10813 (funcall save-position-maybe)))
10815 (defun org-file-apps-entry-match-against-dlink-p (entry)
10816 "This function returns non-nil if `entry' uses a regular
10817 expression which should be matched against the whole link by
10818 org-open-file.
10820 It assumes that is the case when the entry uses a regular
10821 expression which has at least one grouping construct and the
10822 action is either a lisp form or a command string containing
10823 `%1', i.e. using at least one subexpression match as a
10824 parameter."
10825 (let ((selector (car entry))
10826 (action (cdr entry)))
10827 (if (stringp selector)
10828 (and (> (regexp-opt-depth selector) 0)
10829 (or (and (stringp action)
10830 (string-match "%[0-9]" action))
10831 (consp action)))
10832 nil)))
10834 (defun org-default-apps ()
10835 "Return the default applications for this operating system."
10836 (cond
10837 ((eq system-type 'darwin)
10838 org-file-apps-defaults-macosx)
10839 ((eq system-type 'windows-nt)
10840 org-file-apps-defaults-windowsnt)
10841 (t org-file-apps-defaults-gnu)))
10843 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10844 "Convert extensions to regular expressions in the cars of LIST.
10845 Also, weed out any non-string entries, because the return value is used
10846 only for regexp matching.
10847 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10848 point to the symbol `emacs', indicating that the file should
10849 be opened in Emacs."
10850 (append
10851 (delq nil
10852 (mapcar (lambda (x)
10853 (unless (not (stringp (car x)))
10854 (if (string-match "\\W" (car x))
10856 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10857 list))
10858 (when add-auto-mode
10859 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10861 (defvar ange-ftp-name-format)
10862 (defun org-file-remote-p (file)
10863 "Test whether FILE specifies a location on a remote system.
10864 Return non-nil if the location is indeed remote.
10866 For example, the filename \"/user@host:/foo\" specifies a location
10867 on the system \"/user@host:\"."
10868 (cond ((fboundp 'file-remote-p)
10869 (file-remote-p file))
10870 ((fboundp 'tramp-handle-file-remote-p)
10871 (tramp-handle-file-remote-p file))
10872 ((and (boundp 'ange-ftp-name-format)
10873 (string-match (car ange-ftp-name-format) file))
10874 t)))
10877 ;;;; Refiling
10879 (defun org-get-org-file ()
10880 "Read a filename, with default directory `org-directory'."
10881 (let ((default (or org-default-notes-file remember-data-file)))
10882 (read-file-name (format "File name [%s]: " default)
10883 (file-name-as-directory org-directory)
10884 default)))
10886 (defun org-notes-order-reversed-p ()
10887 "Check if the current file should receive notes in reversed order."
10888 (cond
10889 ((not org-reverse-note-order) nil)
10890 ((eq t org-reverse-note-order) t)
10891 ((not (listp org-reverse-note-order)) nil)
10892 (t (catch 'exit
10893 (dolist (entry org-reverse-note-order)
10894 (when (string-match (car entry) buffer-file-name)
10895 (throw 'exit (cdr entry))))))))
10897 (defvar org-refile-target-table nil
10898 "The list of refile targets, created by `org-refile'.")
10900 (defvar org-agenda-new-buffers nil
10901 "Buffers created to visit agenda files.")
10903 (defvar org-refile-cache nil
10904 "Cache for refile targets.")
10906 (defvar org-refile-markers nil
10907 "All the markers used for caching refile locations.")
10909 (defun org-refile-marker (pos)
10910 "Get a new refile marker, but only if caching is in use."
10911 (if (not org-refile-use-cache)
10913 (let ((m (make-marker)))
10914 (move-marker m pos)
10915 (push m org-refile-markers)
10916 m)))
10918 (defun org-refile-cache-clear ()
10919 "Clear the refile cache and disable all the markers."
10920 (dolist (m org-refile-markers) (move-marker m nil))
10921 (setq org-refile-markers nil)
10922 (setq org-refile-cache nil)
10923 (message "Refile cache has been cleared"))
10925 (defun org-refile-cache-check-set (set)
10926 "Check if all the markers in the cache still have live buffers."
10927 (let (marker)
10928 (catch 'exit
10929 (while (and set (setq marker (nth 3 (pop set))))
10930 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10931 (when (and marker (null (marker-buffer marker)))
10932 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10933 (sit-for 3)
10934 (throw 'exit nil)))
10935 t)))
10937 (defun org-refile-cache-put (set &rest identifiers)
10938 "Push the refile targets SET into the cache, under IDENTIFIERS."
10939 (let* ((key (sha1 (prin1-to-string identifiers)))
10940 (entry (assoc key org-refile-cache)))
10941 (if entry
10942 (setcdr entry set)
10943 (push (cons key set) org-refile-cache))))
10945 (defun org-refile-cache-get (&rest identifiers)
10946 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10947 (cond
10948 ((not org-refile-cache) nil)
10949 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10951 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10952 org-refile-cache))))
10953 (and set (org-refile-cache-check-set set) set)))))
10955 (defvar org-outline-path-cache nil
10956 "Alist between buffer positions and outline paths.
10957 It value is an alist (POSITION . PATH) where POSITION is the
10958 buffer position at the beginning of an entry and PATH is a list
10959 of strings describing the outline path for that entry, in reverse
10960 order.")
10962 (defun org-refile-get-targets (&optional default-buffer)
10963 "Produce a table with refile targets."
10964 (let ((case-fold-search nil)
10965 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10966 (entries (or org-refile-targets '((nil . (:level . 1)))))
10967 targets tgs files desc descre)
10968 (message "Getting targets...")
10969 (with-current-buffer (or default-buffer (current-buffer))
10970 (dolist (entry entries)
10971 (setq files (car entry) desc (cdr entry))
10972 (cond
10973 ((null files) (setq files (list (current-buffer))))
10974 ((eq files 'org-agenda-files)
10975 (setq files (org-agenda-files 'unrestricted)))
10976 ((and (symbolp files) (fboundp files))
10977 (setq files (funcall files)))
10978 ((and (symbolp files) (boundp files))
10979 (setq files (symbol-value files))))
10980 (when (stringp files) (setq files (list files)))
10981 (cond
10982 ((eq (car desc) :tag)
10983 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10984 ((eq (car desc) :todo)
10985 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10986 ((eq (car desc) :regexp)
10987 (setq descre (cdr desc)))
10988 ((eq (car desc) :level)
10989 (setq descre (concat "^\\*\\{" (number-to-string
10990 (if org-odd-levels-only
10991 (1- (* 2 (cdr desc)))
10992 (cdr desc)))
10993 "\\}[ \t]")))
10994 ((eq (car desc) :maxlevel)
10995 (setq descre (concat "^\\*\\{1," (number-to-string
10996 (if org-odd-levels-only
10997 (1- (* 2 (cdr desc)))
10998 (cdr desc)))
10999 "\\}[ \t]")))
11000 (t (error "Bad refiling target description %s" desc)))
11001 (dolist (f files)
11002 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11004 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11005 (progn
11006 (when (bufferp f)
11007 (setq f (buffer-file-name (buffer-base-buffer f))))
11008 (setq f (and f (expand-file-name f)))
11009 (when (eq org-refile-use-outline-path 'file)
11010 (push (list (file-name-nondirectory f) f nil nil) tgs))
11011 (when (eq org-refile-use-outline-path 'buffer-name)
11012 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11013 (when (eq org-refile-use-outline-path 'full-file-path)
11014 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11015 (org-with-wide-buffer
11016 (goto-char (point-min))
11017 (setq org-outline-path-cache nil)
11018 (while (re-search-forward descre nil t)
11019 (beginning-of-line)
11020 (let ((case-fold-search nil))
11021 (looking-at org-complex-heading-regexp))
11022 (let ((begin (point))
11023 (heading (match-string-no-properties 4)))
11024 (unless (or (and
11025 org-refile-target-verify-function
11026 (not
11027 (funcall org-refile-target-verify-function)))
11028 (not heading))
11029 (let ((re (format org-complex-heading-regexp-format
11030 (regexp-quote heading)))
11031 (target
11032 (if (not org-refile-use-outline-path) heading
11033 (mapconcat
11034 #'identity
11035 (append
11036 (pcase org-refile-use-outline-path
11037 (`file (list (file-name-nondirectory
11038 (buffer-file-name
11039 (buffer-base-buffer)))))
11040 (`full-file-path
11041 (list (buffer-file-name
11042 (buffer-base-buffer))))
11043 (`buffer-name
11044 (list (buffer-name
11045 (buffer-base-buffer))))
11046 (_ nil))
11047 (mapcar (lambda (s) (replace-regexp-in-string
11048 "/" "\\/" s nil t))
11049 (org-get-outline-path t t)))
11050 "/"))))
11051 (push (list target f re (org-refile-marker (point)))
11052 tgs)))
11053 (when (= (point) begin)
11054 ;; Verification function has not moved point.
11055 (end-of-line)))))))
11056 (when org-refile-use-cache
11057 (org-refile-cache-put tgs (buffer-file-name) descre))
11058 (setq targets (append tgs targets))))))
11059 (message "Getting targets...done")
11060 (delete-dups (nreverse targets))))
11062 (defun org--get-outline-path-1 (&optional use-cache)
11063 "Return outline path to current headline.
11065 Outline path is a list of strings, in reverse order. When
11066 optional argument USE-CACHE is non-nil, make use of a cache. See
11067 `org-get-outline-path' for details.
11069 Assume buffer is widened and point is on a headline."
11070 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11071 (let ((p (point))
11072 (heading (let ((case-fold-search nil))
11073 (looking-at org-complex-heading-regexp)
11074 (if (not (match-end 4)) ""
11075 ;; Remove statistics cookies.
11076 (org-trim
11077 (org-link-display-format
11078 (replace-regexp-in-string
11079 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11080 (match-string-no-properties 4))))))))
11081 (if (org-up-heading-safe)
11082 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11083 (when use-cache
11084 (push (cons p path) org-outline-path-cache))
11085 path)
11086 ;; This is a new root node. Since we assume we are moving
11087 ;; forward, we can drop previous cache so as to limit number
11088 ;; of associations there.
11089 (let ((path (list heading)))
11090 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11091 path)))))
11093 (defun org-get-outline-path (&optional with-self use-cache)
11094 "Return the outline path to the current entry.
11096 An outline path is a list of ancestors for current headline, as
11097 a list of strings. Statistics cookies are removed and links are
11098 replaced with their description, if any, or their path otherwise.
11100 When optional argument WITH-SELF is non-nil, the path also
11101 includes the current headline.
11103 When optional argument USE-CACHE is non-nil, cache outline paths
11104 between calls to this function so as to avoid backtracking. This
11105 argument is useful when planning to find more than one outline
11106 path in the same document. In that case, there are two
11107 conditions to satisfy:
11108 - `org-outline-path-cache' is set to nil before starting the
11109 process;
11110 - outline paths are computed by increasing buffer positions."
11111 (org-with-wide-buffer
11112 (and (or (and with-self (org-back-to-heading t))
11113 (org-up-heading-safe))
11114 (reverse (org--get-outline-path-1 use-cache)))))
11116 (defun org-format-outline-path (path &optional width prefix separator)
11117 "Format the outline path PATH for display.
11118 WIDTH is the maximum number of characters that is available.
11119 PREFIX is a prefix to be included in the returned string,
11120 such as the file name.
11121 SEPARATOR is inserted between the different parts of the path,
11122 the default is \"/\"."
11123 (setq width (or width 79))
11124 (setq path (delq nil path))
11125 (unless (> width 0)
11126 (user-error "Argument `width' must be positive"))
11127 (setq separator (or separator "/"))
11128 (let* ((org-odd-levels-only nil)
11129 (fpath (concat
11130 prefix (and prefix path separator)
11131 (mapconcat
11132 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11133 (cl-loop for head in path
11134 for n from 0
11135 collect (org-add-props
11136 head nil 'face
11137 (nth (% n org-n-level-faces) org-level-faces)))
11138 separator))))
11139 (when (> (length fpath) width)
11140 (if (< width 7)
11141 ;; It's unlikely that `width' will be this small, but don't
11142 ;; waste characters by adding ".." if it is.
11143 (setq fpath (substring fpath 0 width))
11144 (setf (substring fpath (- width 2)) "..")))
11145 fpath))
11147 (defun org-display-outline-path (&optional file current separator just-return-string)
11148 "Display the current outline path in the echo area.
11150 If FILE is non-nil, prepend the output with the file name.
11151 If CURRENT is non-nil, append the current heading to the output.
11152 SEPARATOR is passed through to `org-format-outline-path'. It separates
11153 the different parts of the path and defaults to \"/\".
11154 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11155 (interactive "P")
11156 (let* (case-fold-search
11157 (bfn (buffer-file-name (buffer-base-buffer)))
11158 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11159 res)
11160 (when current (setq path (append path
11161 (save-excursion
11162 (org-back-to-heading t)
11163 (when (looking-at org-complex-heading-regexp)
11164 (list (match-string 4)))))))
11165 (setq res
11166 (org-format-outline-path
11167 path
11168 (1- (frame-width))
11169 (and file bfn (concat (file-name-nondirectory bfn) separator))
11170 separator))
11171 (if just-return-string
11172 (org-no-properties res)
11173 (org-unlogged-message "%s" res))))
11175 (defvar org-refile-history nil
11176 "History for refiling operations.")
11178 (defvar org-after-refile-insert-hook nil
11179 "Hook run after `org-refile' has inserted its stuff at the new location.
11180 Note that this is still *before* the stuff will be removed from
11181 the *old* location.")
11183 (defvar org-capture-last-stored-marker)
11184 (defvar org-refile-keep nil
11185 "Non-nil means `org-refile' will copy instead of refile.")
11187 (defun org-copy ()
11188 "Like `org-refile', but copy."
11189 (interactive)
11190 (let ((org-refile-keep t))
11191 (funcall 'org-refile nil nil nil "Copy")))
11193 (defun org-refile (&optional arg default-buffer rfloc msg)
11194 "Move the entry or entries at point to another heading.
11196 The list of target headings is compiled using the information in
11197 `org-refile-targets', which see.
11199 At the target location, the entry is filed as a subitem of the
11200 target heading. Depending on `org-reverse-note-order', the new
11201 subitem will either be the first or the last subitem.
11203 If there is an active region, all entries in that region will be
11204 refiled. However, the region must fulfill the requirement that
11205 the first heading sets the top-level of the moved text.
11207 With a `\\[universal-argument]' ARG, the command will only visit the target \
11208 location
11209 and not actually move anything.
11211 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11212 location where the last
11213 refiling operation has put the subtree.
11215 With a numeric prefix argument of `2', refile to the running clock.
11217 With a numeric prefix argument of `3', emulate `org-refile-keep'
11218 being set to t and copy to the target location, don't move it.
11219 Beware that keeping refiled entries may result in duplicated ID
11220 properties.
11222 RFLOC can be a refile location obtained in a different way.
11224 MSG is a string to replace \"Refile\" in the default prompt with
11225 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11227 See also `org-refile-use-outline-path'.
11229 If you are using target caching (see `org-refile-use-cache'), you
11230 have to clear the target cache in order to find new targets.
11231 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11232 prefix argument (`C-u C-u C-u C-c C-w')."
11233 (interactive "P")
11234 (if (member arg '(0 (64)))
11235 (org-refile-cache-clear)
11236 (let* ((actionmsg (cond (msg msg)
11237 ((equal arg 3) "Refile (and keep)")
11238 (t "Refile")))
11239 (regionp (org-region-active-p))
11240 (region-start (and regionp (region-beginning)))
11241 (region-end (and regionp (region-end)))
11242 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11243 pos it nbuf file level reversed)
11244 (setq last-command nil)
11245 (when regionp
11246 (goto-char region-start)
11247 (or (bolp) (goto-char (point-at-bol)))
11248 (setq region-start (point))
11249 (unless (or (org-kill-is-subtree-p
11250 (buffer-substring region-start region-end))
11251 (prog1 org-refile-active-region-within-subtree
11252 (let ((s (point-at-eol)))
11253 (org-toggle-heading)
11254 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11255 (user-error "The region is not a (sequence of) subtree(s)")))
11256 (if (equal arg '(16))
11257 (org-refile-goto-last-stored)
11258 (when (or
11259 (and (equal arg 2)
11260 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11261 (prog1
11262 (setq it (list (or org-clock-heading "running clock")
11263 (buffer-file-name
11264 (marker-buffer org-clock-hd-marker))
11266 (marker-position org-clock-hd-marker)))
11267 (setq arg nil)))
11268 (setq it
11269 (or rfloc
11270 (let (heading-text)
11271 (save-excursion
11272 (unless (and arg (listp arg))
11273 (org-back-to-heading t)
11274 (setq heading-text
11275 (replace-regexp-in-string
11276 org-bracket-link-regexp
11277 "\\3"
11278 (or (nth 4 (org-heading-components))
11279 ""))))
11280 (org-refile-get-location
11281 (cond ((and arg (listp arg)) "Goto")
11282 (regionp (concat actionmsg " region to"))
11283 (t (concat actionmsg " subtree \""
11284 heading-text "\" to")))
11285 default-buffer
11286 (and (not (equal '(4) arg))
11287 org-refile-allow-creating-parent-nodes)))))))
11288 (setq file (nth 1 it)
11289 pos (nth 3 it))
11290 (when (and (not arg)
11292 (equal (buffer-file-name) file)
11293 (if regionp
11294 (and (>= pos region-start)
11295 (<= pos region-end))
11296 (and (>= pos (point))
11297 (< pos (save-excursion
11298 (org-end-of-subtree t t))))))
11299 (error "Cannot refile to position inside the tree or region"))
11300 (setq nbuf (or (find-buffer-visiting file)
11301 (find-file-noselect file)))
11302 (if (and arg (not (equal arg 3)))
11303 (progn
11304 (pop-to-buffer-same-window nbuf)
11305 (goto-char (cond (pos)
11306 ((org-notes-order-reversed-p) (point-min))
11307 (t (point-max))))
11308 (org-show-context 'org-goto))
11309 (if regionp
11310 (progn
11311 (org-kill-new (buffer-substring region-start region-end))
11312 (org-save-markers-in-region region-start region-end))
11313 (org-copy-subtree 1 nil t))
11314 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11315 (find-file-noselect file)))
11316 (setq reversed (org-notes-order-reversed-p))
11317 (org-with-wide-buffer
11318 (if pos
11319 (progn
11320 (goto-char pos)
11321 (setq level (org-get-valid-level (funcall outline-level) 1))
11322 (goto-char
11323 (if reversed
11324 (or (outline-next-heading) (point-max))
11325 (or (save-excursion (org-get-next-sibling))
11326 (org-end-of-subtree t t)
11327 (point-max)))))
11328 (setq level 1)
11329 (if (not reversed)
11330 (goto-char (point-max))
11331 (goto-char (point-min))
11332 (or (outline-next-heading) (goto-char (point-max)))))
11333 (unless (bolp) (newline))
11334 (org-paste-subtree level nil nil t)
11335 (when org-log-refile
11336 (org-add-log-setup 'refile nil nil org-log-refile)
11337 (unless (eq org-log-refile 'note)
11338 (save-excursion (org-add-log-note))))
11339 (and org-auto-align-tags
11340 (let ((org-loop-over-headlines-in-active-region nil))
11341 (org-align-tags)))
11342 (let ((bookmark-name (plist-get org-bookmark-names-plist
11343 :last-refile)))
11344 (when bookmark-name
11345 (with-demoted-errors
11346 (bookmark-set bookmark-name))))
11347 ;; If we are refiling for capture, make sure that the
11348 ;; last-capture pointers point here
11349 (when (bound-and-true-p org-capture-is-refiling)
11350 (let ((bookmark-name (plist-get org-bookmark-names-plist
11351 :last-capture-marker)))
11352 (when bookmark-name
11353 (with-demoted-errors
11354 (bookmark-set bookmark-name))))
11355 (move-marker org-capture-last-stored-marker (point)))
11356 (when (fboundp 'deactivate-mark) (deactivate-mark))
11357 (run-hooks 'org-after-refile-insert-hook)))
11358 (unless org-refile-keep
11359 (if regionp
11360 (delete-region (point) (+ (point) (- region-end region-start)))
11361 (org-preserve-local-variables
11362 (delete-region
11363 (and (org-back-to-heading t) (point))
11364 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11365 (when (featurep 'org-inlinetask)
11366 (org-inlinetask-remove-END-maybe))
11367 (setq org-markers-to-move nil)
11368 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11370 (defun org-refile-goto-last-stored ()
11371 "Go to the location where the last refile was stored."
11372 (interactive)
11373 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11374 (message "This is the location of the last refile"))
11376 (defun org-refile--get-location (refloc tbl)
11377 "When user refile to REFLOC, find the associated target in TBL.
11378 Also check `org-refile-target-table'."
11379 (car (delq
11381 (mapcar
11382 (lambda (r) (or (assoc r tbl)
11383 (assoc r org-refile-target-table)))
11384 (list (replace-regexp-in-string "/$" "" refloc)
11385 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11387 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11388 "Prompt the user for a refile location, using PROMPT.
11389 PROMPT should not be suffixed with a colon and a space, because
11390 this function appends the default value from
11391 `org-refile-history' automatically, if that is not empty."
11392 (let ((org-refile-targets org-refile-targets)
11393 (org-refile-use-outline-path org-refile-use-outline-path))
11394 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11395 (unless org-refile-target-table
11396 (user-error "No refile targets"))
11397 (let* ((cbuf (current-buffer))
11398 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11399 (cfunc (if (and org-refile-use-outline-path
11400 org-outline-path-complete-in-steps)
11401 #'org-olpath-completing-read
11402 #'completing-read))
11403 (extra (if org-refile-use-outline-path "/" ""))
11404 (cbnex (concat (buffer-name) extra))
11405 (filename (and cfn (expand-file-name cfn)))
11406 (tbl (mapcar
11407 (lambda (x)
11408 (if (and (not (member org-refile-use-outline-path
11409 '(file full-file-path)))
11410 (not (equal filename (nth 1 x))))
11411 (cons (concat (car x) extra " ("
11412 (file-name-nondirectory (nth 1 x)) ")")
11413 (cdr x))
11414 (cons (concat (car x) extra) (cdr x))))
11415 org-refile-target-table))
11416 (completion-ignore-case t)
11417 cdef
11418 (prompt (concat prompt
11419 (or (and (car org-refile-history)
11420 (concat " (default " (car org-refile-history) ")"))
11421 (and (assoc cbnex tbl) (setq cdef cbnex)
11422 (concat " (default " cbnex ")"))) ": "))
11423 pa answ parent-target child parent old-hist)
11424 (setq old-hist org-refile-history)
11425 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11426 nil 'org-refile-history (or cdef (car org-refile-history))))
11427 (if (setq pa (org-refile--get-location answ tbl))
11428 (progn
11429 (org-refile-check-position pa)
11430 (when (or (not org-refile-history)
11431 (not (eq old-hist org-refile-history))
11432 (not (equal (car pa) (car org-refile-history))))
11433 (setq org-refile-history
11434 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11435 org-refile-history
11436 (cdr org-refile-history))))
11437 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11438 (pop org-refile-history)))
11440 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11441 (progn
11442 (setq parent (match-string 1 answ)
11443 child (match-string 2 answ))
11444 (setq parent-target (org-refile--get-location parent tbl))
11445 (when (and parent-target
11446 (or (eq new-nodes t)
11447 (and (eq new-nodes 'confirm)
11448 (y-or-n-p (format "Create new node \"%s\"? "
11449 child)))))
11450 (org-refile-new-child parent-target child)))
11451 (user-error "Invalid target location")))))
11453 (declare-function org-string-nw-p "org-macs" (s))
11454 (defun org-refile-check-position (refile-pointer)
11455 "Check if the refile pointer matches the headline to which it points."
11456 (let* ((file (nth 1 refile-pointer))
11457 (re (nth 2 refile-pointer))
11458 (pos (nth 3 refile-pointer))
11459 buffer)
11460 (if (and (not (markerp pos)) (not file))
11461 (user-error "Please indicate a target file in the refile path")
11462 (when (org-string-nw-p re)
11463 (setq buffer (if (markerp pos)
11464 (marker-buffer pos)
11465 (or (find-buffer-visiting file)
11466 (find-file-noselect file))))
11467 (with-current-buffer buffer
11468 (org-with-wide-buffer
11469 (goto-char pos)
11470 (beginning-of-line 1)
11471 (unless (looking-at-p re)
11472 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11474 (defun org-refile-new-child (parent-target child)
11475 "Use refile target PARENT-TARGET to add new CHILD below it."
11476 (unless parent-target
11477 (error "Cannot find parent for new node"))
11478 (let ((file (nth 1 parent-target))
11479 (pos (nth 3 parent-target))
11480 level)
11481 (with-current-buffer (or (find-buffer-visiting file)
11482 (find-file-noselect file))
11483 (org-with-wide-buffer
11484 (if pos
11485 (goto-char pos)
11486 (goto-char (point-max))
11487 (unless (bolp) (newline)))
11488 (when (looking-at org-outline-regexp)
11489 (setq level (funcall outline-level))
11490 (org-end-of-subtree t t))
11491 (org-back-over-empty-lines)
11492 (insert "\n" (make-string
11493 (if pos (org-get-valid-level level 1) 1) ?*)
11494 " " child "\n")
11495 (beginning-of-line 0)
11496 (list (concat (car parent-target) "/" child) file "" (point))))))
11498 (defun org-olpath-completing-read (prompt collection &rest args)
11499 "Read an outline path like a file name."
11500 (let ((thetable collection))
11501 (apply #'completing-read
11502 prompt
11503 (lambda (string predicate &optional flag)
11504 (cond
11505 ((eq flag nil) (try-completion string thetable))
11506 ((eq flag t)
11507 (let ((l (length string)))
11508 (mapcar (lambda (x)
11509 (let ((r (substring x l))
11510 (f (if (string-match " ([^)]*)$" x)
11511 (match-string 0 x)
11512 "")))
11513 (if (string-match "/" r)
11514 (concat string (substring r 0 (match-end 0)) f)
11515 x)))
11516 (all-completions string thetable predicate))))
11517 ;; Exact match?
11518 ((eq flag 'lambda) (assoc string thetable))))
11519 args)))
11521 ;;;; Dynamic blocks
11523 (defun org-find-dblock (name)
11524 "Find the first dynamic block with name NAME in the buffer.
11525 If not found, stay at current position and return nil."
11526 (let ((case-fold-search t) pos)
11527 (save-excursion
11528 (goto-char (point-min))
11529 (setq pos (and (re-search-forward
11530 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11531 (match-beginning 0))))
11532 (when pos (goto-char pos))
11533 pos))
11535 (defun org-create-dblock (plist)
11536 "Create a dynamic block section, with parameters taken from PLIST.
11537 PLIST must contain a :name entry which is used as the name of the block."
11538 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11539 (end-of-line 1)
11540 (newline))
11541 (let ((col (current-column))
11542 (name (plist-get plist :name)))
11543 (insert "#+BEGIN: " name)
11544 (while plist
11545 (if (eq (car plist) :name)
11546 (setq plist (cddr plist))
11547 (insert " " (prin1-to-string (pop plist)))))
11548 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11549 (beginning-of-line -2)))
11551 (defun org-prepare-dblock ()
11552 "Prepare dynamic block for refresh.
11553 This empties the block, puts the cursor at the insert position and returns
11554 the property list including an extra property :name with the block name."
11555 (unless (looking-at org-dblock-start-re)
11556 (user-error "Not at a dynamic block"))
11557 (let* ((begdel (1+ (match-end 0)))
11558 (name (org-no-properties (match-string 1)))
11559 (params (append (list :name name)
11560 (read (concat "(" (match-string 3) ")")))))
11561 (save-excursion
11562 (beginning-of-line 1)
11563 (skip-chars-forward " \t")
11564 (setq params (plist-put params :indentation-column (current-column))))
11565 (unless (re-search-forward org-dblock-end-re nil t)
11566 (error "Dynamic block not terminated"))
11567 (setq params
11568 (append params
11569 (list :content (buffer-substring
11570 begdel (match-beginning 0)))))
11571 (delete-region begdel (match-beginning 0))
11572 (goto-char begdel)
11573 (open-line 1)
11574 params))
11576 (defun org-map-dblocks (&optional command)
11577 "Apply COMMAND to all dynamic blocks in the current buffer.
11578 If COMMAND is not given, use `org-update-dblock'."
11579 (let ((cmd (or command 'org-update-dblock)))
11580 (save-excursion
11581 (goto-char (point-min))
11582 (while (re-search-forward org-dblock-start-re nil t)
11583 (goto-char (match-beginning 0))
11584 (save-excursion
11585 (condition-case nil
11586 (funcall cmd)
11587 (error (message "Error during update of dynamic block"))))
11588 (unless (re-search-forward org-dblock-end-re nil t)
11589 (error "Dynamic block not terminated"))))))
11591 (defun org-dblock-update (&optional arg)
11592 "User command for updating dynamic blocks.
11593 Update the dynamic block at point. With prefix ARG, update all dynamic
11594 blocks in the buffer."
11595 (interactive "P")
11596 (if arg
11597 (org-update-all-dblocks)
11598 (or (looking-at org-dblock-start-re)
11599 (org-beginning-of-dblock))
11600 (org-update-dblock)))
11602 (defun org-update-dblock ()
11603 "Update the dynamic block at point.
11604 This means to empty the block, parse for parameters and then call
11605 the correct writing function."
11606 (interactive)
11607 (save-excursion
11608 (let* ((win (selected-window))
11609 (pos (point))
11610 (line (org-current-line))
11611 (params (org-prepare-dblock))
11612 (name (plist-get params :name))
11613 (indent (plist-get params :indentation-column))
11614 (cmd (intern (concat "org-dblock-write:" name))))
11615 (message "Updating dynamic block `%s' at line %d..." name line)
11616 (funcall cmd params)
11617 (message "Updating dynamic block `%s' at line %d...done" name line)
11618 (goto-char pos)
11619 (when (and indent (> indent 0))
11620 (setq indent (make-string indent ?\ ))
11621 (save-excursion
11622 (select-window win)
11623 (org-beginning-of-dblock)
11624 (forward-line 1)
11625 (while (not (looking-at org-dblock-end-re))
11626 (insert indent)
11627 (beginning-of-line 2))
11628 (when (looking-at org-dblock-end-re)
11629 (and (looking-at "[ \t]+")
11630 (replace-match ""))
11631 (insert indent)))))))
11633 (defun org-beginning-of-dblock ()
11634 "Find the beginning of the dynamic block at point.
11635 Error if there is no such block at point."
11636 (let ((pos (point))
11637 beg)
11638 (end-of-line 1)
11639 (if (and (re-search-backward org-dblock-start-re nil t)
11640 (setq beg (match-beginning 0))
11641 (re-search-forward org-dblock-end-re nil t)
11642 (> (match-end 0) pos))
11643 (goto-char beg)
11644 (goto-char pos)
11645 (error "Not in a dynamic block"))))
11647 (defun org-update-all-dblocks ()
11648 "Update all dynamic blocks in the buffer.
11649 This function can be used in a hook."
11650 (interactive)
11651 (when (derived-mode-p 'org-mode)
11652 (org-map-dblocks 'org-update-dblock)))
11655 ;;;; Completion
11657 (declare-function org-export-backend-options "ox" (cl-x) t)
11658 (defun org-get-export-keywords ()
11659 "Return a list of all currently understood export keywords.
11660 Export keywords include options, block names, attributes and
11661 keywords relative to each registered export back-end."
11662 (let (keywords)
11663 (dolist (backend
11664 (bound-and-true-p org-export-registered-backends)
11665 (delq nil keywords))
11666 ;; Back-end name (for keywords, like #+LATEX:)
11667 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11668 (dolist (option-entry (org-export-backend-options backend))
11669 ;; Back-end options.
11670 (push (nth 1 option-entry) keywords)))))
11672 (defconst org-options-keywords
11673 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11674 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11675 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11676 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11677 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11679 (defcustom org-structure-template-alist
11680 '(("a" . "export ascii")
11681 ("c" . "center")
11682 ("C" . "comment")
11683 ("e" . "example")
11684 ("E" . "export")
11685 ("h" . "export html")
11686 ("l" . "export latex")
11687 ("q" . "quote")
11688 ("s" . "src")
11689 ("v" . "verse"))
11690 "Structure completion elements.
11691 This is an alist of keys and block types. With
11692 `org-insert-structure-template' a block can be inserted through a
11693 menu. The block type is inserted, with \"#+BEGIN_\" and
11694 \"#+END_\" added automatically. The menukeys are determined
11695 based on the key elements in the `org-structure-template-alist'.
11696 If two entries have the keys \"a\" and \"aa\" respectively, the
11697 former will be inserted by typing \"a TAB/RET/SPC\" and the
11698 latter will be inserted by typing \"aa\". If an entry with the
11699 key \"aab\" is later added it would be inserted by typing \"ab\".
11701 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11702 block can be inserted by pressing TAB after the string \"<KEY\".
11704 :group 'org-edit-structure
11705 :type '(repeat
11706 (cons (string :tag "Key")
11707 (string :tag "Template")))
11708 :package-version '(Org . "9.2"))
11710 (defun org--insert-structure-template-mks ()
11711 "Present `org-structure-template-alist' with `org-mks'.
11713 Menus are added if keys require more than one keystroke.
11714 Tabs are added to single key entires when needing more than one stroke.
11715 Keys longer than two characters are reduced to two characters."
11716 (let* (case-fold-search
11717 (templates (append org-structure-template-alist
11718 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11719 (keys (mapcar #'car templates))
11720 (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11721 ;; Sort each element of `org-structure-template-alist' into
11722 ;; sublists according to the first letter.
11723 (superlist (mapcar (lambda (letter)
11724 (list letter
11725 (cl-remove-if-not
11726 (apply-partially #'string-match-p (concat "^" letter))
11727 templates :key #'car)))
11728 start-letters)))
11729 (org-mks
11730 (apply #'append
11731 ;; Make an `org-mks' table. If only one element is
11732 ;; present in a sublist, make it part of the top-menu,
11733 ;; otherwise make a submenu according to the starting
11734 ;; letter and populate it.
11735 (mapcar (lambda (sublist)
11736 (if (eq 1 (length (cadr sublist)))
11737 (mapcar (lambda (elm)
11738 (list (substring (car elm) 0 1)
11739 (cdr elm) ""))
11740 (cadr sublist))
11741 ;; Create submenu.
11742 (let* ((topkey (car sublist))
11743 (elms (cadr sublist))
11744 (keys (mapcar #'car elms))
11745 (long (> (length elms) 3)))
11746 (append
11747 (list
11748 ;; Make a description of the submenu.
11749 (list topkey
11750 (concat
11751 (mapconcat #'cdr
11752 (cl-subseq elms 0 (if long 3 (length elms)))
11753 ", ")
11754 (when long ", ..."))))
11755 ;; List of entries in submenu.
11756 (cl-mapcar #'list
11757 (org--insert-structure-template-unique-keys keys)
11758 (mapcar #'cdr elms)
11759 (make-list (length elms) ""))))))
11760 superlist))
11761 "Select a key\n============"
11762 "Key: ")))
11764 (defun org--insert-structure-template-unique-keys (keys)
11765 "Make list of unique, two character long elements from KEYS.
11767 Elements of length one have a tab appended. Elements of length
11768 two are kept as is. Longer elements are truncated to length two.
11770 If an element cannot be made unique an error is raised."
11771 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11772 menu-keys)
11773 (dolist (key orderd-keys)
11774 (let ((potential-key
11775 (cl-case (length key)
11776 (1 (concat key "\t"))
11777 (2 key)
11778 (otherwise
11779 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11780 (mapcar (apply-partially #'concat (substring key 0 1))
11781 (split-string (substring key 1) "" t)))))))
11782 (if (or (not potential-key) (assoc potential-key menu-keys))
11783 (user-error "Could not make unique key for %s." key)
11784 (push (cons potential-key key) menu-keys))))
11785 (mapcar #'car
11786 (cl-sort menu-keys #'<
11787 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11789 (defun org-insert-structure-template (type)
11790 "Insert a block structure of the type #+begin_foo/#+end_foo.
11791 First choose a block based on `org-structure-template-alist'.
11792 Alternatively, type RET, TAB or SPC to write the block type.
11793 With an active region, wrap the region in the block. Otherwise,
11794 insert an empty block."
11795 (interactive
11796 (list (pcase (org--insert-structure-template-mks)
11797 (`("\t" . ,_) (read-string "Structure type: "))
11798 (`(,_ ,choice . ,_) choice))))
11799 (let* ((region? (use-region-p))
11800 (col (current-indentation))
11801 (indent (make-string col ?\s))
11802 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11803 (region-string (and region?
11804 (buffer-substring (region-beginning)
11805 (region-end))))
11806 (region-end-blank (and region?
11807 (save-excursion
11808 (goto-char (region-end))
11809 (when (looking-at "[ \t]*$")
11810 (replace-match "")
11811 t))))
11813 (when region? (delete-region (region-beginning) (region-end)))
11814 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11815 (insert "\n"))
11816 (beginning-of-line)
11817 (save-excursion
11818 (insert
11819 (with-temp-buffer
11820 (when region?
11821 (insert region-string "\n")
11822 (when (string-match-p
11823 (concat "\\`" (regexp-opt '("example" "export" "src")))
11824 type)
11825 (org-escape-code-in-region (point-min) (point-max))))
11826 (goto-char (point-min))
11827 ;; Delete trailing white-lines.
11828 (when region?
11829 (while (looking-at-p "^[ \t]*$")
11830 (delete-region (line-beginning-position)
11831 (line-beginning-position 2))))
11832 (save-excursion
11833 (while (not (eobp))
11834 (unless (looking-at-p indent)
11835 (insert indent))
11836 (forward-line)))
11837 (insert
11838 indent
11839 (format "#+begin_%s%s\n" type (if special? " " "")))
11840 (unless region? (indent-to col))
11841 (setq s (point))
11842 (goto-char (point-max))
11843 (skip-chars-backward "[ \t\n]" s)
11844 (delete-region (line-end-position) (point-max))
11845 (insert "\n" indent
11846 (format "#+end_%s" (car (split-string type)))
11847 (if region-end-blank "" "\n"))
11848 (buffer-substring (point-min) (point))))
11849 (when (and (eobp) (not (bolp))) (insert "\n")))
11850 (cond (special?
11851 (end-of-line))
11853 (forward-line)
11854 (skip-chars-forward "[ \t]*")))))
11857 ;;;; TODO, DEADLINE, Comments
11859 (defun org-toggle-comment ()
11860 "Change the COMMENT state of an entry."
11861 (interactive)
11862 (save-excursion
11863 (org-back-to-heading)
11864 (let ((case-fold-search nil))
11865 (looking-at org-complex-heading-regexp))
11866 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11867 (skip-chars-forward " \t")
11868 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11869 (if (org-in-commented-heading-p t)
11870 (delete-region (point)
11871 (progn (search-forward " " (line-end-position) 'move)
11872 (skip-chars-forward " \t")
11873 (point)))
11874 (insert org-comment-string)
11875 (unless (eolp) (insert " ")))))
11877 (defvar org-last-todo-state-is-todo nil
11878 "This is non-nil when the last TODO state change led to a TODO state.
11879 If the last change removed the TODO tag or switched to DONE, then
11880 this is nil.")
11882 (defvar org-todo-setup-filter-hook nil
11883 "Hook for functions that pre-filter todo specs.
11884 Each function takes a todo spec and returns either nil or the spec
11885 transformed into canonical form." )
11887 (defvar org-todo-get-default-hook nil
11888 "Hook for functions that get a default item for todo.
11889 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11890 nil or a string to be used for the todo mark." )
11892 (defvar org-agenda-headline-snapshot-before-repeat)
11894 (defun org-current-effective-time ()
11895 "Return current time adjusted for `org-extend-today-until' variable."
11896 (let* ((ct (org-current-time))
11897 (dct (decode-time ct))
11898 (ct1
11899 (cond
11900 (org-use-last-clock-out-time-as-effective-time
11901 (or (org-clock-get-last-clock-out-time) ct))
11902 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11903 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11904 (t ct))))
11905 ct1))
11907 (defun org-todo-yesterday (&optional arg)
11908 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11909 (interactive "P")
11910 (if (eq major-mode 'org-agenda-mode)
11911 (apply 'org-agenda-todo-yesterday arg)
11912 (let* ((org-use-effective-time t)
11913 (hour (nth 2 (decode-time (org-current-time))))
11914 (org-extend-today-until (1+ hour)))
11915 (org-todo arg))))
11917 (defvar org-block-entry-blocking ""
11918 "First entry preventing the TODO state change.")
11920 (defun org-cancel-repeater ()
11921 "Cancel a repeater by setting its numeric value to zero."
11922 (interactive)
11923 (save-excursion
11924 (org-back-to-heading t)
11925 (let ((bound1 (point))
11926 (bound0 (save-excursion (outline-next-heading) (point))))
11927 (when (and (re-search-forward
11928 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11929 org-deadline-time-regexp "\\)\\|\\("
11930 org-ts-regexp "\\)")
11931 bound0 t)
11932 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11933 bound1 t))
11934 (replace-match "0" t nil nil 1)))))
11936 (defvar org-state)
11937 (defvar org-blocked-by-checkboxes)
11938 (defun org-todo (&optional arg)
11939 "Change the TODO state of an item.
11941 The state of an item is given by a keyword at the start of the heading,
11942 like
11943 *** TODO Write paper
11944 *** DONE Call mom
11946 The different keywords are specified in the variable `org-todo-keywords'.
11947 By default the available states are \"TODO\" and \"DONE\". So, for this
11948 example: when the item starts with TODO, it is changed to DONE.
11949 When it starts with DONE, the DONE is removed. And when neither TODO nor
11950 DONE are present, add TODO at the beginning of the heading.
11952 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11953 state.
11954 With numeric prefix ARG, switch to that state.
11955 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11956 next set of TODO \
11957 keywords (nextset).
11958 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11959 prefix, circumvent any state blocking.
11960 With a numeric prefix arg of 0, inhibit note taking for the change.
11961 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11963 When called through ELisp, arg is also interpreted in the following way:
11964 `none' -> empty state
11965 \"\" -> switch to empty state
11966 `done' -> switch to DONE
11967 `nextset' -> switch to the next set of keywords
11968 `previousset' -> switch to the previous set of keywords
11969 \"WAITING\" -> switch to the specified keyword, but only if it
11970 really is a member of `org-todo-keywords'."
11971 (interactive "P")
11972 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11973 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11974 'region-start-level 'region))
11975 org-loop-over-headlines-in-active-region)
11976 (org-map-entries
11977 `(org-todo ,arg)
11978 org-loop-over-headlines-in-active-region
11979 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11980 (when (equal arg '(16)) (setq arg 'nextset))
11981 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11982 (let ((org-blocker-hook org-blocker-hook)
11983 commentp
11984 case-fold-search)
11985 (when (equal arg '(64))
11986 (setq arg nil org-blocker-hook nil))
11987 (when (and org-blocker-hook
11988 (or org-inhibit-blocking
11989 (org-entry-get nil "NOBLOCKING")))
11990 (setq org-blocker-hook nil))
11991 (save-excursion
11992 (catch 'exit
11993 (org-back-to-heading t)
11994 (when (org-in-commented-heading-p t)
11995 (org-toggle-comment)
11996 (setq commentp t))
11997 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11998 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11999 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12000 (let* ((match-data (match-data))
12001 (startpos (copy-marker (line-beginning-position)))
12002 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12003 (org-log-done org-log-done)
12004 (org-log-repeat org-log-repeat)
12005 (org-todo-log-states org-todo-log-states)
12006 (org-inhibit-logging
12007 (if (equal arg 0)
12008 (progn (setq arg nil) 'note) org-inhibit-logging))
12009 (this (match-string 1))
12010 (hl-pos (match-beginning 0))
12011 (head (org-get-todo-sequence-head this))
12012 (ass (assoc head org-todo-kwd-alist))
12013 (interpret (nth 1 ass))
12014 (done-word (nth 3 ass))
12015 (final-done-word (nth 4 ass))
12016 (org-last-state (or this ""))
12017 (completion-ignore-case t)
12018 (member (member this org-todo-keywords-1))
12019 (tail (cdr member))
12020 (org-state (cond
12021 ((and org-todo-key-trigger
12022 (or (and (equal arg '(4))
12023 (eq org-use-fast-todo-selection 'prefix))
12024 (and (not arg) org-use-fast-todo-selection
12025 (not (eq org-use-fast-todo-selection
12026 'prefix)))))
12027 ;; Use fast selection.
12028 (org-fast-todo-selection))
12029 ((and (equal arg '(4))
12030 (or (not org-use-fast-todo-selection)
12031 (not org-todo-key-trigger)))
12032 ;; Read a state with completion.
12033 (completing-read
12034 "State: " (mapcar #'list org-todo-keywords-1)
12035 nil t))
12036 ((eq arg 'right)
12037 (if this
12038 (if tail (car tail) nil)
12039 (car org-todo-keywords-1)))
12040 ((eq arg 'left)
12041 (unless (equal member org-todo-keywords-1)
12042 (if this
12043 (nth (- (length org-todo-keywords-1)
12044 (length tail) 2)
12045 org-todo-keywords-1)
12046 (org-last org-todo-keywords-1))))
12047 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12048 (setq arg nil))) ;hack to fall back to cycling
12049 (arg
12050 ;; User or caller requests a specific state.
12051 (cond
12052 ((equal arg "") nil)
12053 ((eq arg 'none) nil)
12054 ((eq arg 'done) (or done-word (car org-done-keywords)))
12055 ((eq arg 'nextset)
12056 (or (car (cdr (member head org-todo-heads)))
12057 (car org-todo-heads)))
12058 ((eq arg 'previousset)
12059 (let ((org-todo-heads (reverse org-todo-heads)))
12060 (or (car (cdr (member head org-todo-heads)))
12061 (car org-todo-heads))))
12062 ((car (member arg org-todo-keywords-1)))
12063 ((stringp arg)
12064 (user-error "State `%s' not valid in this file" arg))
12065 ((nth (1- (prefix-numeric-value arg))
12066 org-todo-keywords-1))))
12067 ((null member) (or head (car org-todo-keywords-1)))
12068 ((equal this final-done-word) nil) ;-> make empty
12069 ((null tail) nil) ;-> first entry
12070 ((memq interpret '(type priority))
12071 (if (eq this-command last-command)
12072 (car tail)
12073 (if (> (length tail) 0)
12074 (or done-word (car org-done-keywords))
12075 nil)))
12077 (car tail))))
12078 (org-state (or
12079 (run-hook-with-args-until-success
12080 'org-todo-get-default-hook org-state org-last-state)
12081 org-state))
12082 (next (if org-state (concat " " org-state " ") " "))
12083 (change-plist (list :type 'todo-state-change :from this :to org-state
12084 :position startpos))
12085 dolog now-done-p)
12086 (when org-blocker-hook
12087 (let (org-blocked-by-checkboxes block-reason)
12088 (setq org-last-todo-state-is-todo
12089 (not (member this org-done-keywords)))
12090 (unless (save-excursion
12091 (save-match-data
12092 (org-with-wide-buffer
12093 (run-hook-with-args-until-failure
12094 'org-blocker-hook change-plist))))
12095 (setq block-reason (if org-blocked-by-checkboxes
12096 "contained checkboxes"
12097 (format "\"%s\"" org-block-entry-blocking)))
12098 (if (called-interactively-p 'interactive)
12099 (user-error "TODO state change from %s to %s blocked (by %s)"
12100 this org-state block-reason)
12101 ;; Fail silently.
12102 (message "TODO state change from %s to %s blocked (by %s)"
12103 this org-state block-reason)
12104 (throw 'exit nil)))))
12105 (store-match-data match-data)
12106 (replace-match next t t)
12107 (cond ((equal this org-state)
12108 (message "TODO state was already %s" (org-trim next)))
12109 ((not (pos-visible-in-window-p hl-pos))
12110 (message "TODO state changed to %s" (org-trim next))))
12111 (unless head
12112 (setq head (org-get-todo-sequence-head org-state)
12113 ass (assoc head org-todo-kwd-alist)
12114 interpret (nth 1 ass)
12115 done-word (nth 3 ass)
12116 final-done-word (nth 4 ass)))
12117 (when (memq arg '(nextset previousset))
12118 (message "Keyword-Set %d/%d: %s"
12119 (- (length org-todo-sets) -1
12120 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12121 (length org-todo-sets)
12122 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12123 (setq org-last-todo-state-is-todo
12124 (not (member org-state org-done-keywords)))
12125 (setq now-done-p (and (member org-state org-done-keywords)
12126 (not (member this org-done-keywords))))
12127 (and logging (org-local-logging logging))
12128 (when (and (or org-todo-log-states org-log-done)
12129 (not (eq org-inhibit-logging t))
12130 (not (memq arg '(nextset previousset))))
12131 ;; We need to look at recording a time and note.
12132 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12133 (nth 2 (assoc this org-todo-log-states))))
12134 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12135 (setq dolog 'time))
12136 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12137 (and org-state
12138 (member org-state org-not-done-keywords)
12139 (not (member this org-not-done-keywords))))
12140 ;; This is now a todo state and was not one before
12141 ;; If there was a CLOSED time stamp, get rid of it.
12142 (org-add-planning-info nil nil 'closed))
12143 (when (and now-done-p org-log-done)
12144 ;; It is now done, and it was not done before.
12145 (org-add-planning-info 'closed (org-current-effective-time))
12146 (when (and (not dolog) (eq 'note org-log-done))
12147 (org-add-log-setup 'done org-state this 'note)))
12148 (when (and org-state dolog)
12149 ;; This is a non-nil state, and we need to log it.
12150 (org-add-log-setup 'state org-state this dolog)))
12151 ;; Fixup tag positioning.
12152 (org-todo-trigger-tag-changes org-state)
12153 (when org-auto-align-tags (org-align-tags))
12154 (when org-provide-todo-statistics
12155 (org-update-parent-todo-statistics))
12156 (run-hooks 'org-after-todo-state-change-hook)
12157 (when (and arg (not (member org-state org-done-keywords)))
12158 (setq head (org-get-todo-sequence-head org-state)))
12159 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12160 ;; Do we need to trigger a repeat?
12161 (when now-done-p
12162 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12163 ;; This is for the agenda, take a snapshot of the headline.
12164 (save-match-data
12165 (setq org-agenda-headline-snapshot-before-repeat
12166 (org-get-heading))))
12167 (org-auto-repeat-maybe org-state))
12168 ;; Fixup cursor location if close to the keyword.
12169 (when (and (outline-on-heading-p)
12170 (not (bolp))
12171 (save-excursion (beginning-of-line 1)
12172 (looking-at org-todo-line-regexp))
12173 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12174 (goto-char (or (match-end 2) (match-end 1)))
12175 (and (looking-at " ") (just-one-space)))
12176 (when org-trigger-hook
12177 (save-excursion
12178 (run-hook-with-args 'org-trigger-hook change-plist)))
12179 (when commentp (org-toggle-comment))))))))
12181 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12182 "Block turning an entry into a TODO, using the hierarchy.
12183 This checks whether the current task should be blocked from state
12184 changes. Such blocking occurs when:
12186 1. The task has children which are not all in a completed state.
12188 2. A task has a parent with the property :ORDERED:, and there
12189 are siblings prior to the current task with incomplete
12190 status.
12192 3. The parent of the task is blocked because it has siblings that should
12193 be done first, or is child of a block grandparent TODO entry."
12195 (if (not org-enforce-todo-dependencies)
12196 t ; if locally turned off don't block
12197 (catch 'dont-block
12198 ;; If this is not a todo state change, or if this entry is already DONE,
12199 ;; do not block
12200 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12201 (member (plist-get change-plist :from)
12202 (cons 'done org-done-keywords))
12203 (member (plist-get change-plist :to)
12204 (cons 'todo org-not-done-keywords))
12205 (not (plist-get change-plist :to)))
12206 (throw 'dont-block t))
12207 ;; If this task has children, and any are undone, it's blocked
12208 (save-excursion
12209 (org-back-to-heading t)
12210 (let ((this-level (funcall outline-level)))
12211 (outline-next-heading)
12212 (let ((child-level (funcall outline-level)))
12213 (while (and (not (eobp))
12214 (> child-level this-level))
12215 ;; this todo has children, check whether they are all
12216 ;; completed
12217 (when (and (not (org-entry-is-done-p))
12218 (org-entry-is-todo-p))
12219 (setq org-block-entry-blocking (org-get-heading))
12220 (throw 'dont-block nil))
12221 (outline-next-heading)
12222 (setq child-level (funcall outline-level))))))
12223 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12224 ;; any previous siblings are undone, it's blocked
12225 (save-excursion
12226 (org-back-to-heading t)
12227 (let* ((pos (point))
12228 (parent-pos (and (org-up-heading-safe) (point)))
12229 (case-fold-search nil))
12230 (unless parent-pos (throw 'dont-block t)) ; no parent
12231 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12232 (forward-line 1)
12233 (re-search-forward org-not-done-heading-regexp pos t))
12234 (setq org-block-entry-blocking (match-string 0))
12235 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12236 ;; Search further up the hierarchy, to see if an ancestor is blocked
12237 (while t
12238 (goto-char parent-pos)
12239 (unless (looking-at org-not-done-heading-regexp)
12240 (throw 'dont-block t)) ; do not block, parent is not a TODO
12241 (setq pos (point))
12242 (setq parent-pos (and (org-up-heading-safe) (point)))
12243 (unless parent-pos (throw 'dont-block t)) ; no parent
12244 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12245 (forward-line 1)
12246 (re-search-forward org-not-done-heading-regexp pos t)
12247 (setq org-block-entry-blocking (org-get-heading)))
12248 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12250 (defcustom org-track-ordered-property-with-tag nil
12251 "Should the ORDERED property also be shown as a tag?
12252 The ORDERED property decides if an entry should require subtasks to be
12253 completed in sequence. Since a property is not very visible, setting
12254 this option means that toggling the ORDERED property with the command
12255 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12256 not relevant for the behavior, but it makes things more visible.
12258 Note that toggling the tag with tags commands will not change the property
12259 and therefore not influence behavior!
12261 This can be t, meaning the tag ORDERED should be used, It can also be a
12262 string to select a different tag for this task."
12263 :group 'org-todo
12264 :type '(choice
12265 (const :tag "No tracking" nil)
12266 (const :tag "Track with ORDERED tag" t)
12267 (string :tag "Use other tag")))
12269 (defun org-toggle-ordered-property ()
12270 "Toggle the ORDERED property of the current entry.
12271 For better visibility, you can track the value of this property with a tag.
12272 See variable `org-track-ordered-property-with-tag'."
12273 (interactive)
12274 (let* ((t1 org-track-ordered-property-with-tag)
12275 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12276 (save-excursion
12277 (org-back-to-heading)
12278 (if (org-entry-get nil "ORDERED")
12279 (progn
12280 (org-delete-property "ORDERED")
12281 (and tag (org-toggle-tag tag 'off))
12282 (message "Subtasks can be completed in arbitrary order"))
12283 (org-entry-put nil "ORDERED" "t")
12284 (and tag (org-toggle-tag tag 'on))
12285 (message "Subtasks must be completed in sequence")))))
12287 (defun org-block-todo-from-checkboxes (change-plist)
12288 "Block turning an entry into a TODO, using checkboxes.
12289 This checks whether the current task should be blocked from state
12290 changes because there are unchecked boxes in this entry."
12291 (if (not org-enforce-todo-checkbox-dependencies)
12292 t ; if locally turned off don't block
12293 (catch 'dont-block
12294 ;; If this is not a todo state change, or if this entry is already DONE,
12295 ;; do not block
12296 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12297 (member (plist-get change-plist :from)
12298 (cons 'done org-done-keywords))
12299 (member (plist-get change-plist :to)
12300 (cons 'todo org-not-done-keywords))
12301 (not (plist-get change-plist :to)))
12302 (throw 'dont-block t))
12303 ;; If this task has checkboxes that are not checked, it's blocked
12304 (save-excursion
12305 (org-back-to-heading t)
12306 (let ((beg (point)) end)
12307 (outline-next-heading)
12308 (setq end (point))
12309 (goto-char beg)
12310 (when (org-list-search-forward
12311 (concat (org-item-beginning-re)
12312 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12313 "\\[[- ]\\]")
12314 end t)
12315 (when (boundp 'org-blocked-by-checkboxes)
12316 (setq org-blocked-by-checkboxes t))
12317 (throw 'dont-block nil))))
12318 t))) ; do not block
12320 (defun org-entry-blocked-p ()
12321 "Non-nil if entry at point is blocked."
12322 (and (not (org-entry-get nil "NOBLOCKING"))
12323 (member (org-entry-get nil "TODO") org-not-done-keywords)
12324 (not (run-hook-with-args-until-failure
12325 'org-blocker-hook
12326 (list :type 'todo-state-change
12327 :position (point)
12328 :from 'todo
12329 :to 'done)))))
12331 (defun org-update-statistics-cookies (all)
12332 "Update the statistics cookie, either from TODO or from checkboxes.
12333 This should be called with the cursor in a line with a statistics
12334 cookie. When called with a \\[universal-argument] prefix, update
12335 all statistics cookies in the buffer."
12336 (interactive "P")
12337 (if all
12338 (progn
12339 (org-update-checkbox-count 'all)
12340 (org-map-entries 'org-update-parent-todo-statistics))
12341 (if (not (org-at-heading-p))
12342 (org-update-checkbox-count)
12343 (let ((pos (point-marker))
12344 end l1 l2)
12345 (ignore-errors (org-back-to-heading t))
12346 (if (not (org-at-heading-p))
12347 (org-update-checkbox-count)
12348 (setq l1 (org-outline-level))
12349 (setq end (save-excursion
12350 (outline-next-heading)
12351 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12352 (point)))
12353 (if (and (save-excursion
12354 (re-search-forward
12355 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12356 (not (save-excursion (re-search-forward
12357 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12358 (org-update-checkbox-count)
12359 (if (and l2 (> l2 l1))
12360 (progn
12361 (goto-char end)
12362 (org-update-parent-todo-statistics))
12363 (goto-char pos)
12364 (beginning-of-line 1)
12365 (while (re-search-forward
12366 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12367 (point-at-eol) t)
12368 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12369 (goto-char pos)
12370 (move-marker pos nil)))))
12372 (defvar org-entry-property-inherited-from) ;; defined below
12373 (defun org-update-parent-todo-statistics ()
12374 "Update any statistics cookie in the parent of the current headline.
12375 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12376 the entire subtree and this will travel up the hierarchy and update
12377 statistics everywhere."
12378 (let* ((prop (save-excursion (org-up-heading-safe)
12379 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12380 (recursive (or (not org-hierarchical-todo-statistics)
12381 (and prop (string-match "\\<recursive\\>" prop))))
12382 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12384 (first t)
12385 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12386 level ltoggle l1 new ndel
12387 (cnt-all 0) (cnt-done 0) is-percent kwd
12388 checkbox-beg cookie-present)
12389 (catch 'exit
12390 (save-excursion
12391 (beginning-of-line 1)
12392 (setq ltoggle (funcall outline-level))
12393 ;; Three situations are to consider:
12395 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12396 ;; to the top-level ancestor on the headline;
12398 ;; 2. If parent has "recursive" property, repeat up to the
12399 ;; headline setting that property, taking inheritance into
12400 ;; account;
12402 ;; 3. Else, move up to direct parent and proceed only once.
12403 (while (and (setq level (org-up-heading-safe))
12404 (or recursive first)
12405 (>= (point) lim))
12406 (setq first nil cookie-present nil)
12407 (unless (and level
12408 (not (string-match
12409 "\\<checkbox\\>"
12410 (downcase (or (org-entry-get nil "COOKIE_DATA")
12411 "")))))
12412 (throw 'exit nil))
12413 (while (re-search-forward box-re (point-at-eol) t)
12414 (setq cnt-all 0 cnt-done 0 cookie-present t)
12415 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12416 (save-match-data
12417 (unless (outline-next-heading) (throw 'exit nil))
12418 (while (and (looking-at org-complex-heading-regexp)
12419 (> (setq l1 (length (match-string 1))) level))
12420 (setq kwd (and (or recursive (= l1 ltoggle))
12421 (match-string 2)))
12422 (if (or (eq org-provide-todo-statistics 'all-headlines)
12423 (and (eq org-provide-todo-statistics t)
12424 (or (member kwd org-done-keywords)))
12425 (and (listp org-provide-todo-statistics)
12426 (stringp (car org-provide-todo-statistics))
12427 (or (member kwd org-provide-todo-statistics)
12428 (member kwd org-done-keywords)))
12429 (and (listp org-provide-todo-statistics)
12430 (listp (car org-provide-todo-statistics))
12431 (or (member kwd (car org-provide-todo-statistics))
12432 (and (member kwd org-done-keywords)
12433 (member kwd (cadr org-provide-todo-statistics))))))
12434 (setq cnt-all (1+ cnt-all))
12435 (and (eq org-provide-todo-statistics t)
12437 (setq cnt-all (1+ cnt-all))))
12438 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12439 (member kwd org-done-keywords))
12440 (and (listp org-provide-todo-statistics)
12441 (listp (car org-provide-todo-statistics))
12442 (member kwd org-done-keywords)
12443 (member kwd (cadr org-provide-todo-statistics)))
12444 (and (listp org-provide-todo-statistics)
12445 (stringp (car org-provide-todo-statistics))
12446 (member kwd org-done-keywords)))
12447 (setq cnt-done (1+ cnt-done)))
12448 (outline-next-heading)))
12449 (setq new
12450 (if is-percent
12451 (format "[%d%%]" (floor (* 100.0 cnt-done)
12452 (max 1 cnt-all)))
12453 (format "[%d/%d]" cnt-done cnt-all))
12454 ndel (- (match-end 0) checkbox-beg))
12455 (goto-char checkbox-beg)
12456 (insert new)
12457 (delete-region (point) (+ (point) ndel))
12458 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12459 (when cookie-present
12460 (run-hook-with-args 'org-after-todo-statistics-hook
12461 cnt-done (- cnt-all cnt-done))))))
12462 (run-hooks 'org-todo-statistics-hook)))
12464 (defvar org-after-todo-statistics-hook nil
12465 "Hook that is called after a TODO statistics cookie has been updated.
12466 Each function is called with two arguments: the number of not-done entries
12467 and the number of done entries.
12469 For example, the following function, when added to this hook, will switch
12470 an entry to DONE when all children are done, and back to TODO when new
12471 entries are set to a TODO status. Note that this hook is only called
12472 when there is a statistics cookie in the headline!
12474 (defun org-summary-todo (n-done n-not-done)
12475 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12476 (let (org-log-done org-log-states) ; turn off logging
12477 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12480 (defvar org-todo-statistics-hook nil
12481 "Hook that is run whenever Org thinks TODO statistics should be updated.
12482 This hook runs even if there is no statistics cookie present, in which case
12483 `org-after-todo-statistics-hook' would not run.")
12485 (defun org-todo-trigger-tag-changes (state)
12486 "Apply the changes defined in `org-todo-state-tags-triggers'."
12487 (let ((l org-todo-state-tags-triggers)
12488 changes)
12489 (when (or (not state) (equal state ""))
12490 (setq changes (append changes (cdr (assoc "" l)))))
12491 (when (and (stringp state) (> (length state) 0))
12492 (setq changes (append changes (cdr (assoc state l)))))
12493 (when (member state org-not-done-keywords)
12494 (setq changes (append changes (cdr (assq 'todo l)))))
12495 (when (member state org-done-keywords)
12496 (setq changes (append changes (cdr (assq 'done l)))))
12497 (dolist (c changes)
12498 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12500 (defun org-local-logging (value)
12501 "Get logging settings from a property VALUE."
12502 ;; Directly set the variables, they are already local.
12503 (setq org-log-done nil
12504 org-log-repeat nil
12505 org-todo-log-states nil)
12506 (dolist (w (split-string value))
12507 (let (a)
12508 (cond
12509 ((setq a (assoc w org-startup-options))
12510 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12511 (set (nth 1 a) (nth 2 a))))
12512 ((setq a (org-extract-log-state-settings w))
12513 (and (member (car a) org-todo-keywords-1)
12514 (push a org-todo-log-states)))))))
12516 (defun org-get-todo-sequence-head (kwd)
12517 "Return the head of the TODO sequence to which KWD belongs.
12518 If KWD is not set, check if there is a text property remembering the
12519 right sequence."
12520 (let (p)
12521 (cond
12522 ((not kwd)
12523 (or (get-text-property (point-at-bol) 'org-todo-head)
12524 (progn
12525 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12526 nil (point-at-eol)))
12527 (get-text-property p 'org-todo-head))))
12528 ((not (member kwd org-todo-keywords-1))
12529 (car org-todo-keywords-1))
12530 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12532 (defun org-fast-todo-selection ()
12533 "Fast TODO keyword selection with single keys.
12534 Returns the new TODO keyword, or nil if no state change should occur."
12535 (let* ((fulltable org-todo-key-alist)
12536 (done-keywords org-done-keywords) ;; needed for the faces.
12537 (maxlen (apply 'max (mapcar
12538 (lambda (x)
12539 (if (stringp (car x)) (string-width (car x)) 0))
12540 fulltable)))
12541 (expert nil)
12542 (fwidth (+ maxlen 3 1 3))
12543 (ncol (/ (- (window-width) 4) fwidth))
12544 tg cnt e c tbl
12545 groups ingroup)
12546 (save-excursion
12547 (save-window-excursion
12548 (if expert
12549 (set-buffer (get-buffer-create " *Org todo*"))
12550 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12551 (erase-buffer)
12552 (setq-local org-done-keywords done-keywords)
12553 (setq tbl fulltable cnt 0)
12554 (while (setq e (pop tbl))
12555 (cond
12556 ((equal e '(:startgroup))
12557 (push '() groups) (setq ingroup t)
12558 (unless (= cnt 0)
12559 (setq cnt 0)
12560 (insert "\n"))
12561 (insert "{ "))
12562 ((equal e '(:endgroup))
12563 (setq ingroup nil cnt 0)
12564 (insert "}\n"))
12565 ((equal e '(:newline))
12566 (unless (= cnt 0)
12567 (setq cnt 0)
12568 (insert "\n")
12569 (setq e (car tbl))
12570 (while (equal (car tbl) '(:newline))
12571 (insert "\n")
12572 (setq tbl (cdr tbl)))))
12574 (setq tg (car e) c (cdr e))
12575 (when ingroup (push tg (car groups)))
12576 (setq tg (org-add-props tg nil 'face
12577 (org-get-todo-face tg)))
12578 (when (and (= cnt 0) (not ingroup)) (insert " "))
12579 (insert "[" c "] " tg (make-string
12580 (- fwidth 4 (length tg)) ?\ ))
12581 (when (= (setq cnt (1+ cnt)) ncol)
12582 (insert "\n")
12583 (when ingroup (insert " "))
12584 (setq cnt 0)))))
12585 (insert "\n")
12586 (goto-char (point-min))
12587 (unless expert (org-fit-window-to-buffer))
12588 (message "[a-z..]:Set [SPC]:clear")
12589 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12590 (cond
12591 ((or (= c ?\C-g)
12592 (and (= c ?q) (not (rassoc c fulltable))))
12593 (setq quit-flag t))
12594 ((= c ?\ ) nil)
12595 ((setq e (rassoc c fulltable) tg (car e))
12597 (t (setq quit-flag t)))))))
12599 (defun org-entry-is-todo-p ()
12600 (member (org-get-todo-state) org-not-done-keywords))
12602 (defun org-entry-is-done-p ()
12603 (member (org-get-todo-state) org-done-keywords))
12605 (defun org-get-todo-state ()
12606 "Return the TODO keyword of the current subtree."
12607 (save-excursion
12608 (org-back-to-heading t)
12609 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12610 (match-end 2)
12611 (match-string 2))))
12613 (defun org-at-date-range-p (&optional inactive-ok)
12614 "Non-nil if point is inside a date range.
12616 When optional argument INACTIVE-OK is non-nil, also consider
12617 inactive time ranges.
12619 When this function returns a non-nil value, match data is set
12620 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12621 on INACTIVE-OK."
12622 (interactive)
12623 (save-excursion
12624 (catch 'exit
12625 (let ((pos (point)))
12626 (skip-chars-backward "^[<\r\n")
12627 (skip-chars-backward "<[")
12628 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12629 (>= (match-end 0) pos)
12630 (throw 'exit t))
12631 (skip-chars-backward "^<[\r\n")
12632 (skip-chars-backward "<[")
12633 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12634 (>= (match-end 0) pos)
12635 (throw 'exit t)))
12636 nil)))
12638 (defun org-get-repeat (&optional timestamp)
12639 "Check if there is a time-stamp with repeater in this entry.
12641 Return the repeater, as a string, or nil. Also return nil when
12642 this function is called before first heading.
12644 When optional argument TIMESTAMP is a string, extract the
12645 repeater from there instead."
12646 (save-match-data
12647 (cond (timestamp
12648 (and (string-match org-repeat-re timestamp)
12649 (match-string-no-properties 1 timestamp)))
12650 ((org-before-first-heading-p) nil)
12652 (save-excursion
12653 (org-back-to-heading t)
12654 (let ((end (org-entry-end-position)))
12655 (catch :repeat
12656 (while (re-search-forward org-repeat-re end t)
12657 (when (save-match-data (org-at-timestamp-p 'agenda))
12658 (throw :repeat (match-string-no-properties 1)))))))))))
12660 (defvar org-last-changed-timestamp)
12661 (defvar org-last-inserted-timestamp)
12662 (defvar org-log-post-message)
12663 (defvar org-log-note-purpose)
12664 (defvar org-log-note-how nil)
12665 (defvar org-log-note-extra)
12666 (defun org-auto-repeat-maybe (done-word)
12667 "Check if the current headline contains a repeated time-stamp.
12669 If yes, set TODO state back to what it was and change the base date
12670 of repeating deadline/scheduled time stamps to new date.
12672 This function is run automatically after each state change to a DONE state."
12673 (let* ((repeat (org-get-repeat))
12674 (aa (assoc org-last-state org-todo-kwd-alist))
12675 (interpret (nth 1 aa))
12676 (head (nth 2 aa))
12677 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12678 (msg "Entry repeats: ")
12679 (org-log-done nil)
12680 (org-todo-log-states nil)
12681 (end (copy-marker (org-entry-end-position))))
12682 (unwind-protect
12683 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12684 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12685 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12686 (and (stringp org-todo-repeat-to-state)
12687 org-todo-repeat-to-state)
12688 (and org-todo-repeat-to-state org-last-state))))
12689 (org-todo (cond
12690 ((and to-state (member to-state org-todo-keywords-1))
12691 to-state)
12692 ((eq interpret 'type) org-last-state)
12693 (head)
12694 (t 'none))))
12695 (org-back-to-heading t)
12696 (org-add-planning-info nil nil 'closed)
12697 ;; When `org-log-repeat' is non-nil or entry contains
12698 ;; a clock, set LAST_REPEAT property.
12699 (when (or org-log-repeat
12700 (catch :clock
12701 (save-excursion
12702 (while (re-search-forward org-clock-line-re end t)
12703 (when (org-at-clock-log-p) (throw :clock t))))))
12704 (org-entry-put nil "LAST_REPEAT" (format-time-string
12705 (org-time-stamp-format t t)
12706 (current-time))))
12707 (when org-log-repeat
12708 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12709 (memq 'org-add-log-note post-command-hook))
12710 ;; We are already setup for some record.
12711 (when (eq org-log-repeat 'note)
12712 ;; Make sure we take a note, not only a time stamp.
12713 (setq org-log-note-how 'note))
12714 ;; Set up for taking a record.
12715 (org-add-log-setup 'state
12716 (or done-word (car org-done-keywords))
12717 org-last-state
12718 org-log-repeat)))
12719 (let ((planning-re (regexp-opt
12720 (list org-scheduled-string org-deadline-string))))
12721 (while (re-search-forward org-ts-regexp end t)
12722 (let* ((ts (match-string 0))
12723 (planning? (org-at-planning-p))
12724 (type (if (not planning?) "Plain:"
12725 (save-excursion
12726 (re-search-backward
12727 planning-re (line-beginning-position) t)
12728 (match-string 0)))))
12729 (cond
12730 ;; Ignore fake time-stamps (e.g., within comments).
12731 ((not (org-at-timestamp-p 'agenda)))
12732 ;; Time-stamps without a repeater are usually
12733 ;; skipped. However, a SCHEDULED time-stamp without
12734 ;; one is removed, as they are no longer relevant.
12735 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12736 ts))
12737 (when (equal type org-scheduled-string)
12738 (org-remove-timestamp-with-keyword type)))
12740 (let ((n (string-to-number (match-string 2 ts)))
12741 (what (match-string 3 ts)))
12742 (when (equal what "w") (setq n (* n 7) what "d"))
12743 (when (and (equal what "h")
12744 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12745 ts)))
12746 (user-error
12747 "Cannot repeat in Repeat in %d hour(s) because no hour \
12748 has been set"
12750 ;; Preparation, see if we need to modify the start
12751 ;; date for the change.
12752 (when (match-end 1)
12753 (let ((time (save-match-data
12754 (org-time-string-to-time ts))))
12755 (cond
12756 ((equal (match-string 1 ts) ".")
12757 ;; Shift starting date to today
12758 (org-timestamp-change
12759 (- (org-today) (time-to-days time))
12760 'day))
12761 ((equal (match-string 1 ts) "+")
12762 (let ((nshiftmax 10)
12763 (nshift 0))
12764 (while (or (= nshift 0)
12765 (not (time-less-p (current-time) time)))
12766 (when (= (cl-incf nshift) nshiftmax)
12767 (or (y-or-n-p
12768 (format "%d repeater intervals were not \
12769 enough to shift date past today. Continue? "
12770 nshift))
12771 (user-error "Abort")))
12772 (org-timestamp-change n (cdr (assoc what whata)))
12773 (org-in-regexp org-ts-regexp3)
12774 (setq ts (match-string 1))
12775 (setq time
12776 (save-match-data
12777 (org-time-string-to-time ts)))))
12778 (org-timestamp-change (- n) (cdr (assoc what whata)))
12779 ;; Rematch, so that we have everything in place
12780 ;; for the real shift.
12781 (org-in-regexp org-ts-regexp3)
12782 (setq ts (match-string 1))
12783 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12784 ts)))))
12785 (save-excursion
12786 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12787 (setq msg
12788 (concat
12789 msg type " " org-last-changed-timestamp " "))))))))
12790 (setq org-log-post-message msg)
12791 (message "%s" msg))
12792 (set-marker end nil))))
12794 (defun org-show-todo-tree (arg)
12795 "Make a compact tree which shows all headlines marked with TODO.
12796 The tree will show the lines where the regexp matches, and all higher
12797 headlines above the match.
12798 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12799 With a numeric prefix N, construct a sparse tree for the Nth element
12800 of `org-todo-keywords-1'."
12801 (interactive "P")
12802 (let ((case-fold-search nil)
12803 (kwd-re
12804 (cond ((null arg) org-not-done-regexp)
12805 ((equal arg '(4))
12806 (let ((kwd
12807 (completing-read "Keyword (or KWD1|KWD2|...): "
12808 (mapcar #'list org-todo-keywords-1))))
12809 (concat "\\("
12810 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12811 "\\)\\>")))
12812 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12813 (regexp-quote (nth (1- (prefix-numeric-value arg))
12814 org-todo-keywords-1)))
12815 (t (user-error "Invalid prefix argument: %s" arg)))))
12816 (message "%d TODO entries found"
12817 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12819 (defun org--deadline-or-schedule (arg type time)
12820 "Insert DEADLINE or SCHEDULE information in current entry.
12821 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12822 `org-schedule' for information about ARG and TIME arguments."
12823 (let* ((deadline? (eq type 'deadline))
12824 (keyword (if deadline? org-deadline-string org-scheduled-string))
12825 (log (if deadline? org-log-redeadline org-log-reschedule))
12826 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12827 (old-date-time (and old-date (org-time-string-to-time old-date)))
12828 ;; Save repeater cookie from either TIME or current scheduled
12829 ;; time stamp. We are going to insert it back at the end of
12830 ;; the process.
12831 (repeater (or (and (org-string-nw-p time)
12832 ;; We use `org-repeat-re' because we need
12833 ;; to tell the difference between a real
12834 ;; repeater and a time delta, e.g. "+2d".
12835 (string-match org-repeat-re time)
12836 (match-string 1 time))
12837 (and (org-string-nw-p old-date)
12838 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12839 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12840 old-date)
12841 (match-string 1 old-date)))))
12842 (pcase arg
12843 (`(4)
12844 (when (and old-date log)
12845 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12846 nil old-date log))
12847 (org-remove-timestamp-with-keyword keyword)
12848 (message (if deadline? "Item no longer has a deadline."
12849 "Item is no longer scheduled.")))
12850 (`(16)
12851 (save-excursion
12852 (org-back-to-heading t)
12853 (let ((regexp (if deadline? org-deadline-time-regexp
12854 org-scheduled-time-regexp)))
12855 (if (not (re-search-forward regexp (line-end-position 2) t))
12856 (user-error (if deadline? "No deadline information to update"
12857 "No scheduled information to update"))
12858 (let* ((rpl0 (match-string 1))
12859 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12860 (msg (if deadline? "Warn starting from" "Delay until")))
12861 (replace-match
12862 (concat keyword
12863 " <" rpl
12864 (format " -%dd"
12865 (abs (- (time-to-days
12866 (save-match-data
12867 (org-read-date
12868 nil t nil msg old-date-time)))
12869 (time-to-days old-date-time))))
12870 ">") t t))))))
12872 (org-add-planning-info type time 'closed)
12873 (when (and old-date
12875 (not (equal old-date org-last-inserted-timestamp)))
12876 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12877 org-last-inserted-timestamp
12878 old-date
12879 log))
12880 (when repeater
12881 (save-excursion
12882 (org-back-to-heading t)
12883 (when (re-search-forward
12884 (concat keyword " " org-last-inserted-timestamp)
12885 (line-end-position 2)
12887 (goto-char (1- (match-end 0)))
12888 (insert " " repeater)
12889 (setq org-last-inserted-timestamp
12890 (concat (substring org-last-inserted-timestamp 0 -1)
12891 " " repeater
12892 (substring org-last-inserted-timestamp -1))))))
12893 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12894 org-last-inserted-timestamp)))))
12896 (defun org-deadline (arg &optional time)
12897 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12898 With one universal prefix argument, remove any deadline from the item.
12899 With two universal prefix arguments, prompt for a warning delay.
12900 With argument TIME, set the deadline at the corresponding date. TIME
12901 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12902 (interactive "P")
12903 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12904 (org-map-entries
12905 (lambda () (org--deadline-or-schedule arg 'deadline time))
12907 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12908 'region-start-level
12909 'region)
12910 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12911 (org--deadline-or-schedule arg 'deadline time)))
12913 (defun org-schedule (arg &optional time)
12914 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12915 With one universal prefix argument, remove any scheduling date from the item.
12916 With two universal prefix arguments, prompt for a delay cookie.
12917 With argument TIME, scheduled at the corresponding date. TIME can
12918 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12919 (interactive "P")
12920 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12921 (org-map-entries
12922 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12924 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12925 'region-start-level
12926 'region)
12927 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12928 (org--deadline-or-schedule arg 'scheduled time)))
12930 (defun org-get-scheduled-time (pom &optional inherit)
12931 "Get the scheduled time as a time tuple, of a format suitable
12932 for calling org-schedule with, or if there is no scheduling,
12933 returns nil."
12934 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12935 (when time
12936 (apply 'encode-time (org-parse-time-string time)))))
12938 (defun org-get-deadline-time (pom &optional inherit)
12939 "Get the deadline as a time tuple, of a format suitable for
12940 calling org-deadline with, or if there is no scheduling, returns
12941 nil."
12942 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12943 (when time
12944 (apply 'encode-time (org-parse-time-string time)))))
12946 (defun org-remove-timestamp-with-keyword (keyword)
12947 "Remove all time stamps with KEYWORD in the current entry."
12948 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12949 beg)
12950 (save-excursion
12951 (org-back-to-heading t)
12952 (setq beg (point))
12953 (outline-next-heading)
12954 (while (re-search-backward re beg t)
12955 (replace-match "")
12956 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12957 (equal (char-before) ?\ ))
12958 (backward-delete-char 1)
12959 (when (string-match "^[ \t]*$" (buffer-substring
12960 (point-at-bol) (point-at-eol)))
12961 (delete-region (point-at-bol)
12962 (min (point-max) (1+ (point-at-eol))))))))))
12964 (defvar org-time-was-given) ; dynamically scoped parameter
12965 (defvar org-end-time-was-given) ; dynamically scoped parameter
12967 (defun org-at-planning-p ()
12968 "Non-nil when point is on a planning info line."
12969 ;; This is as accurate and faster than `org-element-at-point' since
12970 ;; planning info location is fixed in the section.
12971 (org-with-wide-buffer
12972 (beginning-of-line)
12973 (and (looking-at-p org-planning-line-re)
12974 (eq (point)
12975 (ignore-errors
12976 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12977 (org-back-to-heading t)
12978 (org-with-limited-levels (org-back-to-heading t)))
12979 (line-beginning-position 2))))))
12981 (defun org-add-planning-info (what &optional time &rest remove)
12982 "Insert new timestamp with keyword in the planning line.
12983 WHAT indicates what kind of time stamp to add. It is a symbol
12984 among `closed', `deadline', `scheduled' and nil. TIME indicates
12985 the time to use. If none is given, the user is prompted for
12986 a date. REMOVE indicates what kind of entries to remove. An old
12987 WHAT entry will also be removed."
12988 (let (org-time-was-given org-end-time-was-given default-time default-input)
12989 (catch 'exit
12990 (when (and (memq what '(scheduled deadline))
12991 (or (not time)
12992 (and (stringp time)
12993 (string-match "^[-+]+[0-9]" time))))
12994 ;; Try to get a default date/time from existing timestamp
12995 (save-excursion
12996 (org-back-to-heading t)
12997 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12998 (when (re-search-forward (if (eq what 'scheduled)
12999 org-scheduled-time-regexp
13000 org-deadline-time-regexp)
13001 end t)
13002 (setq ts (match-string 1)
13003 default-time (apply 'encode-time (org-parse-time-string ts))
13004 default-input (and ts (org-get-compact-tod ts)))))))
13005 (when what
13006 (setq time
13007 (if (stringp time)
13008 ;; This is a string (relative or absolute), set
13009 ;; proper date.
13010 (apply #'encode-time
13011 (org-read-date-analyze
13012 time default-time (decode-time default-time)))
13013 ;; If necessary, get the time from the user
13014 (or time (org-read-date nil 'to-time nil nil
13015 default-time default-input)))))
13017 (org-with-wide-buffer
13018 (org-back-to-heading t)
13019 (forward-line)
13020 (unless (bolp) (insert "\n"))
13021 (cond ((looking-at-p org-planning-line-re)
13022 ;; Move to current indentation.
13023 (skip-chars-forward " \t")
13024 ;; Check if we have to remove something.
13025 (dolist (type (if what (cons what remove) remove))
13026 (save-excursion
13027 (when (re-search-forward
13028 (cl-case type
13029 (closed org-closed-time-regexp)
13030 (deadline org-deadline-time-regexp)
13031 (scheduled org-scheduled-time-regexp)
13032 (otherwise
13033 (error "Invalid planning type: %s" type)))
13034 (line-end-position) t)
13035 ;; Delete until next keyword or end of line.
13036 (delete-region
13037 (match-beginning 0)
13038 (if (re-search-forward org-keyword-time-not-clock-regexp
13039 (line-end-position)
13041 (match-beginning 0)
13042 (line-end-position))))))
13043 ;; If there is nothing more to add and no more keyword
13044 ;; is left, remove the line completely.
13045 (if (and (looking-at-p "[ \t]*$") (not what))
13046 (delete-region (line-beginning-position)
13047 (line-beginning-position 2))
13048 ;; If we removed last keyword, do not leave trailing
13049 ;; white space at the end of line.
13050 (let ((p (point)))
13051 (save-excursion
13052 (end-of-line)
13053 (unless (= (skip-chars-backward " \t" p) 0)
13054 (delete-region (point) (line-end-position)))))))
13055 ((not what) (throw 'exit nil)) ; Nothing to do.
13056 (t (insert-before-markers "\n")
13057 (backward-char 1)
13058 (when org-adapt-indentation
13059 (indent-to-column (1+ (org-outline-level))))))
13060 (when what
13061 ;; Insert planning keyword.
13062 (insert (cl-case what
13063 (closed org-closed-string)
13064 (deadline org-deadline-string)
13065 (scheduled org-scheduled-string)
13066 (otherwise (error "Invalid planning type: %s" what)))
13067 " ")
13068 ;; Insert associated timestamp.
13069 (let ((ts (org-insert-time-stamp
13070 time
13071 (or org-time-was-given
13072 (and (eq what 'closed) org-log-done-with-time))
13073 (eq what 'closed)
13074 nil nil (list org-end-time-was-given))))
13075 (unless (eolp) (insert " "))
13076 ts))))))
13078 (defvar org-log-note-marker (make-marker)
13079 "Marker pointing at the entry where the note is to be inserted.")
13080 (defvar org-log-note-purpose nil)
13081 (defvar org-log-note-state nil)
13082 (defvar org-log-note-previous-state nil)
13083 (defvar org-log-note-extra nil)
13084 (defvar org-log-note-window-configuration nil)
13085 (defvar org-log-note-return-to (make-marker))
13086 (defvar org-log-note-effective-time nil
13087 "Remembered current time so that dynamically scoped
13088 `org-extend-today-until' affects timestamps in state change log")
13090 (defvar org-log-post-message nil
13091 "Message to be displayed after a log note has been stored.
13092 The auto-repeater uses this.")
13094 (defun org-add-note ()
13095 "Add a note to the current entry.
13096 This is done in the same way as adding a state change note."
13097 (interactive)
13098 (org-add-log-setup 'note))
13100 (defun org-log-beginning (&optional create)
13101 "Return expected start of log notes in current entry.
13102 When optional argument CREATE is non-nil, the function creates
13103 a drawer to store notes, if necessary. Returned position ignores
13104 narrowing."
13105 (org-with-wide-buffer
13106 (let ((drawer (org-log-into-drawer)))
13107 (cond
13108 (drawer
13109 (org-end-of-meta-data)
13110 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13111 (end (if (org-at-heading-p) (point)
13112 (save-excursion (outline-next-heading) (point))))
13113 (case-fold-search t))
13114 (catch 'exit
13115 ;; Try to find existing drawer.
13116 (while (re-search-forward regexp end t)
13117 (let ((element (org-element-at-point)))
13118 (when (eq (org-element-type element) 'drawer)
13119 (let ((cend (org-element-property :contents-end element)))
13120 (when (and (not org-log-states-order-reversed) cend)
13121 (goto-char cend)))
13122 (throw 'exit nil))))
13123 ;; No drawer found. Create one, if permitted.
13124 (when create
13125 (unless (bolp) (insert "\n"))
13126 (let ((beg (point)))
13127 (insert ":" drawer ":\n:END:\n")
13128 (org-indent-region beg (point))
13129 (org-flag-region
13130 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13131 (end-of-line -1)))))
13133 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13134 (skip-chars-forward " \t\n")
13135 (beginning-of-line)
13136 (unless org-log-states-order-reversed
13137 (org-skip-over-state-notes)
13138 (skip-chars-backward " \t\n")
13139 (forward-line)))))
13140 (if (bolp) (point) (line-beginning-position 2))))
13142 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13143 "Set up the post command hook to take a note.
13144 If this is about to TODO state change, the new state is expected in STATE.
13145 HOW is an indicator what kind of note should be created.
13146 EXTRA is additional text that will be inserted into the notes buffer."
13147 (move-marker org-log-note-marker (point))
13148 (setq org-log-note-purpose purpose
13149 org-log-note-state state
13150 org-log-note-previous-state prev-state
13151 org-log-note-how how
13152 org-log-note-extra extra
13153 org-log-note-effective-time (org-current-effective-time))
13154 (add-hook 'post-command-hook 'org-add-log-note 'append))
13156 (defun org-skip-over-state-notes ()
13157 "Skip past the list of State notes in an entry."
13158 (when (ignore-errors (goto-char (org-in-item-p)))
13159 (let* ((struct (org-list-struct))
13160 (prevs (org-list-prevs-alist struct))
13161 (regexp
13162 (concat "[ \t]*- +"
13163 (replace-regexp-in-string
13164 " +" " +"
13165 (org-replace-escapes
13166 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13167 `(("%d" . ,org-ts-regexp-inactive)
13168 ("%D" . ,org-ts-regexp)
13169 ("%s" . "\"\\S-+\"")
13170 ("%S" . "\"\\S-+\"")
13171 ("%t" . ,org-ts-regexp-inactive)
13172 ("%T" . ,org-ts-regexp)
13173 ("%u" . ".*?")
13174 ("%U" . ".*?")))))))
13175 (while (looking-at-p regexp)
13176 (goto-char (or (org-list-get-next-item (point) struct prevs)
13177 (org-list-get-item-end (point) struct)))))))
13179 (defun org-add-log-note (&optional _purpose)
13180 "Pop up a window for taking a note, and add this note later."
13181 (remove-hook 'post-command-hook 'org-add-log-note)
13182 (setq org-log-note-window-configuration (current-window-configuration))
13183 (delete-other-windows)
13184 (move-marker org-log-note-return-to (point))
13185 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13186 (goto-char org-log-note-marker)
13187 (org-switch-to-buffer-other-window "*Org Note*")
13188 (erase-buffer)
13189 (if (memq org-log-note-how '(time state))
13190 (org-store-log-note)
13191 (let ((org-inhibit-startup t)) (org-mode))
13192 (insert (format "# Insert note for %s.
13193 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13194 (cond
13195 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13196 ((eq org-log-note-purpose 'done) "closed todo item")
13197 ((eq org-log-note-purpose 'state)
13198 (format "state change from \"%s\" to \"%s\""
13199 (or org-log-note-previous-state "")
13200 (or org-log-note-state "")))
13201 ((eq org-log-note-purpose 'reschedule)
13202 "rescheduling")
13203 ((eq org-log-note-purpose 'delschedule)
13204 "no longer scheduled")
13205 ((eq org-log-note-purpose 'redeadline)
13206 "changing deadline")
13207 ((eq org-log-note-purpose 'deldeadline)
13208 "removing deadline")
13209 ((eq org-log-note-purpose 'refile)
13210 "refiling")
13211 ((eq org-log-note-purpose 'note)
13212 "this entry")
13213 (t (error "This should not happen")))))
13214 (when org-log-note-extra (insert org-log-note-extra))
13215 (setq-local org-finish-function 'org-store-log-note)
13216 (run-hooks 'org-log-buffer-setup-hook)))
13218 (defvar org-note-abort nil) ; dynamically scoped
13219 (defun org-store-log-note ()
13220 "Finish taking a log note, and insert it to where it belongs."
13221 (let ((txt (prog1 (buffer-string)
13222 (kill-buffer)))
13223 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13224 lines)
13225 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13226 (setq txt (replace-match "" t t txt)))
13227 (when (string-match "\\s-+\\'" txt)
13228 (setq txt (replace-match "" t t txt)))
13229 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13230 (when (org-string-nw-p note)
13231 (setq note
13232 (org-replace-escapes
13233 note
13234 (list (cons "%u" (user-login-name))
13235 (cons "%U" user-full-name)
13236 (cons "%t" (format-time-string
13237 (org-time-stamp-format 'long 'inactive)
13238 org-log-note-effective-time))
13239 (cons "%T" (format-time-string
13240 (org-time-stamp-format 'long nil)
13241 org-log-note-effective-time))
13242 (cons "%d" (format-time-string
13243 (org-time-stamp-format nil 'inactive)
13244 org-log-note-effective-time))
13245 (cons "%D" (format-time-string
13246 (org-time-stamp-format nil nil)
13247 org-log-note-effective-time))
13248 (cons "%s" (cond
13249 ((not org-log-note-state) "")
13250 ((string-match-p org-ts-regexp
13251 org-log-note-state)
13252 (format "\"[%s]\""
13253 (substring org-log-note-state 1 -1)))
13254 (t (format "\"%s\"" org-log-note-state))))
13255 (cons "%S"
13256 (cond
13257 ((not org-log-note-previous-state) "")
13258 ((string-match-p org-ts-regexp
13259 org-log-note-previous-state)
13260 (format "\"[%s]\""
13261 (substring
13262 org-log-note-previous-state 1 -1)))
13263 (t (format "\"%s\""
13264 org-log-note-previous-state)))))))
13265 (when lines (setq note (concat note " \\\\")))
13266 (push note lines))
13267 (when (and lines (not org-note-abort))
13268 (with-current-buffer (marker-buffer org-log-note-marker)
13269 (org-with-wide-buffer
13270 ;; Find location for the new note.
13271 (goto-char org-log-note-marker)
13272 (set-marker org-log-note-marker nil)
13273 ;; Note associated to a clock is to be located right after
13274 ;; the clock. Do not move point.
13275 (unless (eq org-log-note-purpose 'clock-out)
13276 (goto-char (org-log-beginning t)))
13277 ;; Make sure point is at the beginning of an empty line.
13278 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13279 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13280 ;; In an existing list, add a new item at the top level.
13281 ;; Otherwise, indent line like a regular one.
13282 (let ((itemp (org-in-item-p)))
13283 (if itemp
13284 (indent-line-to
13285 (let ((struct (save-excursion
13286 (goto-char itemp) (org-list-struct))))
13287 (org-list-get-ind (org-list-get-top-point struct) struct)))
13288 (org-indent-line)))
13289 (insert (org-list-bullet-string "-") (pop lines))
13290 (let ((ind (org-list-item-body-column (line-beginning-position))))
13291 (dolist (line lines)
13292 (insert "\n")
13293 (indent-line-to ind)
13294 (insert line)))
13295 (message "Note stored")
13296 (org-back-to-heading t))
13297 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13298 ;; from within `org-add-log-note' because `buffer-undo-list'
13299 ;; is then modified outside of `org-with-remote-undo'.
13300 (when (eq this-command 'org-agenda-todo)
13301 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13302 ;; Don't add undo information when called from `org-agenda-todo'.
13303 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13304 (set-window-configuration org-log-note-window-configuration)
13305 (with-current-buffer (marker-buffer org-log-note-return-to)
13306 (goto-char org-log-note-return-to))
13307 (move-marker org-log-note-return-to nil)
13308 (when org-log-post-message (message "%s" org-log-post-message))))
13310 (defun org-remove-empty-drawer-at (pos)
13311 "Remove an empty drawer at position POS.
13312 POS may also be a marker."
13313 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13314 (org-with-wide-buffer
13315 (goto-char pos)
13316 (let ((drawer (org-element-at-point)))
13317 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13318 (not (org-element-property :contents-begin drawer)))
13319 (delete-region (org-element-property :begin drawer)
13320 (progn (goto-char (org-element-property :end drawer))
13321 (skip-chars-backward " \r\t\n")
13322 (forward-line)
13323 (point))))))))
13325 (defvar org-ts-type nil)
13326 (defun org-sparse-tree (&optional arg type)
13327 "Create a sparse tree, prompt for the details.
13328 This command can create sparse trees. You first need to select the type
13329 of match used to create the tree:
13331 t Show all TODO entries.
13332 T Show entries with a specific TODO keyword.
13333 m Show entries selected by a tags/property match.
13334 p Enter a property name and its value (both with completion on existing
13335 names/values) and show entries with that property.
13336 r Show entries matching a regular expression (`/' can be used as well).
13337 b Show deadlines and scheduled items before a date.
13338 a Show deadlines and scheduled items after a date.
13339 d Show deadlines due within `org-deadline-warning-days'.
13340 D Show deadlines and scheduled items between a date range."
13341 (interactive "P")
13342 (setq type (or type org-sparse-tree-default-date-type))
13343 (setq org-ts-type type)
13344 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13345 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13346 \[c]ycle through date types: %s"
13347 (cl-case type
13348 (all "all timestamps")
13349 (scheduled "only scheduled")
13350 (deadline "only deadline")
13351 (active "only active timestamps")
13352 (inactive "only inactive timestamps")
13353 (closed "with a closed time-stamp")
13354 (otherwise "scheduled/deadline")))
13355 (let ((answer (read-char-exclusive)))
13356 (cl-case answer
13358 (org-sparse-tree
13360 (cadr
13361 (memq type '(nil all scheduled deadline active inactive closed)))))
13362 (?d (call-interactively 'org-check-deadlines))
13363 (?b (call-interactively 'org-check-before-date))
13364 (?a (call-interactively 'org-check-after-date))
13365 (?D (call-interactively 'org-check-dates-range))
13366 (?t (call-interactively 'org-show-todo-tree))
13367 (?T (org-show-todo-tree '(4)))
13368 (?m (call-interactively 'org-match-sparse-tree))
13369 ((?p ?P)
13370 (let* ((kwd (completing-read
13371 "Property: " (mapcar #'list (org-buffer-property-keys))))
13372 (value (completing-read
13373 "Value: " (mapcar #'list (org-property-values kwd)))))
13374 (unless (string-match "\\`{.*}\\'" value)
13375 (setq value (concat "\"" value "\"")))
13376 (org-match-sparse-tree arg (concat kwd "=" value))))
13377 ((?r ?R ?/) (call-interactively 'org-occur))
13378 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13380 (defvar-local org-occur-highlights nil
13381 "List of overlays used for occur matches.")
13382 (defvar-local org-occur-parameters nil
13383 "Parameters of the active org-occur calls.
13384 This is a list, each call to org-occur pushes as cons cell,
13385 containing the regular expression and the callback, onto the list.
13386 The list can contain several entries if `org-occur' has been called
13387 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13388 will only contain one set of parameters. When the highlights are
13389 removed (for example with `C-c C-c', or with the next edit (depending
13390 on `org-remove-highlights-with-change'), this variable is emptied
13391 as well.")
13393 (defun org-occur (regexp &optional keep-previous callback)
13394 "Make a compact tree which shows all matches of REGEXP.
13396 The tree will show the lines where the regexp matches, and any other context
13397 defined in `org-show-context-detail', which see.
13399 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13400 done by a previous call to `org-occur' will be kept, to allow stacking of
13401 calls to this command.
13403 Optional argument CALLBACK can be a function of no argument. In this case,
13404 it is called with point at the end of the match, match data being set
13405 accordingly. Current match is shown only if the return value is non-nil.
13406 The function must neither move point nor alter narrowing."
13407 (interactive "sRegexp: \nP")
13408 (when (equal regexp "")
13409 (user-error "Regexp cannot be empty"))
13410 (unless keep-previous
13411 (org-remove-occur-highlights nil nil t))
13412 (push (cons regexp callback) org-occur-parameters)
13413 (let ((cnt 0))
13414 (save-excursion
13415 (goto-char (point-min))
13416 (when (or (not keep-previous) ; do not want to keep
13417 (not org-occur-highlights)) ; no previous matches
13418 ;; hide everything
13419 (org-overview))
13420 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13421 (isearch-no-upper-case-p regexp t)
13422 org-occur-case-fold-search)))
13423 (while (re-search-forward regexp nil t)
13424 (when (or (not callback)
13425 (save-match-data (funcall callback)))
13426 (setq cnt (1+ cnt))
13427 (when org-highlight-sparse-tree-matches
13428 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13429 (org-show-context 'occur-tree)))))
13430 (when org-remove-highlights-with-change
13431 (add-hook 'before-change-functions 'org-remove-occur-highlights
13432 nil 'local))
13433 (unless org-sparse-tree-open-archived-trees
13434 (org-hide-archived-subtrees (point-min) (point-max)))
13435 (run-hooks 'org-occur-hook)
13436 (when (called-interactively-p 'interactive)
13437 (message "%d match(es) for regexp %s" cnt regexp))
13438 cnt))
13440 (defun org-occur-next-match (&optional n _reset)
13441 "Function for `next-error-function' to find sparse tree matches.
13442 N is the number of matches to move, when negative move backwards.
13443 This function always goes back to the starting point when no
13444 match is found."
13445 (let* ((limit (if (< n 0) (point-min) (point-max)))
13446 (search-func (if (< n 0)
13447 'previous-single-char-property-change
13448 'next-single-char-property-change))
13449 (n (abs n))
13450 (pos (point))
13452 (catch 'exit
13453 (while (setq p1 (funcall search-func (point) 'org-type))
13454 (when (equal p1 limit)
13455 (goto-char pos)
13456 (user-error "No more matches"))
13457 (when (equal (get-char-property p1 'org-type) 'org-occur)
13458 (setq n (1- n))
13459 (when (= n 0)
13460 (goto-char p1)
13461 (throw 'exit (point))))
13462 (goto-char p1))
13463 (goto-char p1)
13464 (user-error "No more matches"))))
13466 (defun org-highlight-new-match (beg end)
13467 "Highlight from BEG to END and mark the highlight is an occur headline."
13468 (let ((ov (make-overlay beg end)))
13469 (overlay-put ov 'face 'secondary-selection)
13470 (overlay-put ov 'org-type 'org-occur)
13471 (push ov org-occur-highlights)))
13473 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13474 "Remove the occur highlights from the buffer.
13475 BEG and END are ignored. If NOREMOVE is nil, remove this function
13476 from the `before-change-functions' in the current buffer."
13477 (interactive)
13478 (unless org-inhibit-highlight-removal
13479 (mapc #'delete-overlay org-occur-highlights)
13480 (setq org-occur-highlights nil)
13481 (setq org-occur-parameters nil)
13482 (unless noremove
13483 (remove-hook 'before-change-functions
13484 'org-remove-occur-highlights 'local))))
13486 ;;;; Priorities
13488 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13489 "Regular expression matching the priority indicator.")
13491 (defvar org-remove-priority-next-time nil)
13493 (defun org-priority-up ()
13494 "Increase the priority of the current item."
13495 (interactive)
13496 (org-priority 'up))
13498 (defun org-priority-down ()
13499 "Decrease the priority of the current item."
13500 (interactive)
13501 (org-priority 'down))
13503 (defun org-priority (&optional action _show)
13504 "Change the priority of an item.
13505 ACTION can be `set', `up', `down', or a character."
13506 (interactive "P")
13507 (if (equal action '(4))
13508 (org-show-priority)
13509 (unless org-enable-priority-commands
13510 (user-error "Priority commands are disabled"))
13511 (setq action (or action 'set))
13512 (let (current new news have remove)
13513 (save-excursion
13514 (org-back-to-heading t)
13515 (when (looking-at org-priority-regexp)
13516 (setq current (string-to-char (match-string 2))
13517 have t))
13518 (cond
13519 ((eq action 'remove)
13520 (setq remove t new ?\ ))
13521 ((or (eq action 'set)
13522 (integerp action))
13523 (if (not (eq action 'set))
13524 (setq new action)
13525 (message "Priority %c-%c, SPC to remove: "
13526 org-highest-priority org-lowest-priority)
13527 (save-match-data
13528 (setq new (read-char-exclusive))))
13529 (when (and (= (upcase org-highest-priority) org-highest-priority)
13530 (= (upcase org-lowest-priority) org-lowest-priority))
13531 (setq new (upcase new)))
13532 (cond ((equal new ?\ ) (setq remove t))
13533 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13534 (user-error "Priority must be between `%c' and `%c'"
13535 org-highest-priority org-lowest-priority))))
13536 ((eq action 'up)
13537 (setq new (if have
13538 (1- current) ; normal cycling
13539 ;; last priority was empty
13540 (if (eq last-command this-command)
13541 org-lowest-priority ; wrap around empty to lowest
13542 ;; default
13543 (if org-priority-start-cycle-with-default
13544 org-default-priority
13545 (1- org-default-priority))))))
13546 ((eq action 'down)
13547 (setq new (if have
13548 (1+ current) ; normal cycling
13549 ;; last priority was empty
13550 (if (eq last-command this-command)
13551 org-highest-priority ; wrap around empty to highest
13552 ;; default
13553 (if org-priority-start-cycle-with-default
13554 org-default-priority
13555 (1+ org-default-priority))))))
13556 (t (user-error "Invalid action")))
13557 (when (or (< (upcase new) org-highest-priority)
13558 (> (upcase new) org-lowest-priority))
13559 (if (and (memq action '(up down))
13560 (not have) (not (eq last-command this-command)))
13561 ;; `new' is from default priority
13562 (error
13563 "The default can not be set, see `org-default-priority' why")
13564 ;; normal cycling: `new' is beyond highest/lowest priority
13565 ;; and is wrapped around to the empty priority
13566 (setq remove t)))
13567 (setq news (format "%c" new))
13568 (if have
13569 (if remove
13570 (replace-match "" t t nil 1)
13571 (replace-match news t t nil 2))
13572 (if remove
13573 (user-error "No priority cookie found in line")
13574 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13575 (if (match-end 2)
13576 (progn
13577 (goto-char (match-end 2))
13578 (insert " [#" news "]"))
13579 (goto-char (match-beginning 3))
13580 (insert "[#" news "] "))))
13581 (org-align-tags))
13582 (if remove
13583 (message "Priority removed")
13584 (message "Priority of current item set to %s" news)))))
13586 (defun org-show-priority ()
13587 "Show the priority of the current item.
13588 This priority is composed of the main priority given with the [#A] cookies,
13589 and by additional input from the age of a schedules or deadline entry."
13590 (interactive)
13591 (let ((pri (if (eq major-mode 'org-agenda-mode)
13592 (org-get-at-bol 'priority)
13593 (save-excursion
13594 (save-match-data
13595 (beginning-of-line)
13596 (and (looking-at org-heading-regexp)
13597 (org-get-priority (match-string 0))))))))
13598 (message "Priority is %d" (if pri pri -1000))))
13600 (defun org-get-priority (s)
13601 "Find priority cookie and return priority."
13602 (save-match-data
13603 (if (functionp org-get-priority-function)
13604 (funcall org-get-priority-function)
13605 (if (not (string-match org-priority-regexp s))
13606 (* 1000 (- org-lowest-priority org-default-priority))
13607 (* 1000 (- org-lowest-priority
13608 (string-to-char (match-string 2 s))))))))
13610 ;;;; Tags
13612 (defvar org-agenda-archives-mode)
13613 (defvar org-map-continue-from nil
13614 "Position from where mapping should continue.
13615 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13617 (defvar org-scanner-tags nil
13618 "The current tag list while the tags scanner is running.")
13620 (defvar org-trust-scanner-tags nil
13621 "Should `org-get-tags' use the tags for the scanner.
13622 This is for internal dynamical scoping only.
13623 When this is non-nil, the function `org-get-tags' will return the value
13624 of `org-scanner-tags' instead of building the list by itself. This
13625 can lead to large speed-ups when the tags scanner is used in a file with
13626 many entries, and when the list of tags is retrieved, for example to
13627 obtain a list of properties. Building the tags list for each entry in such
13628 a file becomes an N^2 operation - but with this variable set, it scales
13629 as N.")
13631 (defvar org--matcher-tags-todo-only nil)
13633 (defun org-scan-tags (action matcher todo-only &optional start-level)
13634 "Scan headline tags with inheritance and produce output ACTION.
13636 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13637 or `agenda' to produce an entry list for an agenda view. It can also be
13638 a Lisp form or a function that should be called at each matched headline, in
13639 this case the return value is a list of all return values from these calls.
13641 MATCHER is a function accepting three arguments, returning
13642 a non-nil value whenever a given set of tags qualifies a headline
13643 for inclusion. See `org-make-tags-matcher' for more information.
13644 As a special case, it can also be set to t (respectively nil) in
13645 order to match all (respectively none) headline.
13647 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13648 included in the output.
13650 START-LEVEL can be a string with asterisks, reducing the scope to
13651 headlines matching this string."
13652 (require 'org-agenda)
13653 (let* ((re (concat "^"
13654 (if start-level
13655 ;; Get the correct level to match
13656 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13657 org-outline-regexp)
13658 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13659 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13660 (props (list 'face 'default
13661 'done-face 'org-agenda-done
13662 'undone-face 'default
13663 'mouse-face 'highlight
13664 'org-not-done-regexp org-not-done-regexp
13665 'org-todo-regexp org-todo-regexp
13666 'org-complex-heading-regexp org-complex-heading-regexp
13667 'help-echo
13668 (format "mouse-2 or RET jump to Org file %S"
13669 (abbreviate-file-name
13670 (or (buffer-file-name (buffer-base-buffer))
13671 (buffer-name (buffer-base-buffer)))))))
13672 (org-map-continue-from nil)
13673 lspos tags tags-list
13674 (tags-alist (list (cons 0 org-file-tags)))
13675 (llast 0) rtn rtn1 level category i txt
13676 todo marker entry priority
13677 ts-date ts-date-type ts-date-pair)
13678 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13679 (setq action (list 'lambda nil action)))
13680 (save-excursion
13681 (goto-char (point-min))
13682 (when (eq action 'sparse-tree)
13683 (org-overview)
13684 (org-remove-occur-highlights))
13685 (while (let (case-fold-search)
13686 (re-search-forward re nil t))
13687 (setq org-map-continue-from nil)
13688 (catch :skip
13689 ;; Ignore closing parts of inline tasks.
13690 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13691 (throw :skip t))
13692 (setq todo
13693 ;; TODO: is the 1-2 difference a bug?
13694 (when (match-end 1) (match-string-no-properties 2))
13695 tags (when (match-end 4) (match-string-no-properties 4)))
13696 (goto-char (setq lspos (match-beginning 0)))
13697 (setq level (org-reduced-level (org-outline-level))
13698 category (org-get-category))
13699 (when (eq action 'agenda)
13700 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13701 ts-date (car ts-date-pair)
13702 ts-date-type (cdr ts-date-pair)))
13703 (setq i llast llast level)
13704 ;; remove tag lists from same and sublevels
13705 (while (>= i level)
13706 (when (setq entry (assoc i tags-alist))
13707 (setq tags-alist (delete entry tags-alist)))
13708 (setq i (1- i)))
13709 ;; add the next tags
13710 (when tags
13711 (setq tags (org-split-string tags ":")
13712 tags-alist
13713 (cons (cons level tags) tags-alist)))
13714 ;; compile tags for current headline
13715 (setq tags-list
13716 (if org-use-tag-inheritance
13717 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13718 tags)
13719 org-scanner-tags tags-list)
13720 (when org-use-tag-inheritance
13721 (setcdr (car tags-alist)
13722 (mapcar (lambda (x)
13723 (setq x (copy-sequence x))
13724 (org-add-prop-inherited x))
13725 (cdar tags-alist))))
13726 (when (and tags org-use-tag-inheritance
13727 (or (not (eq t org-use-tag-inheritance))
13728 org-tags-exclude-from-inheritance))
13729 ;; Selective inheritance, remove uninherited ones.
13730 (setcdr (car tags-alist)
13731 (org-remove-uninherited-tags (cdar tags-alist))))
13732 (when (and
13734 ;; eval matcher only when the todo condition is OK
13735 (and (or (not todo-only) (member todo org-todo-keywords-1))
13736 (if (functionp matcher)
13737 (let ((case-fold-search t) (org-trust-scanner-tags t))
13738 (funcall matcher todo tags-list level))
13739 matcher))
13741 ;; Call the skipper, but return t if it does not
13742 ;; skip, so that the `and' form continues evaluating.
13743 (progn
13744 (unless (eq action 'sparse-tree) (org-agenda-skip))
13747 ;; Check if timestamps are deselecting this entry
13748 (or (not todo-only)
13749 (and (member todo org-todo-keywords-1)
13750 (or (not org-agenda-tags-todo-honor-ignore-options)
13751 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13753 ;; select this headline
13754 (cond
13755 ((eq action 'sparse-tree)
13756 (and org-highlight-sparse-tree-matches
13757 (org-get-heading) (match-end 0)
13758 (org-highlight-new-match
13759 (match-beginning 1) (match-end 1)))
13760 (org-show-context 'tags-tree))
13761 ((eq action 'agenda)
13762 (setq txt (org-agenda-format-item
13764 (concat
13765 (if (eq org-tags-match-list-sublevels 'indented)
13766 (make-string (1- level) ?.) "")
13767 (org-get-heading))
13768 (make-string level ?\s)
13769 category
13770 tags-list)
13771 priority (org-get-priority txt))
13772 (goto-char lspos)
13773 (setq marker (org-agenda-new-marker))
13774 (org-add-props txt props
13775 'org-marker marker 'org-hd-marker marker 'org-category category
13776 'todo-state todo
13777 'ts-date ts-date
13778 'priority priority
13779 'type (concat "tagsmatch" ts-date-type))
13780 (push txt rtn))
13781 ((functionp action)
13782 (setq org-map-continue-from nil)
13783 (save-excursion
13784 (setq rtn1 (funcall action))
13785 (push rtn1 rtn)))
13786 (t (user-error "Invalid action")))
13788 ;; if we are to skip sublevels, jump to end of subtree
13789 (unless org-tags-match-list-sublevels
13790 (org-end-of-subtree t)
13791 (backward-char 1))))
13792 ;; Get the correct position from where to continue
13793 (if org-map-continue-from
13794 (goto-char org-map-continue-from)
13795 (and (= (point) lspos) (end-of-line 1)))))
13796 (when (and (eq action 'sparse-tree)
13797 (not org-sparse-tree-open-archived-trees))
13798 (org-hide-archived-subtrees (point-min) (point-max)))
13799 (nreverse rtn)))
13801 (defun org-remove-uninherited-tags (tags)
13802 "Remove all tags that are not inherited from the list TAGS."
13803 (cond
13804 ((eq org-use-tag-inheritance t)
13805 (if org-tags-exclude-from-inheritance
13806 (org-delete-all org-tags-exclude-from-inheritance tags)
13807 tags))
13808 ((not org-use-tag-inheritance) nil)
13809 ((stringp org-use-tag-inheritance)
13810 (delq nil (mapcar
13811 (lambda (x)
13812 (if (and (string-match org-use-tag-inheritance x)
13813 (not (member x org-tags-exclude-from-inheritance)))
13814 x nil))
13815 tags)))
13816 ((listp org-use-tag-inheritance)
13817 (delq nil (mapcar
13818 (lambda (x)
13819 (if (member x org-use-tag-inheritance) x nil))
13820 tags)))))
13822 (defun org-match-sparse-tree (&optional todo-only match)
13823 "Create a sparse tree according to tags string MATCH.
13825 MATCH is a string with match syntax. It can contain a selection
13826 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13827 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13828 those. See the manual for details.
13830 If optional argument TODO-ONLY is non-nil, only select lines that
13831 are also TODO tasks."
13832 (interactive "P")
13833 (org-agenda-prepare-buffers (list (current-buffer)))
13834 (let ((org--matcher-tags-todo-only todo-only))
13835 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13836 org--matcher-tags-todo-only)))
13838 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13840 (defvar org-cached-props nil)
13841 (defun org-cached-entry-get (pom property)
13842 (if (or (eq t org-use-property-inheritance)
13843 (and (stringp org-use-property-inheritance)
13844 (let ((case-fold-search t))
13845 (string-match-p org-use-property-inheritance property)))
13846 (and (listp org-use-property-inheritance)
13847 (member-ignore-case property org-use-property-inheritance)))
13848 ;; Caching is not possible, check it directly.
13849 (org-entry-get pom property 'inherit)
13850 ;; Get all properties, so we can do complicated checks easily.
13851 (cdr (assoc-string property
13852 (or org-cached-props
13853 (setq org-cached-props (org-entry-properties pom)))
13854 t))))
13856 (defun org-global-tags-completion-table (&optional files)
13857 "Return the list of all tags in all agenda buffer/files.
13858 Optional FILES argument is a list of files which can be used
13859 instead of the agenda files."
13860 (save-excursion
13861 (org-uniquify
13862 (delq nil
13863 (apply #'append
13864 (mapcar
13865 (lambda (file)
13866 (set-buffer (find-file-noselect file))
13867 (org--tag-add-to-alist
13868 (org-get-buffer-tags)
13869 (mapcar (lambda (x)
13870 (and (stringp (car-safe x))
13871 (list (car-safe x))))
13872 org-current-tag-alist)))
13873 (if (car-safe files) files
13874 (org-agenda-files))))))))
13876 (defun org-make-tags-matcher (match)
13877 "Create the TAGS/TODO matcher form for the selection string MATCH.
13879 Returns a cons of the selection string MATCH and a function
13880 implementing the matcher.
13882 The matcher is to be called at an Org entry, with point on the
13883 headline, and returns non-nil if the entry matches the selection
13884 string MATCH. It must be called with three arguments: the TODO
13885 keyword at the entry (or nil if none), the list of all tags at
13886 the entry including inherited ones and the reduced level of the
13887 headline. Additionally, the category of the entry, if any, must
13888 be specified as the text property `org-category' on the headline.
13890 This function sets the variable `org--matcher-tags-todo-only' to
13891 a non-nil value if the matcher restricts matching to TODO
13892 entries, otherwise it is not touched.
13894 See also `org-scan-tags'."
13895 (unless match
13896 ;; Get a new match request, with completion against the global
13897 ;; tags table and the local tags in current buffer.
13898 (let ((org-last-tags-completion-table
13899 (org--tag-add-to-alist
13900 (org-get-buffer-tags)
13901 (org-global-tags-completion-table))))
13902 (setq match
13903 (completing-read
13904 "Match: "
13905 'org-tags-completion-function nil nil nil 'org-tags-history))))
13907 (let ((match0 match)
13908 (re (concat
13909 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13910 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13911 "\\([<>=]\\{1,2\\}\\)"
13912 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13913 "\\|" org-tag-re "\\)"))
13914 (start 0)
13915 tagsmatch todomatch tagsmatcher todomatcher)
13917 ;; Expand group tags.
13918 (setq match (org-tags-expand match))
13920 ;; Check if there is a TODO part of this match, which would be the
13921 ;; part after a "/". To make sure that this slash is not part of
13922 ;; a property value to be matched against, we also check that
13923 ;; there is no / after that slash. First, find the last slash.
13924 (let ((s 0))
13925 (while (string-match "/+" match s)
13926 (setq start (match-beginning 0))
13927 (setq s (match-end 0))))
13928 (if (and (string-match "/+" match start)
13929 (not (string-match-p "\"" match start)))
13930 ;; Match contains also a TODO-matching request.
13931 (progn
13932 (setq tagsmatch (substring match 0 (match-beginning 0)))
13933 (setq todomatch (substring match (match-end 0)))
13934 (when (string-prefix-p "!" todomatch)
13935 (setq org--matcher-tags-todo-only t)
13936 (setq todomatch (substring todomatch 1)))
13937 (when (string-match "\\`\\s-*\\'" todomatch)
13938 (setq todomatch nil)))
13939 ;; Only matching tags.
13940 (setq tagsmatch match)
13941 (setq todomatch nil))
13943 ;; Make the tags matcher.
13944 (when (org-string-nw-p tagsmatch)
13945 (let ((orlist nil)
13946 (orterms (org-split-string tagsmatch "|"))
13947 term)
13948 (while (setq term (pop orterms))
13949 (while (and (equal (substring term -1) "\\") orterms)
13950 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13951 (while (string-match re term)
13952 (let* ((rest (substring term (match-end 0)))
13953 (minus (and (match-end 1)
13954 (equal (match-string 1 term) "-")))
13955 (tag (save-match-data
13956 (replace-regexp-in-string
13957 "\\\\-" "-" (match-string 2 term))))
13958 (regexp (eq (string-to-char tag) ?{))
13959 (levelp (match-end 4))
13960 (propp (match-end 5))
13962 (cond
13963 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13964 (levelp
13965 `(,(org-op-to-function (match-string 3 term))
13966 level
13967 ,(string-to-number (match-string 4 term))))
13968 (propp
13969 (let* ((gv (pcase (upcase (match-string 5 term))
13970 ("CATEGORY"
13971 '(get-text-property (point) 'org-category))
13972 ("TODO" 'todo)
13973 (p `(org-cached-entry-get nil ,p))))
13974 (pv (match-string 7 term))
13975 (regexp (eq (string-to-char pv) ?{))
13976 (strp (eq (string-to-char pv) ?\"))
13977 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13978 (po (org-op-to-function (match-string 6 term)
13979 (if timep 'time strp))))
13980 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13981 (when timep (setq pv (org-matcher-time pv)))
13982 (cond ((and regexp (eq po '/=))
13983 `(not (string-match ,pv (or ,gv ""))))
13984 (regexp `(string-match ,pv (or ,gv "")))
13985 (strp `(,po (or ,gv "") ,pv))
13987 `(,po
13988 (string-to-number (or ,gv ""))
13989 ,(string-to-number pv))))))
13990 (t `(member ,tag tags-list)))))
13991 (push (if minus `(not ,mm) mm) tagsmatcher)
13992 (setq term rest)))
13993 (push `(and ,@tagsmatcher) orlist)
13994 (setq tagsmatcher nil))
13995 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13997 ;; Make the TODO matcher.
13998 (when (org-string-nw-p todomatch)
13999 (let ((orlist nil))
14000 (dolist (term (org-split-string todomatch "|"))
14001 (while (string-match re term)
14002 (let* ((minus (and (match-end 1)
14003 (equal (match-string 1 term) "-")))
14004 (kwd (match-string 2 term))
14005 (regexp (eq (string-to-char kwd) ?{))
14006 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14007 `(equal todo ,kwd))))
14008 (push (if minus `(not ,mm) mm) todomatcher))
14009 (setq term (substring term (match-end 0))))
14010 (push (if (> (length todomatcher) 1)
14011 (cons 'and todomatcher)
14012 (car todomatcher))
14013 orlist)
14014 (setq todomatcher nil))
14015 (setq todomatcher (cons 'or orlist))))
14017 ;; Return the string and function of the matcher. If no
14018 ;; tags-specific or todo-specific matcher exists, match
14019 ;; everything.
14020 (let ((matcher (if (and tagsmatcher todomatcher)
14021 `(and ,tagsmatcher ,todomatcher)
14022 (or tagsmatcher todomatcher t))))
14023 (when org--matcher-tags-todo-only
14024 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14025 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14027 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14028 "Expand group tags in MATCH.
14030 This replaces every group tag in MATCH with a regexp tag search.
14031 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14032 will be replaced like this:
14034 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14035 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14036 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14038 Replacing by a regexp preserves the structure of the match.
14039 E.g., this expansion
14041 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14043 will match anything tagged with \"Lab\" and \"Home\", or tagged
14044 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14046 A group tag in MATCH can contain regular expressions of its own.
14047 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14048 will be replaced like this:
14050 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14052 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14053 assumed to be a single group tag, and the function will return
14054 the list of tags in this group.
14056 When DOWNCASE is non-nil, expand downcased TAGS."
14057 (if org-group-tags
14058 (let* ((case-fold-search t)
14059 (stable org-mode-syntax-table)
14060 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14061 (taggroups (if downcased
14062 (mapcar (lambda (tg) (mapcar #'downcase tg))
14063 taggroups)
14064 taggroups))
14065 (taggroups-keys (mapcar #'car taggroups))
14066 (return-match (if downcased (downcase match) match))
14067 (count 0)
14068 (work-already-expanded tags-already-expanded)
14069 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14070 ;; @ and _ are allowed as word-components in tags.
14071 (modify-syntax-entry ?@ "w" stable)
14072 (modify-syntax-entry ?_ "w" stable)
14073 ;; Temporarily replace regexp-expressions in the match-expression.
14074 (while (string-match "{.+?}" return-match)
14075 (cl-incf count)
14076 (push (match-string 0 return-match) regexps-in-match)
14077 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14078 (while (and taggroups-keys
14079 (with-syntax-table stable
14080 (string-match
14081 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14082 (regexp-opt taggroups-keys) "\\>\\)")
14083 return-match)))
14084 (let* ((dir (match-string 1 return-match))
14085 (tag (match-string 2 return-match))
14086 (tag (if downcased (downcase tag) tag)))
14087 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14088 (member tag tags-already-expanded))
14089 (setq tags-in-group (assoc tag taggroups))
14090 (push tag work-already-expanded)
14091 ;; Recursively expand each tag in the group, if the tag hasn't
14092 ;; already been expanded. Restore the match-data after all recursive calls.
14093 (save-match-data
14094 (let (tags-expanded)
14095 (dolist (x (cdr tags-in-group))
14096 (if (and (member x taggroups-keys)
14097 (not (member x work-already-expanded)))
14098 (setq tags-expanded
14099 (delete-dups
14100 (append
14101 (org-tags-expand x t downcased
14102 work-already-expanded)
14103 tags-expanded)))
14104 (setq tags-expanded
14105 (append (list x) tags-expanded)))
14106 (setq work-already-expanded
14107 (delete-dups
14108 (append tags-expanded
14109 work-already-expanded))))
14110 (setq tags-in-group
14111 (delete-dups (cons (car tags-in-group)
14112 tags-expanded)))))
14113 ;; Filter tag-regexps from tags.
14114 (setq regexp-in-group-escaped
14115 (delq nil (mapcar (lambda (x)
14116 (if (stringp x)
14117 (and (equal "{" (substring x 0 1))
14118 (equal "}" (substring x -1))
14121 tags-in-group))
14122 regexp-in-group
14123 (mapcar (lambda (x)
14124 (substring x 1 -1))
14125 regexp-in-group-escaped)
14126 tags-in-group
14127 (delq nil (mapcar (lambda (x)
14128 (if (stringp x)
14129 (and (not (equal "{" (substring x 0 1)))
14130 (not (equal "}" (substring x -1)))
14133 tags-in-group)))
14134 ;; If single-as-list, do no more in the while-loop.
14135 (if (not single-as-list)
14136 (progn
14137 (when regexp-in-group
14138 (setq regexp-in-group
14139 (concat "\\|"
14140 (mapconcat 'identity regexp-in-group
14141 "\\|"))))
14142 (setq tags-in-group
14143 (concat dir
14144 "{\\<"
14145 (regexp-opt tags-in-group)
14146 "\\>"
14147 regexp-in-group
14148 "}"))
14149 (when (stringp tags-in-group)
14150 (org-add-props tags-in-group '(grouptag t)))
14151 (setq return-match
14152 (replace-match tags-in-group t t return-match)))
14153 (setq tags-in-group
14154 (append regexp-in-group-escaped tags-in-group))))
14155 (setq taggroups-keys (delete tag taggroups-keys))))
14156 ;; Add the regular expressions back into the match-expression again.
14157 (while regexps-in-match
14158 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14159 (pop regexps-in-match)
14160 return-match t t))
14161 (cl-decf count))
14162 (if single-as-list
14163 (if tags-in-group tags-in-group (list return-match))
14164 return-match))
14165 (if single-as-list
14166 (list (if downcased (downcase match) match))
14167 match)))
14169 (defun org-op-to-function (op &optional stringp)
14170 "Turn an operator into the appropriate function."
14171 (setq op
14172 (cond
14173 ((equal op "<" ) '(< org-string< org-time<))
14174 ((equal op ">" ) '(> org-string> org-time>))
14175 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14176 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14177 ((member op '("=" "==")) '(= string= org-time=))
14178 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14179 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14181 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14182 (defvar org-tags-overlay (make-overlay 1 1))
14183 (delete-overlay org-tags-overlay)
14185 (defun org-add-prop-inherited (s)
14186 (add-text-properties 0 (length s) '(inherited t) s)
14189 (defun org-toggle-tag (tag &optional onoff)
14190 "Toggle the tag TAG for the current line.
14191 If ONOFF is `on' or `off', don't toggle but set to this state."
14192 (save-excursion
14193 (org-back-to-heading t)
14194 (let ((current
14195 ;; Reverse the tags list so any new tag is appended to the
14196 ;; current list of tags.
14197 (nreverse (org-get-tags)))
14198 res)
14199 (pcase onoff
14200 (`off (setq current (delete tag current)))
14201 ((or `on (guard (not (member tag current))))
14202 (setq res t)
14203 (cl-pushnew tag current :test #'equal))
14204 (_ (setq current (delete tag current))))
14205 (org-set-tags (nreverse current))
14206 res)))
14208 (defun org--align-tags-here (to-col)
14209 "Align tags on the current headline to TO-COL.
14210 Assume point is on a headline."
14211 (when (and (org-match-line org-tag-line-re)
14212 (< (point) (match-beginning 1)))
14213 (let ((pos (point))
14214 (shift (if (>= to-col 0) to-col
14215 (- (abs to-col) (string-width (match-string 1))))))
14216 ;; Delete all blanks before tags.
14217 (goto-char (match-beginning 1))
14218 (skip-chars-backward " \t")
14219 (delete-region (point) (match-beginning 1))
14220 ;; Insert new blanks.
14221 (insert (make-string (max 1 (- shift (current-column))) ?\s))
14222 ;; Preserve initial position, if possible. In any case, stop
14223 ;; before tags.
14224 (when (< pos (point)) (goto-char pos)))))
14226 (defun org-set-tags-command (&optional arg)
14227 "Set the tags for the current visible entry.
14229 When called with `\\[universal-argument]' prefix argument ARG, \
14230 realign all tags
14231 in the current buffer. If a region is active, set tags for
14232 all headlines in the region.
14234 This function is for interactive use only;
14235 in Lisp code use `org-set-tags' instead."
14236 (interactive "P")
14237 (cond
14238 (arg (org-align-tags t))
14239 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14240 ;; Disable `org-loop-over-headlines-in-active-region' for
14241 ;; successive calls.
14242 (let (org-loop-over-headlines-in-active-region)
14243 (org-map-entries
14244 #'org-set-tags-command
14246 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14247 'region-start-level
14248 'region)
14249 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14251 (org-back-to-heading)
14252 (let* ((all-tags (org-get-tags))
14253 (table (setq org-last-tags-completion-table
14254 (org--tag-add-to-alist
14255 (and org-complete-tags-always-offer-all-agenda-tags
14256 (org-global-tags-completion-table
14257 (org-agenda-files)))
14258 (or org-current-tag-alist (org-get-buffer-tags)))))
14259 (current-tags
14260 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14261 all-tags))
14262 (inherited-tags
14263 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14264 all-tags))
14265 (tags
14266 (replace-regexp-in-string
14267 ;; Ignore all forbidden characters in tags.
14268 "[^[:alnum:]_@#%]+" ":"
14269 (if (or (eq t org-use-fast-tag-selection)
14270 (and org-use-fast-tag-selection
14271 (delq nil (mapcar #'cdr table))))
14272 (org-fast-tag-selection
14273 current-tags
14274 inherited-tags
14275 table
14276 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14277 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14278 (org-trim (completing-read
14279 "Tags: "
14280 #'org-tags-completion-function
14281 nil nil (org-make-tag-string current-tags)
14282 'org-tags-history)))))))
14283 (org-set-tags tags)))))
14285 (defun org-align-tags (&optional all)
14286 "Align tags in current entry.
14287 When optional argument ALL is non-nil, align all tags in the
14288 visible part of the buffer."
14289 (save-excursion
14290 (if all (goto-char (point-min)) (org-back-to-heading t))
14291 (catch :single
14292 (while (re-search-forward org-tag-line-re nil t)
14293 (let* ((offset (if (bound-and-true-p org-indent-mode)
14294 (* (1- org-indent-indentation-per-level)
14295 (1- (org-current-level)))
14297 (tags-column (+ org-tags-column
14298 (if (> org-tags-column 0) (- offset) offset))))
14299 (beginning-of-line)
14300 (org--align-tags-here tags-column)
14301 (if all (forward-line) (throw :single nil)))))))
14303 (defun org-set-tags (tags)
14304 "Set the tags of the current entry to TAGS, replacing current tags.
14306 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14307 If TAGS is nil or the empty string, all tags are removed.
14309 This function assumes point is on a headline."
14310 (let ((tags (pcase tags
14311 ((pred listp) tags)
14312 ((pred stringp) (split-string (org-trim tags) ":" t))
14313 (_ (error "Invalid tag specification: %S" tags))))
14314 (change-flag nil))
14315 (when (functionp org-tags-sort-function)
14316 (setq tags (sort tags org-tags-sort-function)))
14317 (org-with-wide-buffer
14318 (unless (equal tags (org-get-tags nil t))
14319 (setq change-flag t)
14320 ;; Delete previous tags and any trailing white space.
14321 (goto-char (if (looking-at org-tag-line-re) (match-beginning 1)
14322 (line-end-position)))
14323 (skip-chars-backward " \t")
14324 (delete-region (point) (line-end-position))
14325 (when tags
14326 (save-excursion (insert " " (org-make-tag-string tags)))
14327 ;; When text is being inserted on an invisible region
14328 ;; boundary, it can be inadvertently sucked into
14329 ;; invisibility.
14330 (unless (org-invisible-p (line-beginning-position))
14331 (org-flag-region (point) (line-end-position) nil 'outline))))
14332 ;; Align tags, if any. Fix tags column if `org-indent-mode' is
14333 ;; on.
14334 (when tags (org-align-tags))
14335 (when change-flag (run-hooks 'org-after-tags-change-hook)))))
14337 (defun org-change-tag-in-region (beg end tag off)
14338 "Add or remove TAG for each entry in the region.
14339 This works in the agenda, and also in an Org buffer."
14340 (interactive
14341 (list (region-beginning) (region-end)
14342 (let ((org-last-tags-completion-table
14343 (if (derived-mode-p 'org-mode)
14344 (org--tag-add-to-alist
14345 (org-get-buffer-tags)
14346 (org-global-tags-completion-table))
14347 (org-global-tags-completion-table))))
14348 (completing-read
14349 "Tag: " 'org-tags-completion-function nil nil nil
14350 'org-tags-history))
14351 (progn
14352 (message "[s]et or [r]emove? ")
14353 (equal (read-char-exclusive) ?r))))
14354 (when (fboundp 'deactivate-mark) (deactivate-mark))
14355 (let ((agendap (equal major-mode 'org-agenda-mode))
14356 l1 l2 m buf pos newhead (cnt 0))
14357 (goto-char end)
14358 (setq l2 (1- (org-current-line)))
14359 (goto-char beg)
14360 (setq l1 (org-current-line))
14361 (cl-loop for l from l1 to l2 do
14362 (org-goto-line l)
14363 (setq m (get-text-property (point) 'org-hd-marker))
14364 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14365 (and agendap m))
14366 (setq buf (if agendap (marker-buffer m) (current-buffer))
14367 pos (if agendap m (point)))
14368 (with-current-buffer buf
14369 (save-excursion
14370 (save-restriction
14371 (goto-char pos)
14372 (setq cnt (1+ cnt))
14373 (org-toggle-tag tag (if off 'off 'on))
14374 (setq newhead (org-get-heading)))))
14375 (and agendap (org-agenda-change-all-lines newhead m))))
14376 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14378 (defun org-tags-completion-function (string _predicate &optional flag)
14379 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14380 (confirm (lambda (x) (stringp (car x)))))
14381 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14382 (setq s1 (match-string 1 string)
14383 s2 (match-string 2 string))
14384 (setq s1 "" s2 string))
14385 (cond
14386 ((eq flag nil)
14387 ;; try completion
14388 (setq rtn (try-completion s2 ctable confirm))
14389 (when (stringp rtn)
14390 (setq rtn
14391 (concat s1 s2 (substring rtn (length s2))
14392 (if (and org-add-colon-after-tag-completion
14393 (assoc rtn ctable))
14394 ":" ""))))
14395 rtn)
14396 ((eq flag t)
14397 ;; all-completions
14398 (all-completions s2 ctable confirm))
14399 ((eq flag 'lambda)
14400 ;; exact match?
14401 (assoc s2 ctable)))))
14403 (defun org-fast-tag-insert (kwd tags face &optional end)
14404 "Insert KDW, and the TAGS, the latter with face FACE.
14405 Also insert END."
14406 (insert (format "%-12s" (concat kwd ":"))
14407 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14408 (or end "")))
14410 (defun org-fast-tag-show-exit (flag)
14411 (save-excursion
14412 (org-goto-line 3)
14413 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14414 (replace-match ""))
14415 (when flag
14416 (end-of-line 1)
14417 (org-move-to-column (- (window-width) 19) t)
14418 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14420 (defun org-set-current-tags-overlay (current prefix)
14421 "Add an overlay to CURRENT tag with PREFIX."
14422 (let ((s (org-make-tag-string current)))
14423 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14424 (org-overlay-display org-tags-overlay (concat prefix s))))
14426 (defvar org-last-tag-selection-key nil)
14427 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14428 "Fast tag selection with single keys.
14429 CURRENT is the current list of tags in the headline, INHERITED is the
14430 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14431 possibly with grouping information. TODO-TABLE is a similar table with
14432 TODO keywords, should these have keys assigned to them.
14433 If the keys are nil, a-z are automatically assigned.
14434 Returns the new tags string, or nil to not change the current settings."
14435 (let* ((fulltable (append table todo-table))
14436 (maxlen (apply 'max (mapcar
14437 (lambda (x)
14438 (if (stringp (car x)) (string-width (car x)) 0))
14439 fulltable)))
14440 (buf (current-buffer))
14441 (expert (eq org-fast-tag-selection-single-key 'expert))
14442 (buffer-tags nil)
14443 (fwidth (+ maxlen 3 1 3))
14444 (ncol (/ (- (window-width) 4) fwidth))
14445 (i-face 'org-done)
14446 (c-face 'org-todo)
14447 tg cnt e c char c1 c2 ntable tbl rtn
14448 ov-start ov-end ov-prefix
14449 (exit-after-next org-fast-tag-selection-single-key)
14450 (done-keywords org-done-keywords)
14451 groups ingroup intaggroup)
14452 (save-excursion
14453 (beginning-of-line)
14454 (if (looking-at org-tag-line-re)
14455 (setq ov-start (match-beginning 1)
14456 ov-end (match-end 1)
14457 ov-prefix "")
14458 (setq ov-start (1- (point-at-eol))
14459 ov-end (1+ ov-start))
14460 (skip-chars-forward "^\n\r")
14461 (setq ov-prefix
14462 (concat
14463 (buffer-substring (1- (point)) (point))
14464 (if (> (current-column) org-tags-column)
14466 (make-string (- org-tags-column (current-column)) ?\ ))))))
14467 (move-overlay org-tags-overlay ov-start ov-end)
14468 (save-window-excursion
14469 (if expert
14470 (set-buffer (get-buffer-create " *Org tags*"))
14471 (delete-other-windows)
14472 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14473 (org-switch-to-buffer-other-window " *Org tags*"))
14474 (erase-buffer)
14475 (setq-local org-done-keywords done-keywords)
14476 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14477 (org-fast-tag-insert "Current" current c-face "\n\n")
14478 (org-fast-tag-show-exit exit-after-next)
14479 (org-set-current-tags-overlay current ov-prefix)
14480 (setq tbl fulltable char ?a cnt 0)
14481 (while (setq e (pop tbl))
14482 (cond
14483 ((eq (car e) :startgroup)
14484 (push '() groups) (setq ingroup t)
14485 (unless (zerop cnt)
14486 (setq cnt 0)
14487 (insert "\n"))
14488 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14489 ((eq (car e) :endgroup)
14490 (setq ingroup nil cnt 0)
14491 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14492 ((eq (car e) :startgrouptag)
14493 (setq intaggroup t)
14494 (unless (zerop cnt)
14495 (setq cnt 0)
14496 (insert "\n"))
14497 (insert "[ "))
14498 ((eq (car e) :endgrouptag)
14499 (setq intaggroup nil cnt 0)
14500 (insert "]\n"))
14501 ((equal e '(:newline))
14502 (unless (zerop cnt)
14503 (setq cnt 0)
14504 (insert "\n")
14505 (setq e (car tbl))
14506 (while (equal (car tbl) '(:newline))
14507 (insert "\n")
14508 (setq tbl (cdr tbl)))))
14509 ((equal e '(:grouptags)) (insert " : "))
14511 (setq tg (copy-sequence (car e)) c2 nil)
14512 (if (cdr e)
14513 (setq c (cdr e))
14514 ;; automatically assign a character.
14515 (setq c1 (string-to-char
14516 (downcase (substring
14517 tg (if (= (string-to-char tg) ?@) 1 0)))))
14518 (if (or (rassoc c1 ntable) (rassoc c1 table))
14519 (while (or (rassoc char ntable) (rassoc char table))
14520 (setq char (1+ char)))
14521 (setq c2 c1))
14522 (setq c (or c2 char)))
14523 (when ingroup (push tg (car groups)))
14524 (setq tg (org-add-props tg nil 'face
14525 (cond
14526 ((not (assoc tg table))
14527 (org-get-todo-face tg))
14528 ((member tg current) c-face)
14529 ((member tg inherited) i-face))))
14530 (when (equal (caar tbl) :grouptags)
14531 (org-add-props tg nil 'face 'org-tag-group))
14532 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14533 (insert "[" c "] " tg (make-string
14534 (- fwidth 4 (length tg)) ?\ ))
14535 (push (cons tg c) ntable)
14536 (when (= (cl-incf cnt) ncol)
14537 (insert "\n")
14538 (when (or ingroup intaggroup) (insert " "))
14539 (setq cnt 0)))))
14540 (setq ntable (nreverse ntable))
14541 (insert "\n")
14542 (goto-char (point-min))
14543 (unless expert (org-fit-window-to-buffer))
14544 (setq rtn
14545 (catch 'exit
14546 (while t
14547 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14548 (if (not groups) "no " "")
14549 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14550 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14551 (setq org-last-tag-selection-key c)
14552 (cond
14553 ((= c ?\r) (throw 'exit t))
14554 ((= c ?!)
14555 (setq groups (not groups))
14556 (goto-char (point-min))
14557 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14558 ((= c ?\C-c)
14559 (if (not expert)
14560 (org-fast-tag-show-exit
14561 (setq exit-after-next (not exit-after-next)))
14562 (setq expert nil)
14563 (delete-other-windows)
14564 (set-window-buffer (split-window-vertically) " *Org tags*")
14565 (org-switch-to-buffer-other-window " *Org tags*")
14566 (org-fit-window-to-buffer)))
14567 ((or (= c ?\C-g)
14568 (and (= c ?q) (not (rassoc c ntable))))
14569 (delete-overlay org-tags-overlay)
14570 (setq quit-flag t))
14571 ((= c ?\ )
14572 (setq current nil)
14573 (when exit-after-next (setq exit-after-next 'now)))
14574 ((= c ?\t)
14575 (condition-case nil
14576 (setq tg (completing-read
14577 "Tag: "
14578 (or buffer-tags
14579 (with-current-buffer buf
14580 (setq buffer-tags
14581 (org-get-buffer-tags))))))
14582 (quit (setq tg "")))
14583 (when (string-match "\\S-" tg)
14584 (cl-pushnew (list tg) buffer-tags :test #'equal)
14585 (if (member tg current)
14586 (setq current (delete tg current))
14587 (push tg current)))
14588 (when exit-after-next (setq exit-after-next 'now)))
14589 ((setq e (rassoc c todo-table) tg (car e))
14590 (with-current-buffer buf
14591 (save-excursion (org-todo tg)))
14592 (when exit-after-next (setq exit-after-next 'now)))
14593 ((setq e (rassoc c ntable) tg (car e))
14594 (if (member tg current)
14595 (setq current (delete tg current))
14596 (cl-loop for g in groups do
14597 (when (member tg g)
14598 (dolist (x g) (setq current (delete x current)))))
14599 (push tg current))
14600 (when exit-after-next (setq exit-after-next 'now))))
14602 ;; Create a sorted list
14603 (setq current
14604 (sort current
14605 (lambda (a b)
14606 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14607 (when (eq exit-after-next 'now) (throw 'exit t))
14608 (goto-char (point-min))
14609 (beginning-of-line 2)
14610 (delete-region (point) (point-at-eol))
14611 (org-fast-tag-insert "Current" current c-face)
14612 (org-set-current-tags-overlay current ov-prefix)
14613 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14614 (while (re-search-forward tag-re nil t)
14615 (let ((tag (match-string 1)))
14616 (add-text-properties
14617 (match-beginning 1) (match-end 1)
14618 (list 'face
14619 (cond
14620 ((member tag current) c-face)
14621 ((member tag inherited) i-face)
14622 (t (get-text-property (match-beginning 1) '
14623 face))))))))
14624 (goto-char (point-min)))))
14625 (delete-overlay org-tags-overlay)
14626 (if rtn
14627 (mapconcat 'identity current ":")
14628 nil))))
14630 (defun org-make-tag-string (tags)
14631 "Return string associated to TAGS.
14632 TAGS is a list of strings."
14633 (if (null tags) ""
14634 (format ":%s:" (mapconcat #'identity tags ":"))))
14636 (defun org--get-local-tags ()
14637 "Return list of tags for the current headline.
14638 Assume point is at the beginning of the headline."
14639 (and (looking-at org-tag-line-re)
14640 (split-string (match-string-no-properties 2) ":" t)))
14642 (defun org-get-tags (&optional pos local)
14643 "Get the list of tags specified in the current headline.
14645 When argument POS is non-nil, retrieve tags for headline at POS.
14647 Accoring to `org-use-tags-inheritance', tags may be inherited
14648 from parent headlines, and from the whole document, through
14649 `org-file-tags'. However, when optional argument LOCAL is
14650 non-nil, only return tags really specified in the considered
14651 headline.
14653 Inherited tags have the `inherited' text property."
14654 (if (and org-trust-scanner-tags
14655 (or (not pos) (eq pos (point)))
14656 (not local))
14657 org-scanner-tags
14658 (org-with-point-at (or pos (point))
14659 (unless (org-before-first-heading-p)
14660 (org-back-to-heading t)
14661 (let ((tags (org--get-local-tags)))
14662 (if (or local (not org-use-tag-inheritance)) tags
14663 (while (org-up-heading-safe)
14664 (setq tags (append (mapcar #'org-add-prop-inherited
14665 (org--get-local-tags))
14666 tags)))
14667 (org-remove-uninherited-tags
14668 (delete-dups (append org-file-tags tags)))))))))
14670 (defun org-get-buffer-tags ()
14671 "Get a table of all tags used in the buffer, for completion."
14672 (org-with-point-at 1
14673 (let (tags)
14674 (while (re-search-forward org-tag-line-re nil t)
14675 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14676 tags)))
14677 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14679 ;;;; The mapping API
14681 (defvar org-agenda-skip-comment-trees)
14682 (defvar org-agenda-skip-function)
14683 (defun org-map-entries (func &optional match scope &rest skip)
14684 "Call FUNC at each headline selected by MATCH in SCOPE.
14686 FUNC is a function or a lisp form. The function will be called without
14687 arguments, with the cursor positioned at the beginning of the headline.
14688 The return values of all calls to the function will be collected and
14689 returned as a list.
14691 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14692 does not need to preserve point. After evaluation, the cursor will be
14693 moved to the end of the line (presumably of the headline of the
14694 processed entry) and search continues from there. Under some
14695 circumstances, this may not produce the wanted results. For example,
14696 if you have removed (e.g. archived) the current (sub)tree it could
14697 mean that the next entry will be skipped entirely. In such cases, you
14698 can specify the position from where search should continue by making
14699 FUNC set the variable `org-map-continue-from' to the desired buffer
14700 position.
14702 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14703 Only headlines that are matched by this query will be considered during
14704 the iteration. When MATCH is nil or t, all headlines will be
14705 visited by the iteration.
14707 SCOPE determines the scope of this command. It can be any of:
14709 nil The current buffer, respecting the restriction if any
14710 tree The subtree started with the entry at point
14711 region The entries within the active region, if any
14712 region-start-level
14713 The entries within the active region, but only those at
14714 the same level than the first one.
14715 file The current buffer, without restriction
14716 file-with-archives
14717 The current buffer, and any archives associated with it
14718 agenda All agenda files
14719 agenda-with-archives
14720 All agenda files with any archive files associated with them
14721 \(file1 file2 ...)
14722 If this is a list, all files in the list will be scanned
14724 The remaining args are treated as settings for the skipping facilities of
14725 the scanner. The following items can be given here:
14727 archive skip trees with the archive tag
14728 comment skip trees with the COMMENT keyword
14729 function or Emacs Lisp form:
14730 will be used as value for `org-agenda-skip-function', so
14731 whenever the function returns a position, FUNC will not be
14732 called for that entry and search will continue from the
14733 position returned
14735 If your function needs to retrieve the tags including inherited tags
14736 at the *current* entry, you can use the value of the variable
14737 `org-scanner-tags' which will be much faster than getting the value
14738 with `org-get-tags'. If your function gets properties with
14739 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14740 to t around the call to `org-entry-properties' to get the same speedup.
14741 Note that if your function moves around to retrieve tags and properties at
14742 a *different* entry, you cannot use these techniques."
14743 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14744 (not (org-region-active-p)))
14745 (let* ((org-agenda-archives-mode nil) ; just to make sure
14746 (org-agenda-skip-archived-trees (memq 'archive skip))
14747 (org-agenda-skip-comment-trees (memq 'comment skip))
14748 (org-agenda-skip-function
14749 (car (org-delete-all '(comment archive) skip)))
14750 (org-tags-match-list-sublevels t)
14751 (start-level (eq scope 'region-start-level))
14752 matcher res
14753 org-todo-keywords-for-agenda
14754 org-done-keywords-for-agenda
14755 org-todo-keyword-alist-for-agenda
14756 org-tag-alist-for-agenda
14757 org--matcher-tags-todo-only)
14759 (cond
14760 ((eq match t) (setq matcher t))
14761 ((eq match nil) (setq matcher t))
14762 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14764 (save-excursion
14765 (save-restriction
14766 (cond ((eq scope 'tree)
14767 (org-back-to-heading t)
14768 (org-narrow-to-subtree)
14769 (setq scope nil))
14770 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14771 (org-region-active-p))
14772 ;; If needed, set start-level to a string like "2"
14773 (when start-level
14774 (save-excursion
14775 (goto-char (region-beginning))
14776 (unless (org-at-heading-p) (outline-next-heading))
14777 (setq start-level (org-current-level))))
14778 (narrow-to-region (region-beginning)
14779 (save-excursion
14780 (goto-char (region-end))
14781 (unless (and (bolp) (org-at-heading-p))
14782 (outline-next-heading))
14783 (point)))
14784 (setq scope nil)))
14786 (if (not scope)
14787 (progn
14788 (org-agenda-prepare-buffers
14789 (and buffer-file-name (list buffer-file-name)))
14790 (setq res
14791 (org-scan-tags
14792 func matcher org--matcher-tags-todo-only start-level)))
14793 ;; Get the right scope
14794 (cond
14795 ((and scope (listp scope) (symbolp (car scope)))
14796 (setq scope (eval scope)))
14797 ((eq scope 'agenda)
14798 (setq scope (org-agenda-files t)))
14799 ((eq scope 'agenda-with-archives)
14800 (setq scope (org-agenda-files t))
14801 (setq scope (org-add-archive-files scope)))
14802 ((eq scope 'file)
14803 (setq scope (and buffer-file-name (list buffer-file-name))))
14804 ((eq scope 'file-with-archives)
14805 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14806 (org-agenda-prepare-buffers scope)
14807 (dolist (file scope)
14808 (with-current-buffer (org-find-base-buffer-visiting file)
14809 (org-with-wide-buffer
14810 (goto-char (point-min))
14811 (setq res
14812 (append
14814 (org-scan-tags
14815 func matcher org--matcher-tags-todo-only)))))))))
14816 res)))
14818 ;;; Properties API
14820 (defconst org-special-properties
14821 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14822 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14823 "The special properties valid in Org mode.
14824 These are properties that are not defined in the property drawer,
14825 but in some other way.")
14827 (defconst org-default-properties
14828 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14829 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14830 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14831 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14832 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14833 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14834 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14835 "Some properties that are used by Org mode for various purposes.
14836 Being in this list makes sure that they are offered for completion.")
14838 (defun org--valid-property-p (property)
14839 "Non nil when string PROPERTY is a valid property name."
14840 (not
14841 (or (equal property "")
14842 (string-match-p "\\s-" property))))
14844 (defun org--update-property-plist (key val props)
14845 "Associate KEY to VAL in alist PROPS.
14846 Modifications are made by side-effect. Return new alist."
14847 (let* ((appending (string= (substring key -1) "+"))
14848 (key (if appending (substring key 0 -1) key))
14849 (old (assoc-string key props t)))
14850 (if (not old) (cons (cons key val) props)
14851 (setcdr old (if appending (concat (cdr old) " " val) val))
14852 props)))
14854 (defun org-get-property-block (&optional beg force)
14855 "Return the (beg . end) range of the body of the property drawer.
14856 BEG is the beginning of the current subtree, or of the part
14857 before the first headline. If it is not given, it will be found.
14858 If the drawer does not exist, create it if FORCE is non-nil, or
14859 return nil."
14860 (org-with-wide-buffer
14861 (when beg (goto-char beg))
14862 (unless (org-before-first-heading-p)
14863 (let ((beg (cond (beg)
14864 ((or (not (featurep 'org-inlinetask))
14865 (org-inlinetask-in-task-p))
14866 (org-back-to-heading t))
14867 (t (org-with-limited-levels (org-back-to-heading t))))))
14868 (forward-line)
14869 (when (looking-at-p org-planning-line-re) (forward-line))
14870 (cond ((looking-at org-property-drawer-re)
14871 (forward-line)
14872 (cons (point) (progn (goto-char (match-end 0))
14873 (line-beginning-position))))
14874 (force
14875 (goto-char beg)
14876 (org-insert-property-drawer)
14877 (let ((pos (save-excursion (search-forward ":END:")
14878 (line-beginning-position))))
14879 (cons pos pos))))))))
14881 (defun org-at-property-p ()
14882 "Non-nil when point is inside a property drawer.
14883 See `org-property-re' for match data, if applicable."
14884 (save-excursion
14885 (beginning-of-line)
14886 (and (looking-at org-property-re)
14887 (let ((property-drawer (save-match-data (org-get-property-block))))
14888 (and property-drawer
14889 (>= (point) (car property-drawer))
14890 (< (point) (cdr property-drawer)))))))
14892 (defun org-property-action ()
14893 "Do an action on properties."
14894 (interactive)
14895 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14896 (let ((c (read-char-exclusive)))
14897 (cl-case c
14898 (?s (call-interactively #'org-set-property))
14899 (?d (call-interactively #'org-delete-property))
14900 (?D (call-interactively #'org-delete-property-globally))
14901 (?c (call-interactively #'org-compute-property-at-point))
14902 (otherwise (user-error "No such property action %c" c)))))
14904 (defun org-inc-effort ()
14905 "Increment the value of the effort property in the current entry."
14906 (interactive)
14907 (org-set-effort t))
14909 (defvar org-clock-effort) ; Defined in org-clock.el.
14910 (defvar org-clock-current-task) ; Defined in org-clock.el.
14911 (defun org-set-effort (&optional increment value)
14912 "Set the effort property of the current entry.
14913 If INCREMENT is non-nil, set the property to the next allowed
14914 value. Otherwise, if optional argument VALUE is provided, use
14915 it. Eventually, prompt for the new value if none of the previous
14916 variables is set."
14917 (interactive "P")
14918 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14919 (current (org-entry-get nil org-effort-property))
14920 (value
14921 (cond
14922 (increment
14923 (unless allowed (user-error "Allowed effort values are not set"))
14924 (or (cl-caadr (member (list current) allowed))
14925 (user-error "Unknown value %S among allowed values" current)))
14926 (value
14927 (if (stringp value) value
14928 (error "Invalid effort value: %S" value)))
14930 (let ((must-match
14931 (and allowed
14932 (not (get-text-property 0 'org-unrestricted
14933 (caar allowed))))))
14934 (completing-read "Effort: " allowed nil must-match))))))
14935 (unless (equal current value)
14936 (org-entry-put nil org-effort-property value))
14937 (org-refresh-property '((effort . identity)
14938 (effort-minutes . org-duration-to-minutes))
14939 value)
14940 (when (equal (org-get-heading t t t t)
14941 (bound-and-true-p org-clock-current-task))
14942 (setq org-clock-effort (org-get-at-bol 'effort))
14943 (org-clock-update-mode-line))
14944 (message "%s is now %s" org-effort-property value)))
14946 (defun org-entry-properties (&optional pom which)
14947 "Get all properties of the current entry.
14949 When POM is a buffer position, get all properties from the entry
14950 there instead.
14952 This includes the TODO keyword, the tags, time strings for
14953 deadline, scheduled, and clocking, and any additional properties
14954 defined in the entry.
14956 If WHICH is nil or `all', get all properties. If WHICH is
14957 `special' or `standard', only get that subclass. If WHICH is
14958 a string, only get that property.
14960 Return value is an alist. Keys are properties, as upcased
14961 strings."
14962 (org-with-point-at pom
14963 (when (and (derived-mode-p 'org-mode)
14964 (ignore-errors (org-back-to-heading t)))
14965 (catch 'exit
14966 (let* ((beg (point))
14967 (specific (and (stringp which) (upcase which)))
14968 (which (cond ((not specific) which)
14969 ((member specific org-special-properties) 'special)
14970 (t 'standard)))
14971 props)
14972 ;; Get the special properties, like TODO and TAGS.
14973 (when (memq which '(nil all special))
14974 (when (or (not specific) (string= specific "CLOCKSUM"))
14975 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
14976 (when clocksum
14977 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
14978 props)))
14979 (when specific (throw 'exit props)))
14980 (when (or (not specific) (string= specific "CLOCKSUM_T"))
14981 (let ((clocksumt (get-text-property (point)
14982 :org-clock-minutes-today)))
14983 (when clocksumt
14984 (push (cons "CLOCKSUM_T"
14985 (org-duration-from-minutes clocksumt))
14986 props)))
14987 (when specific (throw 'exit props)))
14988 (when (or (not specific) (string= specific "ITEM"))
14989 (let ((case-fold-search nil))
14990 (when (looking-at org-complex-heading-regexp)
14991 (push (cons "ITEM"
14992 (let ((title (match-string-no-properties 4)))
14993 (if (org-string-nw-p title)
14994 (org-remove-tabs title)
14995 "")))
14996 props)))
14997 (when specific (throw 'exit props)))
14998 (when (or (not specific) (string= specific "TODO"))
14999 (let ((case-fold-search nil))
15000 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15001 (push (cons "TODO" (match-string-no-properties 2)) props)))
15002 (when specific (throw 'exit props)))
15003 (when (or (not specific) (string= specific "PRIORITY"))
15004 (push (cons "PRIORITY"
15005 (if (looking-at org-priority-regexp)
15006 (match-string-no-properties 2)
15007 (char-to-string org-default-priority)))
15008 props)
15009 (when specific (throw 'exit props)))
15010 (when (or (not specific) (string= specific "FILE"))
15011 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15012 props)
15013 (when specific (throw 'exit props)))
15014 (when (or (not specific) (string= specific "TAGS"))
15015 (let ((tags (org-get-tags nil t)))
15016 (when tags
15017 (push (cons "TAGS" (org-make-tag-string tags))
15018 props)))
15019 (when specific (throw 'exit props)))
15020 (when (or (not specific) (string= specific "ALLTAGS"))
15021 (let ((tags (org-get-tags)))
15022 (when tags
15023 (push (cons "ALLTAGS" (org-make-tag-string tags))
15024 props)))
15025 (when specific (throw 'exit props)))
15026 (when (or (not specific) (string= specific "BLOCKED"))
15027 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15028 (when specific (throw 'exit props)))
15029 (when (or (not specific)
15030 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15031 (forward-line)
15032 (when (looking-at-p org-planning-line-re)
15033 (end-of-line)
15034 (let ((bol (line-beginning-position))
15035 ;; Backward compatibility: time keywords used to
15036 ;; be configurable (before 8.3). Make sure we
15037 ;; get the correct keyword.
15038 (key-assoc `(("CLOSED" . ,org-closed-string)
15039 ("DEADLINE" . ,org-deadline-string)
15040 ("SCHEDULED" . ,org-scheduled-string))))
15041 (dolist (pair (if specific (list (assoc specific key-assoc))
15042 key-assoc))
15043 (save-excursion
15044 (when (search-backward (cdr pair) bol t)
15045 (goto-char (match-end 0))
15046 (skip-chars-forward " \t")
15047 (and (looking-at org-ts-regexp-both)
15048 (push (cons (car pair)
15049 (match-string-no-properties 0))
15050 props)))))))
15051 (when specific (throw 'exit props)))
15052 (when (or (not specific)
15053 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15054 (let ((find-ts
15055 (lambda (end ts)
15056 ;; Fix next time-stamp before END. TS is the
15057 ;; list of time-stamps found so far.
15058 (let ((ts ts)
15059 (regexp (cond
15060 ((string= specific "TIMESTAMP")
15061 org-ts-regexp)
15062 ((string= specific "TIMESTAMP_IA")
15063 org-ts-regexp-inactive)
15064 ((assoc "TIMESTAMP_IA" ts)
15065 org-ts-regexp)
15066 ((assoc "TIMESTAMP" ts)
15067 org-ts-regexp-inactive)
15068 (t org-ts-regexp-both))))
15069 (catch 'next
15070 (while (re-search-forward regexp end t)
15071 (backward-char)
15072 (let ((object (org-element-context)))
15073 ;; Accept to match timestamps in node
15074 ;; properties, too.
15075 (when (memq (org-element-type object)
15076 '(node-property timestamp))
15077 (let ((type
15078 (org-element-property :type object)))
15079 (cond
15080 ((and (memq type '(active active-range))
15081 (not (equal specific "TIMESTAMP_IA")))
15082 (unless (assoc "TIMESTAMP" ts)
15083 (push (cons "TIMESTAMP"
15084 (org-element-property
15085 :raw-value object))
15087 (when specific (throw 'exit ts))))
15088 ((and (memq type '(inactive inactive-range))
15089 (not (string= specific "TIMESTAMP")))
15090 (unless (assoc "TIMESTAMP_IA" ts)
15091 (push (cons "TIMESTAMP_IA"
15092 (org-element-property
15093 :raw-value object))
15095 (when specific (throw 'exit ts))))))
15096 ;; Both timestamp types are found,
15097 ;; move to next part.
15098 (when (= (length ts) 2) (throw 'next ts)))))
15099 ts)))))
15100 (goto-char beg)
15101 ;; First look for timestamps within headline.
15102 (let ((ts (funcall find-ts (line-end-position) nil)))
15103 (if (= (length ts) 2) (setq props (nconc ts props))
15104 ;; Then find timestamps in the section, skipping
15105 ;; planning line.
15106 (let ((end (save-excursion (outline-next-heading))))
15107 (forward-line)
15108 (when (looking-at-p org-planning-line-re) (forward-line))
15109 (setq props (nconc (funcall find-ts end ts) props))))))))
15110 ;; Get the standard properties, like :PROP:.
15111 (when (memq which '(nil all standard))
15112 ;; If we are looking after a specific property, delegate
15113 ;; to `org-entry-get', which is faster. However, make an
15114 ;; exception for "CATEGORY", since it can be also set
15115 ;; through keywords (i.e. #+CATEGORY).
15116 (if (and specific (not (equal specific "CATEGORY")))
15117 (let ((value (org-entry-get beg specific nil t)))
15118 (throw 'exit (and value (list (cons specific value)))))
15119 (let ((range (org-get-property-block beg)))
15120 (when range
15121 (let ((end (cdr range)) seen-base)
15122 (goto-char (car range))
15123 ;; Unlike to `org--update-property-plist', we
15124 ;; handle the case where base values is found
15125 ;; after its extension. We also forbid standard
15126 ;; properties to be named as special properties.
15127 (while (re-search-forward org-property-re end t)
15128 (let* ((key (upcase (match-string-no-properties 2)))
15129 (extendp (string-match-p "\\+\\'" key))
15130 (key-base (if extendp (substring key 0 -1) key))
15131 (value (match-string-no-properties 3)))
15132 (cond
15133 ((member-ignore-case key-base org-special-properties))
15134 (extendp
15135 (setq props
15136 (org--update-property-plist key value props)))
15137 ((member key seen-base))
15138 (t (push key seen-base)
15139 (let ((p (assoc-string key props t)))
15140 (if p (setcdr p (concat value " " (cdr p)))
15141 (push (cons key value) props))))))))))))
15142 (unless (assoc "CATEGORY" props)
15143 (push (cons "CATEGORY" (org-get-category beg)) props)
15144 (when (string= specific "CATEGORY") (throw 'exit props)))
15145 ;; Return value.
15146 props)))))
15148 (defun org--property-local-values (property literal-nil)
15149 "Return value for PROPERTY in current entry.
15150 Value is a list whose car is the base value for PROPERTY and cdr
15151 a list of accumulated values. Return nil if neither is found in
15152 the entry. Also return nil when PROPERTY is set to \"nil\",
15153 unless LITERAL-NIL is non-nil."
15154 (let ((range (org-get-property-block)))
15155 (when range
15156 (goto-char (car range))
15157 (let* ((case-fold-search t)
15158 (end (cdr range))
15159 (value
15160 ;; Base value.
15161 (save-excursion
15162 (let ((v (and (re-search-forward
15163 (org-re-property property nil t) end t)
15164 (match-string-no-properties 3))))
15165 (list (if literal-nil v (org-not-nil v)))))))
15166 ;; Find additional values.
15167 (let* ((property+ (org-re-property (concat property "+") nil t)))
15168 (while (re-search-forward property+ end t)
15169 (push (match-string-no-properties 3) value)))
15170 ;; Return final values.
15171 (and (not (equal value '(nil))) (nreverse value))))))
15173 (defun org--property-global-value (property literal-nil)
15174 "Return value for PROPERTY in current buffer.
15175 Return value is a string. Return nil if property is not set
15176 globally. Also return nil when PROPERTY is set to \"nil\",
15177 unless LITERAL-NIL is non-nil."
15178 (let ((global
15179 (cdr (or (assoc-string property org-file-properties t)
15180 (assoc-string property org-global-properties t)
15181 (assoc-string property org-global-properties-fixed t)))))
15182 (if literal-nil global (org-not-nil global))))
15184 (defun org-entry-get (pom property &optional inherit literal-nil)
15185 "Get value of PROPERTY for entry or content at point-or-marker POM.
15187 If INHERIT is non-nil and the entry does not have the property,
15188 then also check higher levels of the hierarchy. If INHERIT is
15189 the symbol `selective', use inheritance only if the setting in
15190 `org-use-property-inheritance' selects PROPERTY for inheritance.
15192 If the property is present but empty, the return value is the
15193 empty string. If the property is not present at all, nil is
15194 returned. In any other case, return the value as a string.
15195 Search is case-insensitive.
15197 If LITERAL-NIL is set, return the string value \"nil\" as
15198 a string, do not interpret it as the list atom nil. This is used
15199 for inheritance when a \"nil\" value can supersede a non-nil
15200 value higher up the hierarchy."
15201 (org-with-point-at pom
15202 (cond
15203 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15204 ;; We need a special property. Use `org-entry-properties' to
15205 ;; retrieve it, but specify the wanted property.
15206 (cdr (assoc-string property (org-entry-properties nil property))))
15207 ((and inherit
15208 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15209 (org-entry-get-with-inheritance property literal-nil))
15211 (let* ((local (org--property-local-values property literal-nil))
15212 (value (and local (mapconcat #'identity (delq nil local) " "))))
15213 (if literal-nil value (org-not-nil value)))))))
15215 (defun org-property-or-variable-value (var &optional inherit)
15216 "Check if there is a property fixing the value of VAR.
15217 If yes, return this value. If not, return the current value of the variable."
15218 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15219 (if (and prop (stringp prop) (string-match "\\S-" prop))
15220 (read prop)
15221 (symbol-value var))))
15223 (defun org-entry-delete (pom property)
15224 "Delete PROPERTY from entry at point-or-marker POM.
15225 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15226 non-nil when a property was removed."
15227 (org-with-point-at pom
15228 (pcase (org-get-property-block)
15229 (`(,begin . ,origin)
15230 (let* ((end (copy-marker origin))
15231 (re (org-re-property
15232 (concat (regexp-quote property) "\\+?") t t)))
15233 (goto-char begin)
15234 (while (re-search-forward re end t)
15235 (delete-region (match-beginning 0) (line-beginning-position 2)))
15236 ;; If drawer is empty, remove it altogether.
15237 (when (= begin end)
15238 (delete-region (line-beginning-position 0)
15239 (line-beginning-position 2)))
15240 ;; Return non-nil if some property was removed.
15241 (prog1 (/= end origin) (set-marker end nil))))
15242 (_ nil))))
15244 ;; Multi-values properties are properties that contain multiple values
15245 ;; These values are assumed to be single words, separated by whitespace.
15246 (defun org-entry-add-to-multivalued-property (pom property value)
15247 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15248 (let* ((old (org-entry-get pom property))
15249 (values (and old (split-string old))))
15250 (setq value (org-entry-protect-space value))
15251 (unless (member value values)
15252 (setq values (append values (list value)))
15253 (org-entry-put pom property (mapconcat #'identity values " ")))))
15255 (defun org-entry-remove-from-multivalued-property (pom property value)
15256 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15257 (let* ((old (org-entry-get pom property))
15258 (values (and old (split-string old))))
15259 (setq value (org-entry-protect-space value))
15260 (when (member value values)
15261 (setq values (delete value values))
15262 (org-entry-put pom property (mapconcat #'identity values " ")))))
15264 (defun org-entry-member-in-multivalued-property (pom property value)
15265 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15266 (let* ((old (org-entry-get pom property))
15267 (values (and old (split-string old))))
15268 (setq value (org-entry-protect-space value))
15269 (member value values)))
15271 (defun org-entry-get-multivalued-property (pom property)
15272 "Return a list of values in a multivalued property."
15273 (let* ((value (org-entry-get pom property))
15274 (values (and value (split-string value))))
15275 (mapcar #'org-entry-restore-space values)))
15277 (defun org-entry-put-multivalued-property (pom property &rest values)
15278 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15279 VALUES should be a list of strings. Spaces will be protected."
15280 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15281 (let* ((value (org-entry-get pom property))
15282 (values (and value (split-string value))))
15283 (mapcar #'org-entry-restore-space values)))
15285 (defun org-entry-protect-space (s)
15286 "Protect spaces and newline in string S."
15287 (while (string-match " " s)
15288 (setq s (replace-match "%20" t t s)))
15289 (while (string-match "\n" s)
15290 (setq s (replace-match "%0A" t t s)))
15293 (defun org-entry-restore-space (s)
15294 "Restore spaces and newline in string S."
15295 (while (string-match "%20" s)
15296 (setq s (replace-match " " t t s)))
15297 (while (string-match "%0A" s)
15298 (setq s (replace-match "\n" t t s)))
15301 (defvar org-entry-property-inherited-from (make-marker)
15302 "Marker pointing to the entry from where a property was inherited.
15303 Each call to `org-entry-get-with-inheritance' will set this marker to the
15304 location of the entry where the inheritance search matched. If there was
15305 no match, the marker will point nowhere.
15306 Note that also `org-entry-get' calls this function, if the INHERIT flag
15307 is set.")
15309 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15310 "Get PROPERTY of entry or content at point, search higher levels if needed.
15311 The search will stop at the first ancestor which has the property defined.
15312 If the value found is \"nil\", return nil to show that the property
15313 should be considered as undefined (this is the meaning of nil here).
15314 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15315 (move-marker org-entry-property-inherited-from nil)
15316 (org-with-wide-buffer
15317 (let (value)
15318 (catch 'exit
15319 (while t
15320 (let ((v (org--property-local-values property literal-nil)))
15321 (when v
15322 (setq value
15323 (concat (mapconcat #'identity (delq nil v) " ")
15324 (and value " ")
15325 value)))
15326 (cond
15327 ((car v)
15328 (org-back-to-heading t)
15329 (move-marker org-entry-property-inherited-from (point))
15330 (throw 'exit nil))
15331 ((org-up-heading-safe))
15333 (let ((global (org--property-global-value property literal-nil)))
15334 (cond ((not global))
15335 (value (setq value (concat global " " value)))
15336 (t (setq value global))))
15337 (throw 'exit nil))))))
15338 (if literal-nil value (org-not-nil value)))))
15340 (defvar org-property-changed-functions nil
15341 "Hook called when the value of a property has changed.
15342 Each hook function should accept two arguments, the name of the property
15343 and the new value.")
15345 (defun org-entry-put (pom property value)
15346 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15348 If the value is nil, it is converted to the empty string. If it
15349 is not a string, an error is raised. Also raise an error on
15350 invalid property names.
15352 PROPERTY can be any regular property (see
15353 `org-special-properties'). It can also be \"TODO\",
15354 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15356 For the last two properties, VALUE may have any of the special
15357 values \"earlier\" and \"later\". The function then increases or
15358 decreases scheduled or deadline date by one day."
15359 (cond ((null value) (setq value ""))
15360 ((not (stringp value)) (error "Properties values should be strings"))
15361 ((not (org--valid-property-p property))
15362 (user-error "Invalid property name: \"%s\"" property)))
15363 (org-with-point-at pom
15364 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15365 (org-back-to-heading t)
15366 (org-with-limited-levels (org-back-to-heading t)))
15367 (let ((beg (point)))
15368 (cond
15369 ((equal property "TODO")
15370 (cond ((not (org-string-nw-p value)) (setq value 'none))
15371 ((not (member value org-todo-keywords-1))
15372 (user-error "\"%s\" is not a valid TODO state" value)))
15373 (org-todo value)
15374 (org-align-tags))
15375 ((equal property "PRIORITY")
15376 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15377 (org-align-tags))
15378 ((equal property "SCHEDULED")
15379 (forward-line)
15380 (if (and (looking-at-p org-planning-line-re)
15381 (re-search-forward
15382 org-scheduled-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-schedule '(4)))
15386 (t (org-schedule nil value)))
15387 (if (member value '("earlier" "later" ""))
15388 (call-interactively #'org-schedule)
15389 (org-schedule nil value))))
15390 ((equal property "DEADLINE")
15391 (forward-line)
15392 (if (and (looking-at-p org-planning-line-re)
15393 (re-search-forward
15394 org-deadline-time-regexp (line-end-position) t))
15395 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15396 ((string= value "later") (org-timestamp-change 1 'day))
15397 ((string= value "") (org-deadline '(4)))
15398 (t (org-deadline nil value)))
15399 (if (member value '("earlier" "later" ""))
15400 (call-interactively #'org-deadline)
15401 (org-deadline nil value))))
15402 ((member property org-special-properties)
15403 (error "The %s property cannot be set with `org-entry-put'" property))
15405 (let* ((range (org-get-property-block beg 'force))
15406 (end (cdr range))
15407 (case-fold-search t))
15408 (goto-char (car range))
15409 (if (re-search-forward (org-re-property property nil t) end t)
15410 (progn (delete-region (match-beginning 0) (match-end 0))
15411 (goto-char (match-beginning 0)))
15412 (goto-char end)
15413 (insert "\n")
15414 (backward-char))
15415 (insert ":" property ":")
15416 (when value (insert " " value))
15417 (org-indent-line)))))
15418 (run-hook-with-args 'org-property-changed-functions property value)))
15420 (defun org-buffer-property-keys (&optional specials defaults columns)
15421 "Get all property keys in the current buffer.
15423 When SPECIALS is non-nil, also list the special properties that
15424 reflect things like tags and TODO state.
15426 When DEFAULTS is non-nil, also include properties that has
15427 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15428 DESCRIPTION, LOCATION, and LOGGING and others.
15430 When COLUMNS in non-nil, also include property names given in
15431 COLUMN formats in the current buffer."
15432 (let ((case-fold-search t)
15433 (props (append
15434 (and specials org-special-properties)
15435 (and defaults (cons org-effort-property org-default-properties))
15436 nil)))
15437 (org-with-wide-buffer
15438 (goto-char (point-min))
15439 (while (re-search-forward org-property-start-re nil t)
15440 (catch :skip
15441 (let ((range (org-get-property-block)))
15442 (unless range (throw :skip nil))
15443 (goto-char (car range))
15444 (let ((begin (car range))
15445 (end (cdr range)))
15446 ;; Make sure that found property block is not located
15447 ;; before current point, as it would generate an infloop.
15448 ;; It can happen, for example, in the following
15449 ;; situation:
15451 ;; * Headline
15452 ;; :PROPERTIES:
15453 ;; ...
15454 ;; :END:
15455 ;; *************** Inlinetask
15456 ;; #+BEGIN_EXAMPLE
15457 ;; :PROPERTIES:
15458 ;; #+END_EXAMPLE
15460 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15461 (while (< (point) end)
15462 (let ((p (progn (looking-at org-property-re)
15463 (match-string-no-properties 2))))
15464 ;; Only add true property name, not extension symbol.
15465 (push (if (not (string-match-p "\\+\\'" p)) p
15466 (substring p 0 -1))
15467 props))
15468 (forward-line))))
15469 (outline-next-heading)))
15470 (when columns
15471 (goto-char (point-min))
15472 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15473 (let ((element (org-element-at-point)))
15474 (when (memq (org-element-type element) '(keyword node-property))
15475 (let ((value (org-element-property :value element))
15476 (start 0))
15477 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15478 \\(?:{[^}]+}\\)?"
15479 value start)
15480 (setq start (match-end 0))
15481 (let ((p (match-string-no-properties 1 value)))
15482 (unless (member-ignore-case p org-special-properties)
15483 (push p props))))))))))
15484 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15486 (defun org-property-values (key)
15487 "List all non-nil values of property KEY in current buffer."
15488 (org-with-wide-buffer
15489 (goto-char (point-min))
15490 (let ((case-fold-search t)
15491 (re (org-re-property key))
15492 values)
15493 (while (re-search-forward re nil t)
15494 (push (org-entry-get (point) key) values))
15495 (delete-dups values))))
15497 (defun org-insert-property-drawer ()
15498 "Insert a property drawer into the current entry."
15499 (org-with-wide-buffer
15500 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15501 (org-back-to-heading t)
15502 (org-with-limited-levels (org-back-to-heading t)))
15503 (forward-line)
15504 (when (looking-at-p org-planning-line-re) (forward-line))
15505 (unless (looking-at-p org-property-drawer-re)
15506 ;; Make sure we start editing a line from current entry, not from
15507 ;; next one. It prevents extending text properties or overlays
15508 ;; belonging to the latter.
15509 (when (bolp) (backward-char))
15510 (let ((begin (1+ (point)))
15511 (inhibit-read-only t))
15512 (insert "\n:PROPERTIES:\n:END:")
15513 (when (eobp) (insert "\n"))
15514 (org-indent-region begin (point))))))
15516 (defun org-insert-drawer (&optional arg drawer)
15517 "Insert a drawer at point.
15519 When optional argument ARG is non-nil, insert a property drawer.
15521 Optional argument DRAWER, when non-nil, is a string representing
15522 drawer's name. Otherwise, the user is prompted for a name.
15524 If a region is active, insert the drawer around that region
15525 instead.
15527 Point is left between drawer's boundaries."
15528 (interactive "P")
15529 (let* ((drawer (if arg "PROPERTIES"
15530 (or drawer (read-from-minibuffer "Drawer: ")))))
15531 (cond
15532 ;; With C-u, fall back on `org-insert-property-drawer'
15533 (arg (org-insert-property-drawer))
15534 ;; Check validity of suggested drawer's name.
15535 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15536 (user-error "Invalid drawer name"))
15537 ;; With an active region, insert a drawer at point.
15538 ((not (org-region-active-p))
15539 (progn
15540 (unless (bolp) (insert "\n"))
15541 (insert (format ":%s:\n\n:END:\n" drawer))
15542 (forward-line -2)))
15543 ;; Otherwise, insert the drawer at point
15545 (let ((rbeg (region-beginning))
15546 (rend (copy-marker (region-end))))
15547 (unwind-protect
15548 (progn
15549 (goto-char rbeg)
15550 (beginning-of-line)
15551 (when (save-excursion
15552 (re-search-forward org-outline-regexp-bol rend t))
15553 (user-error "Drawers cannot contain headlines"))
15554 ;; Position point at the beginning of the first
15555 ;; non-blank line in region. Insert drawer's opening
15556 ;; there, then indent it.
15557 (org-skip-whitespace)
15558 (beginning-of-line)
15559 (insert ":" drawer ":\n")
15560 (forward-line -1)
15561 (indent-for-tab-command)
15562 ;; Move point to the beginning of the first blank line
15563 ;; after the last non-blank line in region. Insert
15564 ;; drawer's closing, then indent it.
15565 (goto-char rend)
15566 (skip-chars-backward " \r\t\n")
15567 (insert "\n:END:")
15568 (deactivate-mark t)
15569 (indent-for-tab-command)
15570 (unless (eolp) (insert "\n")))
15571 ;; Clear marker, whatever the outcome of insertion is.
15572 (set-marker rend nil)))))))
15574 (defvar org-property-set-functions-alist nil
15575 "Property set function alist.
15576 Each entry should have the following format:
15578 (PROPERTY . READ-FUNCTION)
15580 The read function will be called with the same argument as
15581 `org-completing-read'.")
15583 (defun org-set-property-function (property)
15584 "Get the function that should be used to set PROPERTY.
15585 This is computed according to `org-property-set-functions-alist'."
15586 (or (cdr (assoc property org-property-set-functions-alist))
15587 'org-completing-read))
15589 (defun org-read-property-value (property)
15590 "Read PROPERTY value from user."
15591 (let* ((completion-ignore-case t)
15592 (allowed (org-property-get-allowed-values nil property 'table))
15593 (cur (org-entry-get nil property))
15594 (prompt (concat property " value"
15595 (if (and cur (string-match "\\S-" cur))
15596 (concat " [" cur "]") "") ": "))
15597 (set-function (org-set-property-function property))
15598 (val (if allowed
15599 (funcall set-function prompt allowed nil
15600 (not (get-text-property 0 'org-unrestricted
15601 (caar allowed))))
15602 (funcall set-function prompt
15603 (mapcar 'list (org-property-values property))
15604 nil nil "" nil cur))))
15605 (org-trim val)))
15607 (defvar org-last-set-property nil)
15608 (defvar org-last-set-property-value nil)
15609 (defun org-read-property-name ()
15610 "Read a property name."
15611 (let ((completion-ignore-case t)
15612 (default-prop (or (and (org-at-property-p)
15613 (match-string-no-properties 2))
15614 org-last-set-property)))
15615 (org-completing-read
15616 (concat "Property"
15617 (if default-prop (concat " [" default-prop "]") "")
15618 ": ")
15619 (mapcar #'list (org-buffer-property-keys nil t t))
15620 nil nil nil nil default-prop)))
15622 (defun org-set-property-and-value (use-last)
15623 "Allow to set [PROPERTY]: [value] direction from prompt.
15624 When use-default, don't even ask, just use the last
15625 \"[PROPERTY]: [value]\" string from the history."
15626 (interactive "P")
15627 (let* ((completion-ignore-case t)
15628 (pv (or (and use-last org-last-set-property-value)
15629 (org-completing-read
15630 "Enter a \"[Property]: [value]\" pair: "
15631 nil nil nil nil nil
15632 org-last-set-property-value)))
15633 prop val)
15634 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15635 (setq prop (match-string 1 pv)
15636 val (match-string 2 pv))
15637 (org-set-property prop val))))
15639 (defun org-set-property (property value)
15640 "In the current entry, set PROPERTY to VALUE.
15642 When called interactively, this will prompt for a property name, offering
15643 completion on existing and default properties. And then it will prompt
15644 for a value, offering completion either on allowed values (via an inherited
15645 xxx_ALL property) or on existing values in other instances of this property
15646 in the current file.
15648 Throw an error when trying to set a property with an invalid name."
15649 (interactive (list nil nil))
15650 (let ((property (or property (org-read-property-name))))
15651 ;; `org-entry-put' also makes the following check, but this one
15652 ;; avoids polluting `org-last-set-property' and
15653 ;; `org-last-set-property-value' needlessly.
15654 (unless (org--valid-property-p property)
15655 (user-error "Invalid property name: \"%s\"" property))
15656 (let ((value (or value (org-read-property-value property)))
15657 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15658 (setq org-last-set-property property)
15659 (setq org-last-set-property-value (concat property ": " value))
15660 ;; Possibly postprocess the inserted value:
15661 (when fn (setq value (funcall fn value)))
15662 (unless (equal (org-entry-get nil property) value)
15663 (org-entry-put nil property value)))))
15665 (defun org-find-property (property &optional value)
15666 "Find first entry in buffer that sets PROPERTY.
15668 When optional argument VALUE is non-nil, only consider an entry
15669 if it contains PROPERTY set to this value. If PROPERTY should be
15670 explicitly set to nil, use string \"nil\" for VALUE.
15672 Return position where the entry begins, or nil if there is no
15673 such entry. If narrowing is in effect, only search the visible
15674 part of the buffer."
15675 (save-excursion
15676 (goto-char (point-min))
15677 (let ((case-fold-search t)
15678 (re (org-re-property property nil (not value) value)))
15679 (catch 'exit
15680 (while (re-search-forward re nil t)
15681 (when (if value (org-at-property-p)
15682 (org-entry-get (point) property nil t))
15683 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15685 (defun org-delete-property (property)
15686 "In the current entry, delete PROPERTY."
15687 (interactive
15688 (let* ((completion-ignore-case t)
15689 (cat (org-entry-get (point) "CATEGORY"))
15690 (props0 (org-entry-properties nil 'standard))
15691 (props (if cat props0
15692 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15693 (prop (if (< 1 (length props))
15694 (completing-read "Property: " props nil t)
15695 (caar props))))
15696 (list prop)))
15697 (if (not property)
15698 (message "No property to delete in this entry")
15699 (org-entry-delete nil property)
15700 (message "Property \"%s\" deleted" property)))
15702 (defun org-delete-property-globally (property)
15703 "Remove PROPERTY globally, from all entries.
15704 This function ignores narrowing, if any."
15705 (interactive
15706 (let* ((completion-ignore-case t)
15707 (prop (completing-read
15708 "Globally remove property: "
15709 (mapcar #'list (org-buffer-property-keys)))))
15710 (list prop)))
15711 (org-with-wide-buffer
15712 (goto-char (point-min))
15713 (let ((count 0)
15714 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15715 (while (re-search-forward re nil t)
15716 (when (org-entry-delete (point) property) (cl-incf count)))
15717 (message "Property \"%s\" removed from %d entries" property count))))
15719 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15721 (defun org-compute-property-at-point ()
15722 "Compute the property at point.
15723 This looks for an enclosing column format, extracts the operator and
15724 then applies it to the property in the column format's scope."
15725 (interactive)
15726 (unless (org-at-property-p)
15727 (user-error "Not at a property"))
15728 (let ((prop (match-string-no-properties 2)))
15729 (org-columns-get-format-and-top-level)
15730 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15731 (user-error "No operator defined for property %s" prop))
15732 (org-columns-compute prop)))
15734 (defvar org-property-allowed-value-functions nil
15735 "Hook for functions supplying allowed values for a specific property.
15736 The functions must take a single argument, the name of the property, and
15737 return a flat list of allowed values. If \":ETC\" is one of
15738 the values, this means that these values are intended as defaults for
15739 completion, but that other values should be allowed too.
15740 The functions must return nil if they are not responsible for this
15741 property.")
15743 (defun org-property-get-allowed-values (pom property &optional table)
15744 "Get allowed values for the property PROPERTY.
15745 When TABLE is non-nil, return an alist that can directly be used for
15746 completion."
15747 (let (vals)
15748 (cond
15749 ((equal property "TODO")
15750 (setq vals (org-with-point-at pom
15751 (append org-todo-keywords-1 '("")))))
15752 ((equal property "PRIORITY")
15753 (let ((n org-lowest-priority))
15754 (while (>= n org-highest-priority)
15755 (push (char-to-string n) vals)
15756 (setq n (1- n)))))
15757 ((equal property "CATEGORY"))
15758 ((member property org-special-properties))
15759 ((setq vals (run-hook-with-args-until-success
15760 'org-property-allowed-value-functions property)))
15762 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15763 (when (and vals (string-match "\\S-" vals))
15764 (setq vals (car (read-from-string (concat "(" vals ")"))))
15765 (setq vals (mapcar (lambda (x)
15766 (cond ((stringp x) x)
15767 ((numberp x) (number-to-string x))
15768 ((symbolp x) (symbol-name x))
15769 (t "???")))
15770 vals)))))
15771 (when (member ":ETC" vals)
15772 (setq vals (remove ":ETC" vals))
15773 (org-add-props (car vals) '(org-unrestricted t)))
15774 (if table (mapcar 'list vals) vals)))
15776 (defun org-property-previous-allowed-value (&optional _previous)
15777 "Switch to the next allowed value for this property."
15778 (interactive)
15779 (org-property-next-allowed-value t))
15781 (defun org-property-next-allowed-value (&optional previous)
15782 "Switch to the next allowed value for this property."
15783 (interactive)
15784 (unless (org-at-property-p)
15785 (user-error "Not at a property"))
15786 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15787 (key (match-string 2))
15788 (value (match-string 3))
15789 (allowed (or (org-property-get-allowed-values (point) key)
15790 (and (member value '("[ ]" "[-]" "[X]"))
15791 '("[ ]" "[X]"))))
15792 (heading (save-match-data (nth 4 (org-heading-components))))
15793 nval)
15794 (unless allowed
15795 (user-error "Allowed values for this property have not been defined"))
15796 (when previous (setq allowed (reverse allowed)))
15797 (when (member value allowed)
15798 (setq nval (car (cdr (member value allowed)))))
15799 (setq nval (or nval (car allowed)))
15800 (when (equal nval value)
15801 (user-error "Only one allowed value for this property"))
15802 (org-at-property-p)
15803 (replace-match (concat " :" key ": " nval) t t)
15804 (org-indent-line)
15805 (beginning-of-line 1)
15806 (skip-chars-forward " \t")
15807 (when (equal prop org-effort-property)
15808 (org-refresh-property
15809 '((effort . identity)
15810 (effort-minutes . org-duration-to-minutes))
15811 nval)
15812 (when (string= org-clock-current-task heading)
15813 (setq org-clock-effort nval)
15814 (org-clock-update-mode-line)))
15815 (run-hook-with-args 'org-property-changed-functions key nval)))
15817 (defun org-find-olp (path &optional this-buffer)
15818 "Return a marker pointing to the entry at outline path OLP.
15819 If anything goes wrong, throw an error.
15820 You can wrap this call to catch the error like this:
15822 (condition-case msg
15823 (org-mobile-locate-entry (match-string 4))
15824 (error (nth 1 msg)))
15826 The return value will then be either a string with the error message,
15827 or a marker if everything is OK.
15829 If THIS-BUFFER is set, the outline path does not contain a file,
15830 only headings."
15831 (let* ((file (if this-buffer buffer-file-name (pop path)))
15832 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15833 (level 1)
15834 (lmin 1)
15835 (lmax 1)
15836 end found flevel)
15837 (unless buffer (error "File not found :%s" file))
15838 (with-current-buffer buffer
15839 (unless (derived-mode-p 'org-mode)
15840 (error "Buffer %s needs to be in Org mode" buffer))
15841 (org-with-wide-buffer
15842 (goto-char (point-min))
15843 (dolist (heading path)
15844 (let ((re (format org-complex-heading-regexp-format
15845 (regexp-quote heading)))
15846 (cnt 0))
15847 (while (re-search-forward re end t)
15848 (setq level (- (match-end 1) (match-beginning 1)))
15849 (when (and (>= level lmin) (<= level lmax))
15850 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15851 (when (= cnt 0)
15852 (error "Heading not found on level %d: %s" lmax heading))
15853 (when (> cnt 1)
15854 (error "Heading not unique on level %d: %s" lmax heading))
15855 (goto-char found)
15856 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15857 (setq end (save-excursion (org-end-of-subtree t t)))))
15858 (when (org-at-heading-p)
15859 (point-marker))))))
15861 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15862 "Find node HEADING in BUFFER.
15863 Return a marker to the heading if it was found, or nil if not.
15864 If POS-ONLY is set, return just the position instead of a marker.
15866 The heading text must match exact, but it may have a TODO keyword,
15867 a priority cookie and tags in the standard locations."
15868 (with-current-buffer (or buffer (current-buffer))
15869 (org-with-wide-buffer
15870 (goto-char (point-min))
15871 (let (case-fold-search)
15872 (when (re-search-forward
15873 (format org-complex-heading-regexp-format
15874 (regexp-quote heading)) nil t)
15875 (if pos-only
15876 (match-beginning 0)
15877 (move-marker (make-marker) (match-beginning 0))))))))
15879 (defun org-find-exact-heading-in-directory (heading &optional dir)
15880 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15881 When the target headline is found, return a marker to this location."
15882 (let ((files (directory-files (or dir default-directory)
15883 t "\\`[^.#].*\\.org\\'"))
15884 visiting m buffer)
15885 (catch 'found
15886 (dolist (file files)
15887 (message "trying %s" file)
15888 (setq visiting (org-find-base-buffer-visiting file))
15889 (setq buffer (or visiting (find-file-noselect file)))
15890 (setq m (org-find-exact-headline-in-buffer
15891 heading buffer))
15892 (when (and (not m) (not visiting)) (kill-buffer buffer))
15893 (and m (throw 'found m))))))
15895 (defun org-find-entry-with-id (ident)
15896 "Locate the entry that contains the ID property with exact value IDENT.
15897 IDENT can be a string, a symbol or a number, this function will search for
15898 the string representation of it.
15899 Return the position where this entry starts, or nil if there is no such entry."
15900 (interactive "sID: ")
15901 (let ((id (cond
15902 ((stringp ident) ident)
15903 ((symbolp ident) (symbol-name ident))
15904 ((numberp ident) (number-to-string ident))
15905 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15906 (org-with-wide-buffer (org-find-property "ID" id))))
15908 ;;;; Timestamps
15910 (defvar org-last-changed-timestamp nil)
15911 (defvar org-last-inserted-timestamp nil
15912 "The last time stamp inserted with `org-insert-time-stamp'.")
15914 (defun org-time-stamp (arg &optional inactive)
15915 "Prompt for a date/time and insert a time stamp.
15917 If the user specifies a time like HH:MM or if this command is
15918 called with at least one prefix argument, the time stamp contains
15919 the date and the time. Otherwise, only the date is included.
15921 All parts of a date not specified by the user are filled in from
15922 the timestamp at point, if any, or the current date/time
15923 otherwise.
15925 If there is already a timestamp at the cursor, it is replaced.
15927 With two universal prefix arguments, insert an active timestamp
15928 with the current time without prompting the user.
15930 When called from lisp, the timestamp is inactive if INACTIVE is
15931 non-nil."
15932 (interactive "P")
15933 (let* ((ts (cond
15934 ((org-at-date-range-p t)
15935 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15936 ((org-at-timestamp-p 'lax) (match-string 0))))
15937 ;; Default time is either the timestamp at point or today.
15938 ;; When entering a range, only the range start is considered.
15939 (default-time (if (not ts) (current-time)
15940 (apply #'encode-time (org-parse-time-string ts))))
15941 (default-input (and ts (org-get-compact-tod ts)))
15942 (repeater (and ts
15943 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15944 (match-string 0 ts)))
15945 org-time-was-given
15946 org-end-time-was-given
15947 (time
15948 (and (if (equal arg '(16)) (current-time)
15949 ;; Preserve `this-command' and `last-command'.
15950 (let ((this-command this-command)
15951 (last-command last-command))
15952 (org-read-date
15953 arg 'totime nil nil default-time default-input
15954 inactive))))))
15955 (cond
15956 ((and ts
15957 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15958 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15959 (insert "--")
15960 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15962 ;; Make sure we're on a timestamp. When in the middle of a date
15963 ;; range, move arbitrarily to range end.
15964 (unless (org-at-timestamp-p 'lax)
15965 (skip-chars-forward "-")
15966 (org-at-timestamp-p 'lax))
15967 (replace-match "")
15968 (setq org-last-changed-timestamp
15969 (org-insert-time-stamp
15970 time (or org-time-was-given arg)
15971 inactive nil nil (list org-end-time-was-given)))
15972 (when repeater
15973 (backward-char)
15974 (insert " " repeater)
15975 (setq org-last-changed-timestamp
15976 (concat (substring org-last-inserted-timestamp 0 -1)
15977 " " repeater ">")))
15978 (message "Timestamp updated"))
15979 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
15980 (t (org-insert-time-stamp
15981 time (or org-time-was-given arg) inactive nil nil
15982 (list org-end-time-was-given))))))
15984 ;; FIXME: can we use this for something else, like computing time differences?
15985 (defun org-get-compact-tod (s)
15986 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15987 (let* ((t1 (match-string 1 s))
15988 (h1 (string-to-number (match-string 2 s)))
15989 (m1 (string-to-number (match-string 3 s)))
15990 (t2 (and (match-end 4) (match-string 5 s)))
15991 (h2 (and t2 (string-to-number (match-string 6 s))))
15992 (m2 (and t2 (string-to-number (match-string 7 s))))
15993 dh dm)
15994 (if (not t2)
15996 (setq dh (- h2 h1) dm (- m2 m1))
15997 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15998 (concat t1 "+" (number-to-string dh)
15999 (and (/= 0 dm) (format ":%02d" dm)))))))
16001 (defun org-time-stamp-inactive (&optional arg)
16002 "Insert an inactive time stamp.
16004 An inactive time stamp is enclosed in square brackets instead of angle
16005 brackets. It is inactive in the sense that it does not trigger agenda entries,
16006 does not link to the calendar and cannot be changed with the S-cursor keys.
16007 So these are more for recording a certain time/date.
16009 If the user specifies a time like HH:MM or if this command is called with
16010 at least one prefix argument, the time stamp contains the date and the time.
16011 Otherwise, only the date is included.
16013 When called with two universal prefix arguments, insert an active time stamp
16014 with the current time without prompting the user."
16015 (interactive "P")
16016 (org-time-stamp arg 'inactive))
16018 (defvar org-date-ovl (make-overlay 1 1))
16019 (overlay-put org-date-ovl 'face 'org-date-selected)
16020 (delete-overlay org-date-ovl)
16022 (defvar org-ans1) ; dynamically scoped parameter
16023 (defvar org-ans2) ; dynamically scoped parameter
16025 (defvar org-plain-time-of-day-regexp) ; defined below
16027 (defvar org-overriding-default-time nil) ; dynamically scoped
16028 (defvar org-read-date-overlay nil)
16029 (defvar org-dcst nil) ; dynamically scoped
16030 (defvar org-read-date-history nil)
16031 (defvar org-read-date-final-answer nil)
16032 (defvar org-read-date-analyze-futurep nil)
16033 (defvar org-read-date-analyze-forced-year nil)
16034 (defvar org-read-date-inactive)
16036 (defvar org-read-date-minibuffer-local-map
16037 (let* ((map (make-sparse-keymap)))
16038 (set-keymap-parent map minibuffer-local-map)
16039 (org-defkey map (kbd ".")
16040 (lambda () (interactive)
16041 ;; Are we at the beginning of the prompt?
16042 (if (looking-back "^[^:]+: "
16043 (let ((inhibit-field-text-motion t))
16044 (line-beginning-position)))
16045 (org-eval-in-calendar '(calendar-goto-today))
16046 (insert "."))))
16047 (org-defkey map (kbd "C-.")
16048 (lambda () (interactive)
16049 (org-eval-in-calendar '(calendar-goto-today))))
16050 (org-defkey map (kbd "M-S-<left>")
16051 (lambda () (interactive)
16052 (org-eval-in-calendar '(calendar-backward-month 1))))
16053 (org-defkey map (kbd "ESC S-<left>")
16054 (lambda () (interactive)
16055 (org-eval-in-calendar '(calendar-backward-month 1))))
16056 (org-defkey map (kbd "M-S-<right>")
16057 (lambda () (interactive)
16058 (org-eval-in-calendar '(calendar-forward-month 1))))
16059 (org-defkey map (kbd "ESC S-<right>")
16060 (lambda () (interactive)
16061 (org-eval-in-calendar '(calendar-forward-month 1))))
16062 (org-defkey map (kbd "M-S-<up>")
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(calendar-backward-year 1))))
16065 (org-defkey map (kbd "ESC S-<up>")
16066 (lambda () (interactive)
16067 (org-eval-in-calendar '(calendar-backward-year 1))))
16068 (org-defkey map (kbd "M-S-<down>")
16069 (lambda () (interactive)
16070 (org-eval-in-calendar '(calendar-forward-year 1))))
16071 (org-defkey map (kbd "ESC S-<down>")
16072 (lambda () (interactive)
16073 (org-eval-in-calendar '(calendar-forward-year 1))))
16074 (org-defkey map (kbd "S-<up>")
16075 (lambda () (interactive)
16076 (org-eval-in-calendar '(calendar-backward-week 1))))
16077 (org-defkey map (kbd "S-<down>")
16078 (lambda () (interactive)
16079 (org-eval-in-calendar '(calendar-forward-week 1))))
16080 (org-defkey map (kbd "S-<left>")
16081 (lambda () (interactive)
16082 (org-eval-in-calendar '(calendar-backward-day 1))))
16083 (org-defkey map (kbd "S-<right>")
16084 (lambda () (interactive)
16085 (org-eval-in-calendar '(calendar-forward-day 1))))
16086 (org-defkey map (kbd "!")
16087 (lambda () (interactive)
16088 (org-eval-in-calendar '(diary-view-entries))
16089 (message "")))
16090 (org-defkey map (kbd ">")
16091 (lambda () (interactive)
16092 (org-eval-in-calendar '(calendar-scroll-left 1))))
16093 (org-defkey map (kbd "<")
16094 (lambda () (interactive)
16095 (org-eval-in-calendar '(calendar-scroll-right 1))))
16096 (org-defkey map (kbd "C-v")
16097 (lambda () (interactive)
16098 (org-eval-in-calendar
16099 '(calendar-scroll-left-three-months 1))))
16100 (org-defkey map (kbd "M-v")
16101 (lambda () (interactive)
16102 (org-eval-in-calendar
16103 '(calendar-scroll-right-three-months 1))))
16104 map)
16105 "Keymap for minibuffer commands when using `org-read-date'.")
16107 (defvar org-def)
16108 (defvar org-defdecode)
16109 (defvar org-with-time)
16111 (defvar calendar-setup) ; Dynamically scoped.
16112 (defun org-read-date (&optional with-time to-time from-string prompt
16113 default-time default-input inactive)
16114 "Read a date, possibly a time, and make things smooth for the user.
16115 The prompt will suggest to enter an ISO date, but you can also enter anything
16116 which will at least partially be understood by `parse-time-string'.
16117 Unrecognized parts of the date will default to the current day, month, year,
16118 hour and minute. If this command is called to replace a timestamp at point,
16119 or to enter the second timestamp of a range, the default time is taken
16120 from the existing stamp. Furthermore, the command prefers the future,
16121 so if you are giving a date where the year is not given, and the day-month
16122 combination is already past in the current year, it will assume you
16123 mean next year. For details, see the manual. A few examples:
16125 3-2-5 --> 2003-02-05
16126 feb 15 --> currentyear-02-15
16127 2/15 --> currentyear-02-15
16128 sep 12 9 --> 2009-09-12
16129 12:45 --> today 12:45
16130 22 sept 0:34 --> currentyear-09-22 0:34
16131 12 --> currentyear-currentmonth-12
16132 Fri --> nearest Friday after today
16133 -Tue --> last Tuesday
16134 etc.
16136 Furthermore you can specify a relative date by giving, as the *first* thing
16137 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16138 change in days weeks, months, years.
16139 With a single plus or minus, the date is relative to today. With a double
16140 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16141 +4d --> four days from today
16142 +4 --> same as above
16143 +2w --> two weeks from today
16144 ++5 --> five days from default date
16146 The function understands only English month and weekday abbreviations.
16148 While prompting, a calendar is popped up - you can also select the
16149 date with the mouse (button 1). The calendar shows a period of three
16150 months. To scroll it to other months, use the keys `>' and `<'.
16151 If you don't like the calendar, turn it off with
16152 (setq org-read-date-popup-calendar nil)
16154 With optional argument TO-TIME, the date will immediately be converted
16155 to an internal time.
16156 With an optional argument WITH-TIME, the prompt will suggest to
16157 also insert a time. Note that when WITH-TIME is not set, you can
16158 still enter a time, and this function will inform the calling routine
16159 about this change. The calling routine may then choose to change the
16160 format used to insert the time stamp into the buffer to include the time.
16161 With optional argument FROM-STRING, read from this string instead from
16162 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16163 the time/date that is used for everything that is not specified by the
16164 user."
16165 (require 'parse-time)
16166 (let* ((org-with-time with-time)
16167 (org-time-stamp-rounding-minutes
16168 (if (equal org-with-time '(16))
16169 '(0 0)
16170 org-time-stamp-rounding-minutes))
16171 (org-dcst org-display-custom-times)
16172 (ct (org-current-time))
16173 (org-def (or org-overriding-default-time default-time ct))
16174 (org-defdecode (decode-time org-def))
16175 (cur-frame (selected-frame))
16176 (mouse-autoselect-window nil) ; Don't let the mouse jump
16177 (calendar-setup
16178 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16179 (calendar-move-hook nil)
16180 (calendar-view-diary-initially-flag nil)
16181 (calendar-view-holidays-initially-flag nil)
16182 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16183 ;; Rationalize `org-def' and `org-defdecode', if required.
16184 (when (< (nth 2 org-defdecode) org-extend-today-until)
16185 (setf (nth 2 org-defdecode) -1)
16186 (setf (nth 1 org-defdecode) 59)
16187 (setq org-def (apply #'encode-time org-defdecode))
16188 (setq org-defdecode (decode-time org-def)))
16189 (let* ((timestr (format-time-string
16190 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16191 org-def))
16192 (prompt (concat (if prompt (concat prompt " ") "")
16193 (format "Date+time [%s]: " timestr))))
16194 (cond
16195 (from-string (setq ans from-string))
16196 (org-read-date-popup-calendar
16197 (save-excursion
16198 (save-window-excursion
16199 (calendar)
16200 (when (eq calendar-setup 'calendar-only)
16201 (setq cal-frame
16202 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16203 (select-frame cal-frame))
16204 (org-eval-in-calendar '(setq cursor-type nil) t)
16205 (unwind-protect
16206 (progn
16207 (calendar-forward-day (- (time-to-days org-def)
16208 (calendar-absolute-from-gregorian
16209 (calendar-current-date))))
16210 (org-eval-in-calendar nil t)
16211 (let* ((old-map (current-local-map))
16212 (map (copy-keymap calendar-mode-map))
16213 (minibuffer-local-map
16214 (copy-keymap org-read-date-minibuffer-local-map)))
16215 (org-defkey map (kbd "RET") 'org-calendar-select)
16216 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16217 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16218 (unwind-protect
16219 (progn
16220 (use-local-map map)
16221 (setq org-read-date-inactive inactive)
16222 (add-hook 'post-command-hook 'org-read-date-display)
16223 (setq org-ans0
16224 (read-string prompt
16225 default-input
16226 'org-read-date-history
16227 nil))
16228 ;; org-ans0: from prompt
16229 ;; org-ans1: from mouse click
16230 ;; org-ans2: from calendar motion
16231 (setq ans
16232 (concat org-ans0 " " (or org-ans1 org-ans2))))
16233 (remove-hook 'post-command-hook 'org-read-date-display)
16234 (use-local-map old-map)
16235 (when org-read-date-overlay
16236 (delete-overlay org-read-date-overlay)
16237 (setq org-read-date-overlay nil)))))
16238 (bury-buffer "*Calendar*")
16239 (when cal-frame
16240 (delete-frame cal-frame)
16241 (select-frame-set-input-focus cur-frame))))))
16243 (t ; Naked prompt only
16244 (unwind-protect
16245 (setq ans (read-string prompt default-input
16246 'org-read-date-history timestr))
16247 (when org-read-date-overlay
16248 (delete-overlay org-read-date-overlay)
16249 (setq org-read-date-overlay nil))))))
16251 (setq final (org-read-date-analyze ans org-def org-defdecode))
16253 (when org-read-date-analyze-forced-year
16254 (message "Year was forced into %s"
16255 (if org-read-date-force-compatible-dates
16256 "compatible range (1970-2037)"
16257 "range representable on this machine"))
16258 (ding))
16260 ;; One round trip to get rid of 34th of August and stuff like that....
16261 (setq final (decode-time (apply 'encode-time final)))
16263 (setq org-read-date-final-answer ans)
16265 (if to-time
16266 (apply 'encode-time final)
16267 (if (and (boundp 'org-time-was-given) org-time-was-given)
16268 (format "%04d-%02d-%02d %02d:%02d"
16269 (nth 5 final) (nth 4 final) (nth 3 final)
16270 (nth 2 final) (nth 1 final))
16271 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16273 (defun org-read-date-display ()
16274 "Display the current date prompt interpretation in the minibuffer."
16275 (when org-read-date-display-live
16276 (when org-read-date-overlay
16277 (delete-overlay org-read-date-overlay))
16278 (when (minibufferp (current-buffer))
16279 (save-excursion
16280 (end-of-line 1)
16281 (while (not (equal (buffer-substring
16282 (max (point-min) (- (point) 4)) (point))
16283 " "))
16284 (insert " ")))
16285 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16286 " " (or org-ans1 org-ans2)))
16287 (org-end-time-was-given nil)
16288 (f (org-read-date-analyze ans org-def org-defdecode))
16289 (fmts (if org-dcst
16290 org-time-stamp-custom-formats
16291 org-time-stamp-formats))
16292 (fmt (if (or org-with-time
16293 (and (boundp 'org-time-was-given) org-time-was-given))
16294 (cdr fmts)
16295 (car fmts)))
16296 (txt (format-time-string fmt (apply 'encode-time f)))
16297 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16298 (txt (concat "=> " txt)))
16299 (when (and org-end-time-was-given
16300 (string-match org-plain-time-of-day-regexp txt))
16301 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16302 org-end-time-was-given
16303 (substring txt (match-end 0)))))
16304 (when org-read-date-analyze-futurep
16305 (setq txt (concat txt " (=>F)")))
16306 (setq org-read-date-overlay
16307 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16308 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16310 (defun org-read-date-analyze (ans def defdecode)
16311 "Analyze the combined answer of the date prompt."
16312 ;; FIXME: cleanup and comment
16313 ;; Pass `current-time' result to `decode-time' (instead of calling
16314 ;; without arguments) so that only `current-time' has to be
16315 ;; overridden in tests.
16316 (let ((org-def def)
16317 (org-defdecode defdecode)
16318 (nowdecode (decode-time (current-time)))
16319 delta deltan deltaw deltadef year month day
16320 hour minute second wday pm h2 m2 tl wday1
16321 iso-year iso-weekday iso-week iso-date futurep kill-year)
16322 (setq org-read-date-analyze-futurep nil
16323 org-read-date-analyze-forced-year nil)
16324 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16325 (setq ans "+0"))
16327 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16328 (setq ans (replace-match "" t t ans)
16329 deltan (car delta)
16330 deltaw (nth 1 delta)
16331 deltadef (nth 2 delta)))
16333 ;; Check if there is an iso week date in there. If yes, store the
16334 ;; info and postpone interpreting it until the rest of the parsing
16335 ;; is done.
16336 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16337 (setq iso-year (when (match-end 1)
16338 (org-small-year-to-year
16339 (string-to-number (match-string 1 ans))))
16340 iso-weekday (when (match-end 3)
16341 (string-to-number (match-string 3 ans)))
16342 iso-week (string-to-number (match-string 2 ans)))
16343 (setq ans (replace-match "" t t ans)))
16345 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16346 (when (string-match
16347 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16348 (setq year (if (match-end 2)
16349 (string-to-number (match-string 2 ans))
16350 (progn (setq kill-year t)
16351 (string-to-number (format-time-string "%Y"))))
16352 month (string-to-number (match-string 3 ans))
16353 day (string-to-number (match-string 4 ans)))
16354 (setq year (org-small-year-to-year year))
16355 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16356 t nil ans)))
16358 ;; Help matching dotted european dates
16359 (when (string-match
16360 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16361 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16362 (setq kill-year t)
16363 (string-to-number (format-time-string "%Y")))
16364 day (string-to-number (match-string 1 ans))
16365 month (string-to-number (match-string 2 ans))
16366 ans (replace-match (format "%04d-%02d-%02d" year month day)
16367 t nil ans)))
16369 ;; Help matching american dates, like 5/30 or 5/30/7
16370 (when (string-match
16371 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16372 (setq year (if (match-end 4)
16373 (string-to-number (match-string 4 ans))
16374 (progn (setq kill-year t)
16375 (string-to-number (format-time-string "%Y"))))
16376 month (string-to-number (match-string 1 ans))
16377 day (string-to-number (match-string 2 ans)))
16378 (setq year (org-small-year-to-year year))
16379 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16380 t nil ans)))
16381 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16382 ;; If there is a time with am/pm, and *no* time without it, we convert
16383 ;; so that matching will be successful.
16384 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16385 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16386 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16387 (setq hour (string-to-number (match-string 1 ans))
16388 minute (if (match-end 3)
16389 (string-to-number (match-string 3 ans))
16391 pm (equal ?p
16392 (string-to-char (downcase (match-string 4 ans)))))
16393 (if (and (= hour 12) (not pm))
16394 (setq hour 0)
16395 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16396 (setq ans (replace-match (format "%02d:%02d" hour minute)
16397 t t ans))))
16399 ;; Check if a time range is given as a duration
16400 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16401 (setq hour (string-to-number (match-string 1 ans))
16402 h2 (+ hour (string-to-number (match-string 3 ans)))
16403 minute (string-to-number (match-string 2 ans))
16404 m2 (+ minute (if (match-end 5) (string-to-number
16405 (match-string 5 ans))0)))
16406 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16407 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16408 t t ans)))
16410 ;; Check if there is a time range
16411 (when (boundp 'org-end-time-was-given)
16412 (setq org-time-was-given nil)
16413 (when (and (string-match org-plain-time-of-day-regexp ans)
16414 (match-end 8))
16415 (setq org-end-time-was-given (match-string 8 ans))
16416 (setq ans (concat (substring ans 0 (match-beginning 7))
16417 (substring ans (match-end 7))))))
16419 (setq tl (parse-time-string ans)
16420 day (or (nth 3 tl) (nth 3 org-defdecode))
16421 month
16422 (cond ((nth 4 tl))
16423 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16424 ;; Day was specified. Make sure DAY+MONTH
16425 ;; combination happens in the future.
16426 ((nth 3 tl)
16427 (setq futurep t)
16428 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16429 (nth 4 nowdecode)))
16430 (t (nth 4 org-defdecode)))
16431 year
16432 (cond ((and (not kill-year) (nth 5 tl)))
16433 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16434 ;; Month was guessed in the future and is at least
16435 ;; equal to NOWDECODE's. Fix year accordingly.
16436 (futurep
16437 (if (or (> month (nth 4 nowdecode))
16438 (>= day (nth 3 nowdecode)))
16439 (nth 5 nowdecode)
16440 (1+ (nth 5 nowdecode))))
16441 ;; Month was specified. Make sure MONTH+YEAR
16442 ;; combination happens in the future.
16443 ((nth 4 tl)
16444 (setq futurep t)
16445 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16446 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16447 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16448 (t (nth 5 nowdecode))))
16449 (t (nth 5 org-defdecode)))
16450 hour (or (nth 2 tl) (nth 2 org-defdecode))
16451 minute (or (nth 1 tl) (nth 1 org-defdecode))
16452 second (or (nth 0 tl) 0)
16453 wday (nth 6 tl))
16455 (when (and (eq org-read-date-prefer-future 'time)
16456 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16457 (equal day (nth 3 nowdecode))
16458 (equal month (nth 4 nowdecode))
16459 (equal year (nth 5 nowdecode))
16460 (nth 2 tl)
16461 (or (< (nth 2 tl) (nth 2 nowdecode))
16462 (and (= (nth 2 tl) (nth 2 nowdecode))
16463 (nth 1 tl)
16464 (< (nth 1 tl) (nth 1 nowdecode)))))
16465 (setq day (1+ day)
16466 futurep t))
16468 ;; Special date definitions below
16469 (cond
16470 (iso-week
16471 ;; There was an iso week
16472 (require 'cal-iso)
16473 (setq futurep nil)
16474 (setq year (or iso-year year)
16475 day (or iso-weekday wday 1)
16476 wday nil ; to make sure that the trigger below does not match
16477 iso-date (calendar-gregorian-from-absolute
16478 (calendar-iso-to-absolute
16479 (list iso-week day year))))
16480 ; FIXME: Should we also push ISO weeks into the future?
16481 ; (when (and org-read-date-prefer-future
16482 ; (not iso-year)
16483 ; (< (calendar-absolute-from-gregorian iso-date)
16484 ; (time-to-days (current-time))))
16485 ; (setq year (1+ year)
16486 ; iso-date (calendar-gregorian-from-absolute
16487 ; (calendar-iso-to-absolute
16488 ; (list iso-week day year)))))
16489 (setq month (car iso-date)
16490 year (nth 2 iso-date)
16491 day (nth 1 iso-date)))
16492 (deltan
16493 (setq futurep nil)
16494 (unless deltadef
16495 ;; Pass `current-time' result to `decode-time' (instead of
16496 ;; calling without arguments) so that only `current-time' has
16497 ;; to be overridden in tests.
16498 (let ((now (decode-time (current-time))))
16499 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16500 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16501 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16502 ((equal deltaw "m") (setq month (+ month deltan)))
16503 ((equal deltaw "y") (setq year (+ year deltan)))))
16504 ((and wday (not (nth 3 tl)))
16505 ;; Weekday was given, but no day, so pick that day in the week
16506 ;; on or after the derived date.
16507 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16508 (unless (equal wday wday1)
16509 (setq day (+ day (% (- wday wday1 -7) 7))))))
16510 (when (and (boundp 'org-time-was-given)
16511 (nth 2 tl))
16512 (setq org-time-was-given t))
16513 (when (< year 100) (setq year (+ 2000 year)))
16514 ;; Check of the date is representable
16515 (if org-read-date-force-compatible-dates
16516 (progn
16517 (when (< year 1970)
16518 (setq year 1970 org-read-date-analyze-forced-year t))
16519 (when (> year 2037)
16520 (setq year 2037 org-read-date-analyze-forced-year t)))
16521 (condition-case nil
16522 (ignore (encode-time second minute hour day month year))
16523 (error
16524 (setq year (nth 5 org-defdecode))
16525 (setq org-read-date-analyze-forced-year t))))
16526 (setq org-read-date-analyze-futurep futurep)
16527 (list second minute hour day month year)))
16529 (defvar parse-time-weekdays)
16530 (defun org-read-date-get-relative (s today default)
16531 "Check string S for special relative date string.
16532 TODAY and DEFAULT are internal times, for today and for a default.
16533 Return shift list (N what def-flag)
16534 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16535 N is the number of WHATs to shift.
16536 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16537 the DEFAULT date rather than TODAY."
16538 (require 'parse-time)
16539 (when (and
16540 (string-match
16541 (concat
16542 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16543 "\\([0-9]+\\)?"
16544 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16545 "\\([ \t]\\|$\\)") s)
16546 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16547 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16548 (string-to-char (substring (match-string 1 s) -1))
16549 ?+))
16550 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16551 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16552 (what (if (match-end 3) (match-string 3 s) "d"))
16553 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16554 (date (if rel default today))
16555 (wday (nth 6 (decode-time date)))
16556 delta)
16557 (if wday1
16558 (progn
16559 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16560 (when (= delta 0) (setq delta 7))
16561 (when (= dir ?-)
16562 (setq delta (- delta 7))
16563 (when (= delta 0) (setq delta -7)))
16564 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16565 (list delta "d" rel))
16566 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16568 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16569 "Turn a user-specified date into the internal representation.
16570 The internal representation needed by the calendar is (month day year).
16571 This is a wrapper to handle the brain-dead convention in calendar that
16572 user function argument order change dependent on argument order."
16573 (pcase calendar-date-style
16574 (`american (list arg1 arg2 arg3))
16575 (`european (list arg2 arg1 arg3))
16576 (`iso (list arg2 arg3 arg1))))
16578 (defun org-eval-in-calendar (form &optional keepdate)
16579 "Eval FORM in the calendar window and return to current window.
16580 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16581 (let ((sf (selected-frame))
16582 (sw (selected-window)))
16583 (select-window (get-buffer-window "*Calendar*" t))
16584 (eval form)
16585 (when (and (not keepdate) (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-ans2 (format-time-string "%Y-%m-%d" time))))
16589 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16590 (select-window sw)
16591 (select-frame-set-input-focus sf)))
16593 (defun org-calendar-select ()
16594 "Return to `org-read-date' with the date currently selected.
16595 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16596 (interactive)
16597 (when (calendar-cursor-to-date)
16598 (let* ((date (calendar-cursor-to-date))
16599 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16600 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16601 (when (active-minibuffer-window) (exit-minibuffer))))
16603 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16604 "Insert a date stamp for the date given by the internal TIME.
16605 See `format-time-string' for the format of TIME.
16606 WITH-HM means use the stamp format that includes the time of the day.
16607 INACTIVE means use square brackets instead of angular ones, so that the
16608 stamp will not contribute to the agenda.
16609 PRE and POST are optional strings to be inserted before and after the
16610 stamp.
16611 The command returns the inserted time stamp."
16612 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16613 stamp)
16614 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16615 (insert-before-markers (or pre ""))
16616 (when (listp extra)
16617 (setq extra (car extra))
16618 (if (and (stringp extra)
16619 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16620 (setq extra (format "-%02d:%02d"
16621 (string-to-number (match-string 1 extra))
16622 (string-to-number (match-string 2 extra))))
16623 (setq extra nil)))
16624 (when extra
16625 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16626 (insert-before-markers (setq stamp (format-time-string fmt time)))
16627 (insert-before-markers (or post ""))
16628 (setq org-last-inserted-timestamp stamp)))
16630 (defun org-toggle-time-stamp-overlays ()
16631 "Toggle the use of custom time stamp formats."
16632 (interactive)
16633 (setq org-display-custom-times (not org-display-custom-times))
16634 (unless org-display-custom-times
16635 (let ((p (point-min)) (bmp (buffer-modified-p)))
16636 (while (setq p (next-single-property-change p 'display))
16637 (when (and (get-text-property p 'display)
16638 (eq (get-text-property p 'face) 'org-date))
16639 (remove-text-properties
16640 p (setq p (next-single-property-change p 'display))
16641 '(display t))))
16642 (set-buffer-modified-p bmp)))
16643 (org-restart-font-lock)
16644 (setq org-table-may-need-update t)
16645 (if org-display-custom-times
16646 (message "Time stamps are overlaid with custom format")
16647 (message "Time stamp overlays removed")))
16649 (defun org-display-custom-time (beg end)
16650 "Overlay modified time stamp format over timestamp between BEG and END."
16651 (let* ((ts (buffer-substring beg end))
16652 t1 with-hm tf time str (off 0))
16653 (save-match-data
16654 (setq t1 (org-parse-time-string ts t))
16655 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16656 (setq off (- (match-end 0) (match-beginning 0)))))
16657 (setq end (- end off))
16658 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16659 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16660 time (org-fix-decoded-time t1)
16661 str (org-add-props
16662 (format-time-string
16663 (substring tf 1 -1) (apply 'encode-time time))
16664 nil 'mouse-face 'highlight))
16665 (put-text-property beg end 'display str)))
16667 (defun org-fix-decoded-time (time)
16668 "Set 0 instead of nil for the first 6 elements of time.
16669 Don't touch the rest."
16670 (let ((n 0))
16671 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16673 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16674 "Difference between TIMESTAMP-STRING and now in days.
16675 If SECONDS is non-nil, return the difference in seconds."
16676 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16677 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16678 (funcall fdiff (current-time)))))
16680 (defun org-deadline-close-p (timestamp-string &optional ndays)
16681 "Is the time in TIMESTAMP-STRING close to the current date?"
16682 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16683 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16684 (not (org-entry-is-done-p))))
16686 (defun org-get-wdays (ts &optional delay zero-delay)
16687 "Get the deadline lead time appropriate for timestring TS.
16688 When DELAY is non-nil, get the delay time for scheduled items
16689 instead of the deadline lead time. When ZERO-DELAY is non-nil
16690 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16691 don't try to find the delay cookie in the scheduled timestamp."
16692 (let ((tv (if delay org-scheduled-delay-days
16693 org-deadline-warning-days)))
16694 (cond
16695 ((or (and delay (< tv 0))
16696 (and delay zero-delay (<= tv 0))
16697 (and (not delay) (<= tv 0)))
16698 ;; Enforce this value no matter what
16699 (- tv))
16700 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16701 ;; lead time is specified.
16702 (floor (* (string-to-number (match-string 1 ts))
16703 (cdr (assoc (match-string 2 ts)
16704 '(("d" . 1) ("w" . 7)
16705 ("m" . 30.4) ("y" . 365.25)
16706 ("h" . 0.041667)))))))
16707 ;; go for the default.
16708 (t tv))))
16710 (defun org-calendar-select-mouse (ev)
16711 "Return to `org-read-date' with the date currently selected.
16712 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16713 (interactive "e")
16714 (mouse-set-point ev)
16715 (when (calendar-cursor-to-date)
16716 (let* ((date (calendar-cursor-to-date))
16717 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16718 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16719 (when (active-minibuffer-window) (exit-minibuffer))))
16721 (defun org-check-deadlines (ndays)
16722 "Check if there are any deadlines due or past due.
16723 A deadline is considered due if it happens within `org-deadline-warning-days'
16724 days from today's date. If the deadline appears in an entry marked DONE,
16725 it is not shown. A numeric prefix argument NDAYS can be used to test that
16726 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16727 are shown."
16728 (interactive "P")
16729 (let* ((org-warn-days
16730 (cond
16731 ((equal ndays '(4)) 100000)
16732 (ndays (prefix-numeric-value ndays))
16733 (t (abs org-deadline-warning-days))))
16734 (case-fold-search nil)
16735 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16736 (callback
16737 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16738 (message "%d deadlines past-due or due within %d days"
16739 (org-occur regexp nil callback)
16740 org-warn-days)))
16742 (defsubst org-re-timestamp (type)
16743 "Return a regexp for timestamp TYPE.
16744 Allowed values for TYPE are:
16746 all: all timestamps
16747 active: only active timestamps (<...>)
16748 inactive: only inactive timestamps ([...])
16749 scheduled: only scheduled timestamps
16750 deadline: only deadline timestamps
16751 closed: only closed time-stamps
16753 When TYPE is nil, fall back on returning a regexp that matches
16754 both scheduled and deadline timestamps."
16755 (cl-case type
16756 (all org-ts-regexp-both)
16757 (active org-ts-regexp)
16758 (inactive org-ts-regexp-inactive)
16759 (scheduled org-scheduled-time-regexp)
16760 (deadline org-deadline-time-regexp)
16761 (closed org-closed-time-regexp)
16762 (otherwise
16763 (concat "\\<"
16764 (regexp-opt (list org-deadline-string org-scheduled-string))
16765 " *<\\([^>]+\\)>"))))
16767 (defun org-check-before-date (d)
16768 "Check if there are deadlines or scheduled entries before date D."
16769 (interactive (list (org-read-date)))
16770 (let* ((case-fold-search nil)
16771 (regexp (org-re-timestamp org-ts-type))
16772 (ts-type org-ts-type)
16773 (callback
16774 (lambda ()
16775 (let ((match (match-string 1)))
16776 (and (if (memq ts-type '(active inactive all))
16777 (eq (org-element-type (save-excursion
16778 (backward-char)
16779 (org-element-context)))
16780 'timestamp)
16781 (org-at-planning-p))
16782 (time-less-p
16783 (org-time-string-to-time match)
16784 (org-time-string-to-time d)))))))
16785 (message "%d entries before %s"
16786 (org-occur regexp nil callback)
16787 d)))
16789 (defun org-check-after-date (d)
16790 "Check if there are deadlines or scheduled entries after date D."
16791 (interactive (list (org-read-date)))
16792 (let* ((case-fold-search nil)
16793 (regexp (org-re-timestamp org-ts-type))
16794 (ts-type org-ts-type)
16795 (callback
16796 (lambda ()
16797 (let ((match (match-string 1)))
16798 (and (if (memq ts-type '(active inactive all))
16799 (eq (org-element-type (save-excursion
16800 (backward-char)
16801 (org-element-context)))
16802 'timestamp)
16803 (org-at-planning-p))
16804 (not (time-less-p
16805 (org-time-string-to-time match)
16806 (org-time-string-to-time d))))))))
16807 (message "%d entries after %s"
16808 (org-occur regexp nil callback)
16809 d)))
16811 (defun org-check-dates-range (start-date end-date)
16812 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16813 (interactive (list (org-read-date nil nil nil "Range starts")
16814 (org-read-date nil nil nil "Range end")))
16815 (let ((case-fold-search nil)
16816 (regexp (org-re-timestamp org-ts-type))
16817 (callback
16818 (let ((type org-ts-type))
16819 (lambda ()
16820 (let ((match (match-string 1)))
16821 (and
16822 (if (memq type '(active inactive all))
16823 (eq (org-element-type (save-excursion
16824 (backward-char)
16825 (org-element-context)))
16826 'timestamp)
16827 (org-at-planning-p))
16828 (not (time-less-p
16829 (org-time-string-to-time match)
16830 (org-time-string-to-time start-date)))
16831 (time-less-p
16832 (org-time-string-to-time match)
16833 (org-time-string-to-time end-date))))))))
16834 (message "%d entries between %s and %s"
16835 (org-occur regexp nil callback) start-date end-date)))
16837 (defun org-evaluate-time-range (&optional to-buffer)
16838 "Evaluate a time range by computing the difference between start and end.
16839 Normally the result is just printed in the echo area, but with prefix arg
16840 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16841 If the time range is actually in a table, the result is inserted into the
16842 next column.
16843 For time difference computation, a year is assumed to be exactly 365
16844 days in order to avoid rounding problems."
16845 (interactive "P")
16847 (org-clock-update-time-maybe)
16848 (save-excursion
16849 (unless (org-at-date-range-p t)
16850 (goto-char (point-at-bol))
16851 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16852 (unless (org-at-date-range-p t)
16853 (user-error "Not at a time-stamp range, and none found in current line")))
16854 (let* ((ts1 (match-string 1))
16855 (ts2 (match-string 2))
16856 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16857 (match-end (match-end 0))
16858 (time1 (org-time-string-to-time ts1))
16859 (time2 (org-time-string-to-time ts2))
16860 (t1 (float-time time1))
16861 (t2 (float-time time2))
16862 (diff (abs (- t2 t1)))
16863 (negative (< (- t2 t1) 0))
16864 ;; (ys (floor (* 365 24 60 60)))
16865 (ds (* 24 60 60))
16866 (hs (* 60 60))
16867 (fy "%dy %dd %02d:%02d")
16868 (fy1 "%dy %dd")
16869 (fd "%dd %02d:%02d")
16870 (fd1 "%dd")
16871 (fh "%02d:%02d")
16872 y d h m align)
16873 (if havetime
16874 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16876 d (floor (/ diff ds)) diff (mod diff ds)
16877 h (floor (/ diff hs)) diff (mod diff hs)
16878 m (floor (/ diff 60)))
16879 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16881 d (floor (+ (/ diff ds) 0.5))
16882 h 0 m 0))
16883 (if (not to-buffer)
16884 (message "%s" (org-make-tdiff-string y d h m))
16885 (if (org-at-table-p)
16886 (progn
16887 (goto-char match-end)
16888 (setq align t)
16889 (and (looking-at " *|") (goto-char (match-end 0))))
16890 (goto-char match-end))
16891 (when (looking-at
16892 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16893 (replace-match ""))
16894 (when negative (insert " -"))
16895 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16896 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16897 (insert " " (format fh h m))))
16898 (when align (org-table-align))
16899 (message "Time difference inserted")))))
16901 (defun org-make-tdiff-string (y d h m)
16902 (let ((fmt "")
16903 (l nil))
16904 (when (> y 0)
16905 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16906 (push y l))
16907 (when (> d 0)
16908 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16909 (push d l))
16910 (when (> h 0)
16911 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16912 (push h l))
16913 (when (> m 0)
16914 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16915 (push m l))
16916 (apply 'format fmt (nreverse l))))
16918 (defun org-time-string-to-time (s)
16919 "Convert timestamp string S into internal time."
16920 (apply #'encode-time (org-parse-time-string s)))
16922 (defun org-time-string-to-seconds (s)
16923 "Convert a timestamp string S into a number of seconds."
16924 (float-time (org-time-string-to-time s)))
16926 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16928 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16929 "Convert time stamp S to an absolute day number.
16931 If DAYNR in non-nil, and there is a specifier for a cyclic time
16932 stamp, get the closest date to DAYNR. If PREFER is
16933 `past' (respectively `future') return a date past (respectively
16934 after) or equal to DAYNR.
16936 POS is the location of time stamp S, as a buffer position in
16937 BUFFER.
16939 Diary sexp timestamps are matched against DAYNR, when non-nil.
16940 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16941 signaled."
16942 (cond
16943 ((string-match "\\`%%\\((.*)\\)" s)
16944 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16945 ;; only able to match individual dates. If it fails, raise an
16946 ;; error.
16947 (if (and daynr
16948 (org-diary-sexp-entry
16949 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16950 daynr
16951 (signal 'org-diary-sexp-no-match (list s))))
16952 (daynr (org-closest-date s daynr prefer))
16953 (t (time-to-days
16954 (condition-case errdata
16955 (apply #'encode-time (org-parse-time-string s))
16956 (error (error "Bad timestamp `%s'%s\nError was: %s"
16958 (if (not (and buffer pos)) ""
16959 (format-message " at %d in buffer `%s'" pos buffer))
16960 (cdr errdata))))))))
16962 (defun org-days-to-iso-week (days)
16963 "Return the iso week number."
16964 (require 'cal-iso)
16965 (car (calendar-iso-from-absolute days)))
16967 (defun org-small-year-to-year (year)
16968 "Convert 2-digit years into 4-digit years.
16969 YEAR is expanded into one of the 30 next years, if possible, or
16970 into a past one. Any year larger than 99 is returned unchanged."
16971 (if (>= year 100) year
16972 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16973 (century (/ current 100))
16974 (offset (- year (% current 100))))
16975 (cond ((> offset 30) (+ (* (1- century) 100) year))
16976 ((> offset -70) (+ (* century 100) year))
16977 (t (+ (* (1+ century) 100) year))))))
16979 (defun org-time-from-absolute (d)
16980 "Return the time corresponding to date D.
16981 D may be an absolute day number, or a calendar-type list (month day year)."
16982 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16983 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16985 (defvar org-agenda-current-date)
16986 (defun org-calendar-holiday ()
16987 "List of holidays, for Diary display in Org mode."
16988 (require 'holidays)
16989 (let ((hl (calendar-check-holidays org-agenda-current-date)))
16990 (and hl (mapconcat #'identity hl "; "))))
16992 (defun org-diary-sexp-entry (sexp entry d)
16993 "Process a SEXP diary ENTRY for date D."
16994 (require 'diary-lib)
16995 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
16996 ;; dynamically.
16997 (let* ((sexp `(let ((entry ,entry)
16998 (date ',d))
16999 ,(car (read-from-string sexp))))
17000 (result (if calendar-debug-sexp (eval sexp)
17001 (condition-case nil
17002 (eval sexp)
17003 (error
17004 (beep)
17005 (message "Bad sexp at line %d in %s: %s"
17006 (org-current-line)
17007 (buffer-file-name) sexp)
17008 (sleep-for 2))))))
17009 (cond ((stringp result) (split-string result "; "))
17010 ((and (consp result)
17011 (not (consp (cdr result)))
17012 (stringp (cdr result))) (cdr result))
17013 ((and (consp result)
17014 (stringp (car result))) result)
17015 (result entry))))
17017 (defun org-diary-to-ical-string (frombuf)
17018 "Get iCalendar entries from diary entries in buffer FROMBUF.
17019 This uses the icalendar.el library."
17020 (let* ((tmpdir temporary-file-directory)
17021 (tmpfile (make-temp-name
17022 (expand-file-name "orgics" tmpdir)))
17023 buf rtn b e)
17024 (with-current-buffer frombuf
17025 (icalendar-export-region (point-min) (point-max) tmpfile)
17026 (setq buf (find-buffer-visiting tmpfile))
17027 (set-buffer buf)
17028 (goto-char (point-min))
17029 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17030 (setq b (match-beginning 0)))
17031 (goto-char (point-max))
17032 (when (re-search-backward "^END:VEVENT" nil t)
17033 (setq e (match-end 0)))
17034 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17035 (kill-buffer buf)
17036 (delete-file tmpfile)
17037 rtn))
17039 (defun org-closest-date (start current prefer)
17040 "Return closest date to CURRENT starting from START.
17042 CURRENT and START are both time stamps.
17044 When PREFER is `past', return a date that is either CURRENT or
17045 past. When PREFER is `future', return a date that is either
17046 CURRENT or future.
17048 Only time stamps with a repeater are modified. Any other time
17049 stamp stay unchanged. In any case, return value is an absolute
17050 day number."
17051 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17052 ;; No repeater. Do not shift time stamp.
17053 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17054 (let ((value (string-to-number (match-string 1 start)))
17055 (type (match-string 2 start)))
17056 (if (= 0 value)
17057 ;; Repeater with a 0-value is considered as void.
17058 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17059 (let* ((base (org-date-to-gregorian start))
17060 (target (org-date-to-gregorian current))
17061 (sday (calendar-absolute-from-gregorian base))
17062 (cday (calendar-absolute-from-gregorian target))
17063 n1 n2)
17064 ;; If START is already past CURRENT, just return START.
17065 (if (<= cday sday) sday
17066 ;; Compute closest date before (N1) and closest date past
17067 ;; (N2) CURRENT.
17068 (pcase type
17069 ("h"
17070 (let ((missing-hours
17071 (mod (+ (- (* 24 (- cday sday))
17072 (nth 2 (org-parse-time-string start)))
17073 org-extend-today-until)
17074 value)))
17075 (setf n1 (if (= missing-hours 0) cday
17076 (- cday (1+ (/ missing-hours 24)))))
17077 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17078 ((or "d" "w")
17079 (let ((value (if (equal type "w") (* 7 value) value)))
17080 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17081 (setf n2 (+ n1 value))))
17082 ("m"
17083 (let* ((add-months
17084 (lambda (d n)
17085 ;; Add N months to gregorian date D, i.e.,
17086 ;; a list (MONTH DAY YEAR). Return a valid
17087 ;; gregorian date.
17088 (let ((m (+ (nth 0 d) n)))
17089 (list (mod m 12)
17090 (nth 1 d)
17091 (+ (/ m 12) (nth 2 d))))))
17092 (months ; Complete months to TARGET.
17093 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17094 (- (nth 0 target) (nth 0 base))
17095 ;; If START's day is greater than
17096 ;; TARGET's, remove incomplete month.
17097 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17098 value)
17099 value))
17100 (before (funcall add-months base months)))
17101 (setf n1 (calendar-absolute-from-gregorian before))
17102 (setf n2
17103 (calendar-absolute-from-gregorian
17104 (funcall add-months before value)))))
17106 (let* ((d (nth 1 base))
17107 (m (nth 0 base))
17108 (y (nth 2 base))
17109 (years ; Complete years to TARGET.
17110 (* (/ (- (nth 2 target)
17112 ;; If START's month and day are
17113 ;; greater than TARGET's, remove
17114 ;; incomplete year.
17115 (if (or (> (nth 0 target) m)
17116 (and (= (nth 0 target) m)
17117 (> (nth 1 target) d)))
17120 value)
17121 value))
17122 (before (list m d (+ y years))))
17123 (setf n1 (calendar-absolute-from-gregorian before))
17124 (setf n2 (calendar-absolute-from-gregorian
17125 (list m d (+ (nth 2 before) value)))))))
17126 ;; Handle PREFER parameter, if any.
17127 (cond
17128 ((eq prefer 'past) (if (= cday n2) n2 n1))
17129 ((eq prefer 'future) (if (= cday n1) n1 n2))
17130 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17132 (defun org-date-to-gregorian (d)
17133 "Turn any specification of date D into a Gregorian date for the calendar."
17134 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17135 ((and (listp d) (= (length d) 3)) d)
17136 ((stringp d)
17137 (let ((d (org-parse-time-string d)))
17138 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17139 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17141 (defun org-parse-time-string (s &optional nodefault)
17142 "Parse the standard Org time string.
17144 This should be a lot faster than the normal `parse-time-string'.
17146 If time is not given, defaults to 0:00. However, with optional
17147 NODEFAULT, hour and minute fields will be nil if not given."
17148 (cond ((string-match org-ts-regexp0 s)
17149 (list 0
17150 (when (or (match-beginning 8) (not nodefault))
17151 (string-to-number (or (match-string 8 s) "0")))
17152 (when (or (match-beginning 7) (not nodefault))
17153 (string-to-number (or (match-string 7 s) "0")))
17154 (string-to-number (match-string 4 s))
17155 (string-to-number (match-string 3 s))
17156 (string-to-number (match-string 2 s))
17157 nil nil nil))
17158 ((string-match "^<[^>]+>$" s)
17159 ;; FIXME: `decode-time' needs to be called with ZONE as its
17160 ;; second argument. However, this requires at least Emacs
17161 ;; 25.1. We can do it when we switch to this version as our
17162 ;; minimal requirement.
17163 (decode-time (seconds-to-time (org-matcher-time s))))
17164 (t (error "Not a standard Org time string: %s" s))))
17166 (defun org-timestamp-up (&optional arg)
17167 "Increase the date item at the cursor by one.
17168 If the cursor is on the year, change the year. If it is on the month,
17169 the day or the time, change that. If the cursor is on the enclosing
17170 bracket, change the timestamp type.
17171 With prefix ARG, change by that many units."
17172 (interactive "p")
17173 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17175 (defun org-timestamp-down (&optional arg)
17176 "Decrease the date item at the cursor by one.
17177 If the cursor is on the year, change the year. If it is on the month,
17178 the day or the time, change that. If the cursor is on the enclosing
17179 bracket, change the timestamp type.
17180 With prefix ARG, change by that many units."
17181 (interactive "p")
17182 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17184 (defun org-timestamp-up-day (&optional arg)
17185 "Increase the date in the time stamp by one day.
17186 With prefix ARG, change that many days."
17187 (interactive "p")
17188 (if (and (not (org-at-timestamp-p 'lax))
17189 (org-at-heading-p))
17190 (org-todo 'up)
17191 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17193 (defun org-timestamp-down-day (&optional arg)
17194 "Decrease the date in the time stamp by one day.
17195 With prefix ARG, change that many days."
17196 (interactive "p")
17197 (if (and (not (org-at-timestamp-p 'lax))
17198 (org-at-heading-p))
17199 (org-todo 'down)
17200 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17202 (defun org-at-timestamp-p (&optional extended)
17203 "Non-nil if point is inside a timestamp.
17205 By default, the function only consider syntactically valid active
17206 timestamps. However, the caller may have a broader definition
17207 for timestamps. As a consequence, optional argument EXTENDED can
17208 be set to the following values
17210 `inactive'
17212 Include also syntactically valid inactive timestamps.
17214 `agenda'
17216 Include timestamps allowed in Agenda, i.e., those in
17217 properties drawers, planning lines and clock lines.
17219 `lax'
17221 Ignore context. The function matches any part of the
17222 document looking like a timestamp. This includes comments,
17223 example blocks...
17225 For backward-compatibility with Org 9.0, every other non-nil
17226 value is equivalent to `inactive'.
17228 When at a timestamp, return the position of the point as a symbol
17229 among `bracket', `after', `year', `month', `hour', `minute',
17230 `day' or a number of character from the last know part of the
17231 time stamp.
17233 When matching, the match groups are the following:
17234 group 1: year
17235 group 2: month
17236 group 3: day number
17237 group 4: day name
17238 group 5: hours, if any
17239 group 6: minutes, if any"
17240 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17241 (pos (point))
17242 (match?
17243 (let ((boundaries (org-in-regexp regexp)))
17244 (save-match-data
17245 (cond ((null boundaries) nil)
17246 ((eq extended 'lax) t)
17248 (or (and (eq extended 'agenda)
17249 (or (org-at-planning-p)
17250 (org-at-property-p)
17251 (and (bound-and-true-p
17252 org-agenda-include-inactive-timestamps)
17253 (org-at-clock-log-p))))
17254 (eq 'timestamp
17255 (save-excursion
17256 (when (= pos (cdr boundaries)) (forward-char -1))
17257 (org-element-type (org-element-context)))))))))))
17258 (cond
17259 ((not match?) nil)
17260 ((= pos (match-beginning 0)) 'bracket)
17261 ;; Distinguish location right before the closing bracket from
17262 ;; right after it.
17263 ((= pos (1- (match-end 0))) 'bracket)
17264 ((= pos (match-end 0)) 'after)
17265 ((org-pos-in-match-range pos 2) 'year)
17266 ((org-pos-in-match-range pos 3) 'month)
17267 ((org-pos-in-match-range pos 7) 'hour)
17268 ((org-pos-in-match-range pos 8) 'minute)
17269 ((or (org-pos-in-match-range pos 4)
17270 (org-pos-in-match-range pos 5)) 'day)
17271 ((and (> pos (or (match-end 8) (match-end 5)))
17272 (< pos (match-end 0)))
17273 (- pos (or (match-end 8) (match-end 5))))
17274 (t 'day))))
17276 (defun org-toggle-timestamp-type ()
17277 "Toggle the type (<active> or [inactive]) of a time stamp."
17278 (interactive)
17279 (when (org-at-timestamp-p 'lax)
17280 (let ((beg (match-beginning 0)) (end (match-end 0))
17281 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17282 (save-excursion
17283 (goto-char beg)
17284 (while (re-search-forward "[][<>]" end t)
17285 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17286 t t)))
17287 (message "Timestamp is now %sactive"
17288 (if (equal (char-after beg) ?<) "" "in")))))
17290 (defun org-at-clock-log-p ()
17291 "Non-nil if point is on a clock log line."
17292 (and (org-match-line org-clock-line-re)
17293 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17295 (defvar org-clock-history) ; defined in org-clock.el
17296 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17297 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17298 "Change the date in the time stamp at point.
17299 The date will be changed by N times WHAT. WHAT can be `day', `month',
17300 `year', `minute', `second'. If WHAT is not given, the cursor position
17301 in the timestamp determines what will be changed.
17302 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17303 (let ((origin (point))
17304 (timestamp? (org-at-timestamp-p 'lax))
17305 origin-cat
17306 with-hm inactive
17307 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17308 extra rem
17309 ts time time0 fixnext clrgx)
17310 (unless timestamp? (user-error "Not at a timestamp"))
17311 (if (and (not what) (eq timestamp? 'bracket))
17312 (org-toggle-timestamp-type)
17313 ;; Point isn't on brackets. Remember the part of the time-stamp
17314 ;; the point was in. Indeed, size of time-stamps may change,
17315 ;; but point must be kept in the same category nonetheless.
17316 (setq origin-cat timestamp?)
17317 (when (and (not what) (not (eq timestamp? 'day))
17318 org-display-custom-times
17319 (get-text-property (point) 'display)
17320 (not (get-text-property (1- (point)) 'display)))
17321 (setq timestamp? 'day))
17322 (setq timestamp? (or what timestamp?)
17323 inactive (= (char-after (match-beginning 0)) ?\[)
17324 ts (match-string 0))
17325 (replace-match "")
17326 (when (string-match
17327 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17329 (setq extra (match-string 1 ts))
17330 (when suppress-tmp-delay
17331 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17332 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17333 (setq with-hm t))
17334 (setq time0 (org-parse-time-string ts))
17335 (when (and updown
17336 (eq timestamp? 'minute)
17337 (not current-prefix-arg))
17338 ;; This looks like s-up and s-down. Change by one rounding step.
17339 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17340 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17341 (setcar (cdr time0) (+ (nth 1 time0)
17342 (if (> n 0) (- rem) (- dm rem))))))
17343 (setq time
17344 (apply #'encode-time
17345 (or (car time0) 0)
17346 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17347 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17348 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17349 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17350 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17351 (nthcdr 6 time0)))
17352 (when (and (memq timestamp? '(hour minute))
17353 extra
17354 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17355 (setq extra (org-modify-ts-extra
17356 extra
17357 (if (eq timestamp? 'hour) 2 5)
17358 n dm)))
17359 (when (integerp timestamp?)
17360 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17361 (when (eq what 'calendar)
17362 (let ((cal-date (org-get-date-from-calendar)))
17363 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17364 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17365 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17366 (setcar time0 (or (car time0) 0))
17367 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17368 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17369 (setq time (apply 'encode-time time0))))
17370 ;; Insert the new time-stamp, and ensure point stays in the same
17371 ;; category as before (i.e. not after the last position in that
17372 ;; category).
17373 (let ((pos (point)))
17374 ;; Stay before inserted string. `save-excursion' is of no use.
17375 (setq org-last-changed-timestamp
17376 (org-insert-time-stamp time with-hm inactive nil nil extra))
17377 (goto-char pos))
17378 (save-match-data
17379 (looking-at org-ts-regexp3)
17380 (goto-char
17381 (pcase origin-cat
17382 ;; `day' category ends before `hour' if any, or at the end
17383 ;; of the day name.
17384 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17385 (`hour (min (match-end 7) origin))
17386 (`minute (min (1- (match-end 8)) origin))
17387 ((pred integerp) (min (1- (match-end 0)) origin))
17388 ;; Point was right after the time-stamp. However, the
17389 ;; time-stamp length might have changed, so refer to
17390 ;; (match-end 0) instead.
17391 (`after (match-end 0))
17392 ;; `year' and `month' have both fixed size: point couldn't
17393 ;; have moved into another part.
17394 (_ origin))))
17395 ;; Update clock if on a CLOCK line.
17396 (org-clock-update-time-maybe)
17397 ;; Maybe adjust the closest clock in `org-clock-history'
17398 (when org-clock-adjust-closest
17399 (if (not (and (org-at-clock-log-p)
17400 (< 1 (length (delq nil (mapcar 'marker-position
17401 org-clock-history))))))
17402 (message "No clock to adjust")
17403 (cond ((save-excursion ; fix previous clock?
17404 (re-search-backward org-ts-regexp0 nil t)
17405 (looking-back (concat org-clock-string " \\[")
17406 (line-beginning-position)))
17407 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17408 ((save-excursion ; fix next clock?
17409 (re-search-backward org-ts-regexp0 nil t)
17410 (looking-at (concat org-ts-regexp0 "\\] =>")))
17411 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17412 (save-window-excursion
17413 ;; Find closest clock to point, adjust the previous/next one in history
17414 (let* ((p (save-excursion (org-back-to-heading t)))
17415 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17416 (clfixnth
17417 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17418 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17419 (if (not clfixpos)
17420 (message "No clock to adjust")
17421 (save-excursion
17422 (org-goto-marker-or-bmk clfixpos)
17423 (org-show-subtree)
17424 (when (re-search-forward clrgx nil t)
17425 (goto-char (match-beginning 1))
17426 (let (org-clock-adjust-closest)
17427 (org-timestamp-change n timestamp? updown))
17428 (message "Clock adjusted in %s for heading: %s"
17429 (file-name-nondirectory (buffer-file-name))
17430 (org-get-heading t t)))))))))
17431 ;; Try to recenter the calendar window, if any.
17432 (when (and org-calendar-follow-timestamp-change
17433 (get-buffer-window "*Calendar*" t)
17434 (memq timestamp? '(day month year)))
17435 (org-recenter-calendar (time-to-days time))))))
17437 (defun org-modify-ts-extra (s pos n dm)
17438 "Change the different parts of the lead-time and repeat fields in timestamp."
17439 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17440 ng h m new rem)
17441 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17442 (cond
17443 ((or (org-pos-in-match-range pos 2)
17444 (org-pos-in-match-range pos 3))
17445 (setq m (string-to-number (match-string 3 s))
17446 h (string-to-number (match-string 2 s)))
17447 (if (org-pos-in-match-range pos 2)
17448 (setq h (+ h n))
17449 (setq n (* dm (with-no-warnings (signum n))))
17450 (unless (= 0 (setq rem (% m dm)))
17451 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17452 (setq m (+ m n)))
17453 (when (< m 0) (setq m (+ m 60) h (1- h)))
17454 (when (> m 59) (setq m (- m 60) h (1+ h)))
17455 (setq h (mod h 24))
17456 (setq ng 1 new (format "-%02d:%02d" h m)))
17457 ((org-pos-in-match-range pos 6)
17458 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17459 ((org-pos-in-match-range pos 5)
17460 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17462 ((org-pos-in-match-range pos 9)
17463 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17464 ((org-pos-in-match-range pos 8)
17465 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17467 (when ng
17468 (setq s (concat
17469 (substring s 0 (match-beginning ng))
17471 (substring s (match-end ng))))))
17474 (defun org-recenter-calendar (d)
17475 "If the calendar is visible, recenter it to date D."
17476 (let ((cwin (get-buffer-window "*Calendar*" t)))
17477 (when cwin
17478 (let ((calendar-move-hook nil))
17479 (with-selected-window cwin
17480 (calendar-goto-date
17481 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17483 (defun org-goto-calendar (&optional arg)
17484 "Go to the Emacs calendar at the current date.
17485 If there is a time stamp in the current line, go to that date.
17486 A prefix ARG can be used to force the current date."
17487 (interactive "P")
17488 (let ((calendar-move-hook nil)
17489 (calendar-view-holidays-initially-flag nil)
17490 (calendar-view-diary-initially-flag nil)
17491 diff)
17492 (when (or (org-at-timestamp-p 'lax)
17493 (org-match-line (concat ".*" org-ts-regexp)))
17494 (let ((d1 (time-to-days (current-time)))
17495 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17496 (setq diff (- d2 d1))))
17497 (calendar)
17498 (calendar-goto-today)
17499 (when (and diff (not arg)) (calendar-forward-day diff))))
17501 (defun org-get-date-from-calendar ()
17502 "Return a list (month day year) of date at point in calendar."
17503 (with-current-buffer "*Calendar*"
17504 (save-match-data
17505 (calendar-cursor-to-date))))
17507 (defun org-date-from-calendar ()
17508 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17509 If there is already a time stamp at the cursor position, update it."
17510 (interactive)
17511 (if (org-at-timestamp-p 'lax)
17512 (org-timestamp-change 0 'calendar)
17513 (let ((cal-date (org-get-date-from-calendar)))
17514 (org-insert-time-stamp
17515 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17517 (defcustom org-effort-durations
17518 `(("min" . 1)
17519 ("h" . 60)
17520 ("d" . ,(* 60 8))
17521 ("w" . ,(* 60 8 5))
17522 ("m" . ,(* 60 8 5 4))
17523 ("y" . ,(* 60 8 5 40)))
17524 "Conversion factor to minutes for an effort modifier.
17526 Each entry has the form (MODIFIER . MINUTES).
17528 In an effort string, a number followed by MODIFIER is multiplied
17529 by the specified number of MINUTES to obtain an effort in
17530 minutes.
17532 For example, if the value of this variable is ((\"hours\" . 60)), then an
17533 effort string \"2hours\" is equivalent to 120 minutes."
17534 :group 'org-agenda
17535 :version "26.1"
17536 :package-version '(Org . "8.3")
17537 :type '(alist :key-type (string :tag "Modifier")
17538 :value-type (number :tag "Minutes")))
17540 (defcustom org-image-actual-width t
17541 "Should we use the actual width of images when inlining them?
17543 When set to t, always use the image width.
17545 When set to a number, use imagemagick (when available) to set
17546 the image's width to this value.
17548 When set to a number in a list, try to get the width from any
17549 #+ATTR.* keyword if it matches a width specification like
17551 #+ATTR_HTML: :width 300px
17553 and fall back on that number if none is found.
17555 When set to nil, try to get the width from an #+ATTR.* keyword
17556 and fall back on the original width if none is found.
17558 This requires Emacs >= 24.1, build with imagemagick support."
17559 :group 'org-appearance
17560 :version "24.4"
17561 :package-version '(Org . "8.0")
17562 :type '(choice
17563 (const :tag "Use the image width" t)
17564 (integer :tag "Use a number of pixels")
17565 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17566 (const :tag "Use #+ATTR* or don't resize" nil)))
17568 (defcustom org-agenda-inhibit-startup nil
17569 "Inhibit startup when preparing agenda buffers.
17570 When this variable is t, the initialization of the Org agenda
17571 buffers is inhibited: e.g. the visibility state is not set, the
17572 tables are not re-aligned, etc."
17573 :type 'boolean
17574 :version "24.3"
17575 :group 'org-agenda)
17577 (defcustom org-agenda-ignore-properties nil
17578 "Avoid updating text properties when building the agenda.
17579 Properties are used to prepare buffers for effort estimates,
17580 appointments, statistics and subtree-local categories.
17581 If you don't use these in the agenda, you can add them to this
17582 list and agenda building will be a bit faster.
17583 The value is a list, with zero or more of the symbols `effort', `appt',
17584 `stats' or `category'."
17585 :type '(set :greedy t
17586 (const effort)
17587 (const appt)
17588 (const stats)
17589 (const category))
17590 :version "26.1"
17591 :package-version '(Org . "8.3")
17592 :group 'org-agenda)
17594 ;;;; Files
17596 (defun org-save-all-org-buffers ()
17597 "Save all Org buffers without user confirmation."
17598 (interactive)
17599 (message "Saving all Org buffers...")
17600 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17601 (when (featurep 'org-id) (org-id-locations-save))
17602 (message "Saving all Org buffers... done"))
17604 (defun org-revert-all-org-buffers ()
17605 "Revert all Org buffers.
17606 Prompt for confirmation when there are unsaved changes.
17607 Be sure you know what you are doing before letting this function
17608 overwrite your changes.
17610 This function is useful in a setup where one tracks Org files
17611 with a version control system, to revert on one machine after pulling
17612 changes from another. I believe the procedure must be like this:
17614 1. M-x org-save-all-org-buffers
17615 2. Pull changes from the other machine, resolve conflicts
17616 3. M-x org-revert-all-org-buffers"
17617 (interactive)
17618 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17619 (user-error "Abort"))
17620 (save-excursion
17621 (save-window-excursion
17622 (dolist (b (buffer-list))
17623 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17624 (with-current-buffer b buffer-file-name))
17625 (pop-to-buffer-same-window b)
17626 (revert-buffer t 'no-confirm)))
17627 (when (and (featurep 'org-id) org-id-track-globally)
17628 (org-id-locations-load)))))
17630 ;;;; Agenda files
17632 ;;;###autoload
17633 (defun org-switchb (&optional arg)
17634 "Switch between Org buffers.
17636 With `\\[universal-argument]' prefix, restrict available buffers to files.
17638 With `\\[universal-argument] \\[universal-argument]' \
17639 prefix, restrict available buffers to agenda files."
17640 (interactive "P")
17641 (let ((blist (org-buffer-list
17642 (cond ((equal arg '(4)) 'files)
17643 ((equal arg '(16)) 'agenda)))))
17644 (pop-to-buffer-same-window
17645 (completing-read "Org buffer: "
17646 (mapcar #'list (mapcar #'buffer-name blist))
17647 nil t))))
17649 (defun org-buffer-list (&optional predicate exclude-tmp)
17650 "Return a list of Org buffers.
17651 PREDICATE can be `export', `files' or `agenda'.
17653 export restrict the list to Export buffers.
17654 files restrict the list to buffers visiting Org files.
17655 agenda restrict the list to buffers visiting agenda files.
17657 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17658 (let* ((bfn nil)
17659 (agenda-files (and (eq predicate 'agenda)
17660 (mapcar 'file-truename (org-agenda-files t))))
17661 (filter
17662 (cond
17663 ((eq predicate 'files)
17664 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17665 ((eq predicate 'export)
17666 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17667 ((eq predicate 'agenda)
17668 (lambda (b)
17669 (with-current-buffer b
17670 (and (derived-mode-p 'org-mode)
17671 (setq bfn (buffer-file-name b))
17672 (member (file-truename bfn) agenda-files)))))
17673 (t (lambda (b) (with-current-buffer b
17674 (or (derived-mode-p 'org-mode)
17675 (string-match "\\*Org .*Export"
17676 (buffer-name b)))))))))
17677 (delq nil
17678 (mapcar
17679 (lambda(b)
17680 (if (and (funcall filter b)
17681 (or (not exclude-tmp)
17682 (not (string-match "tmp" (buffer-name b)))))
17684 nil))
17685 (buffer-list)))))
17687 (defun org-agenda-files (&optional unrestricted archives)
17688 "Get the list of agenda files.
17689 Optional UNRESTRICTED means return the full list even if a restriction
17690 is currently in place.
17691 When ARCHIVES is t, include all archive files that are really being
17692 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17693 `org-agenda-archives-mode' is t."
17694 (let ((files
17695 (cond
17696 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17697 ((stringp org-agenda-files) (org-read-agenda-file-list))
17698 ((listp org-agenda-files) org-agenda-files)
17699 (t (error "Invalid value of `org-agenda-files'")))))
17700 (setq files (apply 'append
17701 (mapcar (lambda (f)
17702 (if (file-directory-p f)
17703 (directory-files
17704 f t org-agenda-file-regexp)
17705 (list f)))
17706 files)))
17707 (when org-agenda-skip-unavailable-files
17708 (setq files (delq nil
17709 (mapcar (function
17710 (lambda (file)
17711 (and (file-readable-p file) file)))
17712 files))))
17713 (when (or (eq archives t)
17714 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17715 (setq files (org-add-archive-files files)))
17716 files))
17718 (defun org-agenda-file-p (&optional file)
17719 "Return non-nil, if FILE is an agenda file.
17720 If FILE is omitted, use the file associated with the current
17721 buffer."
17722 (let ((fname (or file (buffer-file-name))))
17723 (and fname
17724 (member (file-truename fname)
17725 (mapcar #'file-truename (org-agenda-files t))))))
17727 (defun org-edit-agenda-file-list ()
17728 "Edit the list of agenda files.
17729 Depending on setup, this either uses customize to edit the variable
17730 `org-agenda-files', or it visits the file that is holding the list. In the
17731 latter case, the buffer is set up in a way that saving it automatically kills
17732 the buffer and restores the previous window configuration."
17733 (interactive)
17734 (if (stringp org-agenda-files)
17735 (let ((cw (current-window-configuration)))
17736 (find-file org-agenda-files)
17737 (setq-local org-window-configuration cw)
17738 (add-hook 'after-save-hook
17739 (lambda ()
17740 (set-window-configuration
17741 (prog1 org-window-configuration
17742 (kill-buffer (current-buffer))))
17743 (org-install-agenda-files-menu)
17744 (message "New agenda file list installed"))
17745 nil 'local)
17746 (message "%s" (substitute-command-keys
17747 "Edit list and finish with \\[save-buffer]")))
17748 (customize-variable 'org-agenda-files)))
17750 (defun org-store-new-agenda-file-list (list)
17751 "Set new value for the agenda file list and save it correctly."
17752 (if (stringp org-agenda-files)
17753 (let ((fe (org-read-agenda-file-list t)) b u)
17754 (while (setq b (find-buffer-visiting org-agenda-files))
17755 (kill-buffer b))
17756 (with-temp-file org-agenda-files
17757 (insert
17758 (mapconcat
17759 (lambda (f) ;; Keep un-expanded entries.
17760 (if (setq u (assoc f fe))
17761 (cdr u)
17763 list "\n")
17764 "\n")))
17765 (let ((org-mode-hook nil) (org-inhibit-startup t)
17766 (org-insert-mode-line-in-empty-file nil))
17767 (setq org-agenda-files list)
17768 (customize-save-variable 'org-agenda-files org-agenda-files))))
17770 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17771 "Read the list of agenda files from a file.
17772 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17773 filenames, used by `org-store-new-agenda-file-list' to write back
17774 un-expanded file names."
17775 (when (file-directory-p org-agenda-files)
17776 (error "`org-agenda-files' cannot be a single directory"))
17777 (when (stringp org-agenda-files)
17778 (with-temp-buffer
17779 (insert-file-contents org-agenda-files)
17780 (mapcar
17781 (lambda (f)
17782 (let ((e (expand-file-name (substitute-in-file-name f)
17783 org-directory)))
17784 (if pair-with-expansion
17785 (cons e f)
17786 e)))
17787 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17789 ;;;###autoload
17790 (defun org-cycle-agenda-files ()
17791 "Cycle through the files in `org-agenda-files'.
17792 If the current buffer visits an agenda file, find the next one in the list.
17793 If the current buffer does not, find the first agenda file."
17794 (interactive)
17795 (let* ((fs (or (org-agenda-files t)
17796 (user-error "No agenda files")))
17797 (files (copy-sequence fs))
17798 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17799 file)
17800 (when tcf
17801 (while (and (setq file (pop files))
17802 (not (equal (file-truename file) tcf)))))
17803 (find-file (car (or files fs)))
17804 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17806 (defun org-agenda-file-to-front (&optional to-end)
17807 "Move/add the current file to the top of the agenda file list.
17808 If the file is not present in the list, it is added to the front. If it is
17809 present, it is moved there. With optional argument TO-END, add/move to the
17810 end of the list."
17811 (interactive "P")
17812 (let ((org-agenda-skip-unavailable-files nil)
17813 (file-alist (mapcar (lambda (x)
17814 (cons (file-truename x) x))
17815 (org-agenda-files t)))
17816 (ctf (file-truename
17817 (or buffer-file-name
17818 (user-error "Please save the current buffer to a file"))))
17819 x had)
17820 (setq x (assoc ctf file-alist) had x)
17822 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17823 (if to-end
17824 (setq file-alist (append (delq x file-alist) (list x)))
17825 (setq file-alist (cons x (delq x file-alist))))
17826 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17827 (org-install-agenda-files-menu)
17828 (message "File %s to %s of agenda file list"
17829 (if had "moved" "added") (if to-end "end" "front"))))
17831 (defun org-remove-file (&optional file)
17832 "Remove current file from the list of files in variable `org-agenda-files'.
17833 These are the files which are being checked for agenda entries.
17834 Optional argument FILE means use this file instead of the current."
17835 (interactive)
17836 (let* ((org-agenda-skip-unavailable-files nil)
17837 (file (or file buffer-file-name
17838 (user-error "Current buffer does not visit a file")))
17839 (true-file (file-truename file))
17840 (afile (abbreviate-file-name file))
17841 (files (delq nil (mapcar
17842 (lambda (x)
17843 (unless (equal true-file
17844 (file-truename x))
17846 (org-agenda-files t)))))
17847 (if (not (= (length files) (length (org-agenda-files t))))
17848 (progn
17849 (org-store-new-agenda-file-list files)
17850 (org-install-agenda-files-menu)
17851 (message "Removed from Org Agenda list: %s" afile))
17852 (message "File was not in list: %s (not removed)" afile))))
17854 (defun org-file-menu-entry (file)
17855 (vector file (list 'find-file file) t))
17857 (defun org-check-agenda-file (file)
17858 "Make sure FILE exists. If not, ask user what to do."
17859 (unless (file-exists-p file)
17860 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17861 (abbreviate-file-name file))
17862 (let ((r (downcase (read-char-exclusive))))
17863 (cond
17864 ((equal r ?r)
17865 (org-remove-file file)
17866 (throw 'nextfile t))
17867 (t (user-error "Abort"))))))
17869 (defun org-get-agenda-file-buffer (file)
17870 "Get an agenda buffer visiting FILE.
17871 If the buffer needs to be created, add it to the list of buffers
17872 which might be released later."
17873 (let ((buf (org-find-base-buffer-visiting file)))
17874 (if buf
17875 buf ; just return it
17876 ;; Make a new buffer and remember it
17877 (setq buf (find-file-noselect file))
17878 (when buf (push buf org-agenda-new-buffers))
17879 buf)))
17881 (defun org-release-buffers (blist)
17882 "Release all buffers in list, asking the user for confirmation when needed.
17883 When a buffer is unmodified, it is just killed. When modified, it is saved
17884 \(if the user agrees) and then killed."
17885 (let (file)
17886 (dolist (buf blist)
17887 (setq file (buffer-file-name buf))
17888 (when (and (buffer-modified-p buf)
17889 file
17890 (y-or-n-p (format "Save file %s? " file)))
17891 (with-current-buffer buf (save-buffer)))
17892 (kill-buffer buf))))
17894 (defun org-agenda-prepare-buffers (files)
17895 "Create buffers for all agenda files, protect archived trees and comments."
17896 (interactive)
17897 (let ((pa '(:org-archived t))
17898 (pc '(:org-comment t))
17899 (pall '(:org-archived t :org-comment t))
17900 (inhibit-read-only t)
17901 (org-inhibit-startup org-agenda-inhibit-startup)
17902 (rea (org-make-tag-string (list org-archive-tag)))
17903 re pos)
17904 (setq org-tag-alist-for-agenda nil
17905 org-tag-groups-alist-for-agenda nil)
17906 (save-excursion
17907 (save-restriction
17908 (dolist (file files)
17909 (catch 'nextfile
17910 (if (bufferp file)
17911 (set-buffer file)
17912 (org-check-agenda-file file)
17913 (set-buffer (org-get-agenda-file-buffer file)))
17914 (widen)
17915 (org-set-regexps-and-options 'tags-only)
17916 (setq pos (point))
17917 (or (memq 'category org-agenda-ignore-properties)
17918 (org-refresh-category-properties))
17919 (or (memq 'stats org-agenda-ignore-properties)
17920 (org-refresh-stats-properties))
17921 (or (memq 'effort org-agenda-ignore-properties)
17922 (org-refresh-effort-properties))
17923 (or (memq 'appt org-agenda-ignore-properties)
17924 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17925 (setq org-todo-keywords-for-agenda
17926 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17927 (setq org-done-keywords-for-agenda
17928 (append org-done-keywords-for-agenda org-done-keywords))
17929 (setq org-todo-keyword-alist-for-agenda
17930 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17931 (setq org-tag-alist-for-agenda
17932 (org--tag-add-to-alist
17933 org-tag-alist-for-agenda
17934 org-current-tag-alist))
17935 ;; Merge current file's tag groups into global
17936 ;; `org-tag-groups-alist-for-agenda'.
17937 (when org-group-tags
17938 (dolist (alist org-tag-groups-alist)
17939 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17940 (if old
17941 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17942 (push alist org-tag-groups-alist-for-agenda)))))
17943 (org-with-silent-modifications
17944 (save-excursion
17945 (remove-text-properties (point-min) (point-max) pall)
17946 (when org-agenda-skip-archived-trees
17947 (goto-char (point-min))
17948 (while (re-search-forward rea nil t)
17949 (when (org-at-heading-p t)
17950 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17951 (goto-char (point-min))
17952 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17953 (while (re-search-forward re nil t)
17954 (when (save-match-data (org-in-commented-heading-p t))
17955 (add-text-properties
17956 (match-beginning 0) (org-end-of-subtree t) pc)))))
17957 (goto-char pos)))))
17958 (setq org-todo-keywords-for-agenda
17959 (org-uniquify org-todo-keywords-for-agenda))
17960 (setq org-todo-keyword-alist-for-agenda
17961 (org-uniquify org-todo-keyword-alist-for-agenda))))
17964 ;;;; CDLaTeX minor mode
17966 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17967 "Keymap for the minor `org-cdlatex-mode'.")
17969 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17970 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17971 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17972 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17973 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
17975 (defvar org-cdlatex-texmathp-advice-is-done nil
17976 "Flag remembering if we have applied the advice to texmathp already.")
17978 (define-minor-mode org-cdlatex-mode
17979 "Toggle the minor `org-cdlatex-mode'.
17980 This mode supports entering LaTeX environment and math in LaTeX fragments
17981 in Org mode.
17982 \\{org-cdlatex-mode-map}"
17983 nil " OCDL" nil
17984 (when org-cdlatex-mode
17985 (require 'cdlatex)
17986 (run-hooks 'cdlatex-mode-hook)
17987 (cdlatex-compute-tables))
17988 (unless org-cdlatex-texmathp-advice-is-done
17989 (setq org-cdlatex-texmathp-advice-is-done t)
17990 (defadvice texmathp (around org-math-always-on activate)
17991 "Always return t in Org buffers.
17992 This is because we want to insert math symbols without dollars even outside
17993 the LaTeX math segments. If Org mode thinks that point is actually inside
17994 an embedded LaTeX fragment, let `texmathp' do its job.
17995 `\\[org-cdlatex-mode-map]'"
17996 (interactive)
17997 (let (p)
17998 (cond
17999 ((not (derived-mode-p 'org-mode)) ad-do-it)
18000 ((eq this-command 'cdlatex-math-symbol)
18001 (setq ad-return-value t
18002 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18004 (let ((p (org-inside-LaTeX-fragment-p)))
18005 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18006 (setq ad-return-value t
18007 texmathp-why '("Org mode embedded math" . 0))
18008 (when p ad-do-it)))))))))
18010 (defun turn-on-org-cdlatex ()
18011 "Unconditionally turn on `org-cdlatex-mode'."
18012 (org-cdlatex-mode 1))
18014 (defun org-try-cdlatex-tab ()
18015 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18016 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18017 - inside a LaTeX fragment, or
18018 - after the first word in a line, where an abbreviation expansion could
18019 insert a LaTeX environment."
18020 (when org-cdlatex-mode
18021 (cond
18022 ;; Before any word on the line: No expansion possible.
18023 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18024 ;; Just after first word on the line: Expand it. Make sure it
18025 ;; cannot happen on headlines, though.
18026 ((save-excursion
18027 (skip-chars-backward "a-zA-Z0-9*")
18028 (skip-chars-backward " \t")
18029 (and (bolp) (not (org-at-heading-p))))
18030 (cdlatex-tab) t)
18031 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18033 (defun org-cdlatex-underscore-caret (&optional _arg)
18034 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18035 Revert to the normal definition outside of these fragments."
18036 (interactive "P")
18037 (if (org-inside-LaTeX-fragment-p)
18038 (call-interactively 'cdlatex-sub-superscript)
18039 (let (org-cdlatex-mode)
18040 (call-interactively (key-binding (vector last-input-event))))))
18042 (defun org-cdlatex-math-modify (&optional _arg)
18043 "Execute `cdlatex-math-modify' in LaTeX fragments.
18044 Revert to the normal definition outside of these fragments."
18045 (interactive "P")
18046 (if (org-inside-LaTeX-fragment-p)
18047 (call-interactively 'cdlatex-math-modify)
18048 (let (org-cdlatex-mode)
18049 (call-interactively (key-binding (vector last-input-event))))))
18051 (defun org-cdlatex-environment-indent (&optional environment item)
18052 "Execute `cdlatex-environment' and indent the inserted environment.
18054 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18056 The inserted environment is indented to current indentation
18057 unless point is at the beginning of the line, in which the
18058 environment remains unintended."
18059 (interactive)
18060 ;; cdlatex-environment always return nil. Therefore, capture output
18061 ;; first and determine if an environment was selected.
18062 (let* ((beg (point-marker))
18063 (end (copy-marker (point) t))
18064 (inserted (progn
18065 (ignore-errors (cdlatex-environment environment item))
18066 (< beg end)))
18067 ;; Figure out how many lines to move forward after the
18068 ;; environment has been inserted.
18069 (lines (when inserted
18070 (save-excursion
18071 (- (cl-loop while (< beg (point))
18072 with x = 0
18073 do (forward-line -1)
18074 (cl-incf x)
18075 finally return x)
18076 (if (progn (goto-char beg)
18077 (and (progn (skip-chars-forward " \t") (eolp))
18078 (progn (skip-chars-backward " \t") (bolp))))
18079 1 0)))))
18080 (env (org-trim (delete-and-extract-region beg end))))
18081 (when inserted
18082 ;; Get indentation of next line unless at column 0.
18083 (let ((ind (if (bolp) 0
18084 (save-excursion
18085 (org-return-indent)
18086 (prog1 (org-get-indentation)
18087 (when (progn (skip-chars-forward " \t") (eolp))
18088 (delete-region beg (point)))))))
18089 (bol (progn (skip-chars-backward " \t") (bolp))))
18090 ;; Insert a newline before environment unless at column zero
18091 ;; to "escape" the current line. Insert a newline if
18092 ;; something is one the same line as \end{ENVIRONMENT}.
18093 (insert
18094 (concat (unless bol "\n") env
18095 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18096 (unless (zerop ind)
18097 (save-excursion
18098 (goto-char beg)
18099 (while (< (point) end)
18100 (unless (eolp) (indent-line-to ind))
18101 (forward-line))))
18102 (goto-char beg)
18103 (forward-line lines)
18104 (indent-line-to ind)))
18105 (set-marker beg nil)
18106 (set-marker end nil)))
18109 ;;;; LaTeX fragments
18111 (defun org-inside-LaTeX-fragment-p ()
18112 "Test if point is inside a LaTeX fragment.
18113 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18114 sequence appearing also before point.
18115 Even though the matchers for math are configurable, this function assumes
18116 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18117 delimiters are skipped when they have been removed by customization.
18118 The return value is nil, or a cons cell with the delimiter and the
18119 position of this delimiter.
18121 This function does a reasonably good job, but can locally be fooled by
18122 for example currency specifications. For example it will assume being in
18123 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18124 fragments that are properly closed, but during editing, we have to live
18125 with the uncertainty caused by missing closing delimiters. This function
18126 looks only before point, not after."
18127 (catch 'exit
18128 (let ((pos (point))
18129 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18130 (lim (save-excursion (org-backward-paragraph) (point)))
18131 dd-on str (start 0) m re)
18132 (goto-char pos)
18133 (when dodollar
18134 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18135 re (nth 1 (assoc "$" org-latex-regexps)))
18136 (while (string-match re str start)
18137 (cond
18138 ((= (match-end 0) (length str))
18139 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18140 ((= (match-end 0) (- (length str) 5))
18141 (throw 'exit nil))
18142 (t (setq start (match-end 0))))))
18143 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18144 (goto-char pos)
18145 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18146 (and (match-beginning 2) (throw 'exit nil))
18147 ;; count $$
18148 (while (re-search-backward "\\$\\$" lim t)
18149 (setq dd-on (not dd-on)))
18150 (goto-char pos)
18151 (when dd-on (cons "$$" m))))))
18153 (defun org-inside-latex-macro-p ()
18154 "Is point inside a LaTeX macro or its arguments?"
18155 (save-match-data
18156 (org-in-regexp
18157 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18159 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18160 "Build an overlay between BEG and END using IMAGE file.
18161 Argument IMAGETYPE is the extension of the displayed image,
18162 as a string. It defaults to \"png\"."
18163 (let ((ov (make-overlay beg end))
18164 (imagetype (or (intern imagetype) 'png)))
18165 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18166 (overlay-put ov 'evaporate t)
18167 (overlay-put ov
18168 'modification-hooks
18169 (list (lambda (o _flag _beg _end &optional _l)
18170 (delete-overlay o))))
18171 (overlay-put ov
18172 'display
18173 (list 'image :type imagetype :file image :ascent 'center))))
18175 (defun org--list-latex-overlays (&optional beg end)
18176 "List all Org LaTeX overlays in current buffer.
18177 Limit to overlays between BEG and END when those are provided."
18178 (cl-remove-if-not
18179 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18180 (overlays-in (or beg (point-min)) (or end (point-max)))))
18182 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18183 "Remove all overlays with LaTeX fragment images in current buffer.
18184 When optional arguments BEG and END are non-nil, remove all
18185 overlays between them instead. Return a non-nil value when some
18186 overlays were removed, nil otherwise."
18187 (let ((overlays (org--list-latex-overlays beg end)))
18188 (mapc #'delete-overlay overlays)
18189 overlays))
18191 (defun org-toggle-latex-fragment (&optional arg)
18192 "Preview the LaTeX fragment at point, or all locally or globally.
18194 If the cursor is on a LaTeX fragment, create the image and overlay
18195 it over the source code, if there is none. Remove it otherwise.
18196 If there is no fragment at point, display all fragments in the
18197 current section.
18199 With prefix ARG, preview or clear image for all fragments in the
18200 current subtree or in the whole buffer when used before the first
18201 headline. With a prefix ARG `\\[universal-argument] \
18202 \\[universal-argument]' preview or clear images
18203 for all fragments in the buffer."
18204 (interactive "P")
18205 (when (display-graphic-p)
18206 (catch 'exit
18207 (save-excursion
18208 (let (beg end msg)
18209 (cond
18210 ((or (equal arg '(16))
18211 (and (equal arg '(4))
18212 (org-with-limited-levels (org-before-first-heading-p))))
18213 (if (org-remove-latex-fragment-image-overlays)
18214 (progn (message "LaTeX fragments images removed from buffer")
18215 (throw 'exit nil))
18216 (setq msg "Creating images for buffer...")))
18217 ((equal arg '(4))
18218 (org-with-limited-levels (org-back-to-heading t))
18219 (setq beg (point))
18220 (setq end (progn (org-end-of-subtree t) (point)))
18221 (if (org-remove-latex-fragment-image-overlays beg end)
18222 (progn
18223 (message "LaTeX fragment images removed from subtree")
18224 (throw 'exit nil))
18225 (setq msg "Creating images for subtree...")))
18226 ((let ((datum (org-element-context)))
18227 (when (memq (org-element-type datum)
18228 '(latex-environment latex-fragment))
18229 (setq beg (org-element-property :begin datum))
18230 (setq end (org-element-property :end datum))
18231 (if (org-remove-latex-fragment-image-overlays beg end)
18232 (progn (message "LaTeX fragment image removed")
18233 (throw 'exit nil))
18234 (setq msg "Creating image...")))))
18236 (org-with-limited-levels
18237 (setq beg (if (org-at-heading-p) (line-beginning-position)
18238 (outline-previous-heading)
18239 (point)))
18240 (setq end (progn (outline-next-heading) (point)))
18241 (if (org-remove-latex-fragment-image-overlays beg end)
18242 (progn
18243 (message "LaTeX fragment images removed from section")
18244 (throw 'exit nil))
18245 (setq msg "Creating images for section...")))))
18246 (let ((file (buffer-file-name (buffer-base-buffer))))
18247 (org-format-latex
18248 (concat org-preview-latex-image-directory "org-ltximg")
18249 beg end
18250 ;; Emacs cannot overlay images from remote hosts. Create
18251 ;; it in `temporary-file-directory' instead.
18252 (if (or (not file) (file-remote-p file))
18253 temporary-file-directory
18254 default-directory)
18255 'overlays msg 'forbuffer org-preview-latex-default-process))
18256 (message (concat msg "done")))))))
18258 (defun org-format-latex
18259 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18260 "Replace LaTeX fragments with links to an image.
18262 The function takes care of creating the replacement image.
18264 Only consider fragments between BEG and END when those are
18265 provided.
18267 When optional argument OVERLAYS is non-nil, display the image on
18268 top of the fragment instead of replacing it.
18270 PROCESSING-TYPE is the conversion method to use, as a symbol.
18272 Some of the options can be changed using the variable
18273 `org-format-latex-options', which see."
18274 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18275 (unless (eq processing-type 'verbatim)
18276 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18277 (cnt 0)
18278 checkdir-flag)
18279 (goto-char (or beg (point-min)))
18280 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18281 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18282 (overlay-recenter (or end (point-max))))
18283 (while (re-search-forward math-regexp end t)
18284 (unless (and overlays
18285 (eq (get-char-property (point) 'org-overlay-type)
18286 'org-latex-overlay))
18287 (let* ((context (org-element-context))
18288 (type (org-element-type context)))
18289 (when (memq type '(latex-environment latex-fragment))
18290 (let ((block-type (eq type 'latex-environment))
18291 (value (org-element-property :value context))
18292 (beg (org-element-property :begin context))
18293 (end (save-excursion
18294 (goto-char (org-element-property :end context))
18295 (skip-chars-backward " \r\t\n")
18296 (point))))
18297 (cond
18298 ((eq processing-type 'mathjax)
18299 ;; Prepare for MathJax processing.
18300 (if (not (string-match "\\`\\$\\$?" value))
18301 (goto-char end)
18302 (delete-region beg end)
18303 (if (string= (match-string 0 value) "$$")
18304 (insert "\\[" (substring value 2 -2) "\\]")
18305 (insert "\\(" (substring value 1 -1) "\\)"))))
18306 ((assq processing-type org-preview-latex-process-alist)
18307 ;; Process to an image.
18308 (cl-incf cnt)
18309 (goto-char beg)
18310 (let* ((processing-info
18311 (cdr (assq processing-type org-preview-latex-process-alist)))
18312 (face (face-at-point))
18313 ;; Get the colors from the face at point.
18315 (let ((color (plist-get org-format-latex-options
18316 :foreground)))
18317 (if (and forbuffer (eq color 'auto))
18318 (face-attribute face :foreground nil 'default)
18319 color)))
18321 (let ((color (plist-get org-format-latex-options
18322 :background)))
18323 (if (and forbuffer (eq color 'auto))
18324 (face-attribute face :background nil 'default)
18325 color)))
18326 (hash (sha1 (prin1-to-string
18327 (list org-format-latex-header
18328 org-latex-default-packages-alist
18329 org-latex-packages-alist
18330 org-format-latex-options
18331 forbuffer value fg bg))))
18332 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18333 (absprefix (expand-file-name prefix dir))
18334 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18335 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18336 (sep (and block-type "\n\n"))
18337 (link (concat sep "[[file:" linkfile "]]" sep))
18338 (options
18339 (org-combine-plists
18340 org-format-latex-options
18341 `(:foreground ,fg :background ,bg))))
18342 (when msg (message msg cnt))
18343 (unless checkdir-flag ; Ensure the directory exists.
18344 (setq checkdir-flag t)
18345 (let ((todir (file-name-directory absprefix)))
18346 (unless (file-directory-p todir)
18347 (make-directory todir t))))
18348 (unless (file-exists-p movefile)
18349 (org-create-formula-image
18350 value movefile options forbuffer processing-type))
18351 (if overlays
18352 (progn
18353 (dolist (o (overlays-in beg end))
18354 (when (eq (overlay-get o 'org-overlay-type)
18355 'org-latex-overlay)
18356 (delete-overlay o)))
18357 (org--format-latex-make-overlay beg end movefile imagetype)
18358 (goto-char end))
18359 (delete-region beg end)
18360 (insert
18361 (org-add-props link
18362 (list 'org-latex-src
18363 (replace-regexp-in-string "\"" "" value)
18364 'org-latex-src-embed-type
18365 (if block-type 'paragraph 'character)))))))
18366 ((eq processing-type 'mathml)
18367 ;; Process to MathML.
18368 (unless (org-format-latex-mathml-available-p)
18369 (user-error "LaTeX to MathML converter not configured"))
18370 (cl-incf cnt)
18371 (when msg (message msg cnt))
18372 (goto-char beg)
18373 (delete-region beg end)
18374 (insert (org-format-latex-as-mathml
18375 value block-type prefix dir)))
18377 (error "Unknown conversion process %s for LaTeX fragments"
18378 processing-type)))))))))))
18380 (defun org-create-math-formula (latex-frag &optional mathml-file)
18381 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18382 Use `org-latex-to-mathml-convert-command'. If the conversion is
18383 sucessful, return the portion between \"<math...> </math>\"
18384 elements otherwise return nil. When MATHML-FILE is specified,
18385 write the results in to that file. When invoked as an
18386 interactive command, prompt for LATEX-FRAG, with initial value
18387 set to the current active region and echo the results for user
18388 inspection."
18389 (interactive (list (let ((frag (when (org-region-active-p)
18390 (buffer-substring-no-properties
18391 (region-beginning) (region-end)))))
18392 (read-string "LaTeX Fragment: " frag nil frag))))
18393 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18394 (let* ((tmp-in-file
18395 (let ((file (file-relative-name
18396 (make-temp-name (expand-file-name "ltxmathml-in")))))
18397 (write-region latex-frag nil file)
18398 file))
18399 (tmp-out-file (file-relative-name
18400 (make-temp-name (expand-file-name "ltxmathml-out"))))
18401 (cmd (format-spec
18402 org-latex-to-mathml-convert-command
18403 `((?j . ,(and org-latex-to-mathml-jar-file
18404 (shell-quote-argument
18405 (expand-file-name
18406 org-latex-to-mathml-jar-file))))
18407 (?I . ,(shell-quote-argument tmp-in-file))
18408 (?i . ,latex-frag)
18409 (?o . ,(shell-quote-argument tmp-out-file)))))
18410 mathml shell-command-output)
18411 (when (called-interactively-p 'any)
18412 (unless (org-format-latex-mathml-available-p)
18413 (user-error "LaTeX to MathML converter not configured")))
18414 (message "Running %s" cmd)
18415 (setq shell-command-output (shell-command-to-string cmd))
18416 (setq mathml
18417 (when (file-readable-p tmp-out-file)
18418 (with-current-buffer (find-file-noselect tmp-out-file t)
18419 (goto-char (point-min))
18420 (when (re-search-forward
18421 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18422 (regexp-quote
18423 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18424 nil t)
18425 (prog1 (match-string 0) (kill-buffer))))))
18426 (cond
18427 (mathml
18428 (setq mathml
18429 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18430 (when mathml-file
18431 (write-region mathml nil mathml-file))
18432 (when (called-interactively-p 'any)
18433 (message mathml)))
18434 ((message "LaTeX to MathML conversion failed")
18435 (message shell-command-output)))
18436 (delete-file tmp-in-file)
18437 (when (file-exists-p tmp-out-file)
18438 (delete-file tmp-out-file))
18439 mathml))
18441 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18442 prefix &optional dir)
18443 "Use `org-create-math-formula' but check local cache first."
18444 (let* ((absprefix (expand-file-name prefix dir))
18445 (print-length nil) (print-level nil)
18446 (formula-id (concat
18447 "formula-"
18448 (sha1
18449 (prin1-to-string
18450 (list latex-frag
18451 org-latex-to-mathml-convert-command)))))
18452 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18453 (formula-cache-dir (file-name-directory formula-cache)))
18455 (unless (file-directory-p formula-cache-dir)
18456 (make-directory formula-cache-dir t))
18458 (unless (file-exists-p formula-cache)
18459 (org-create-math-formula latex-frag formula-cache))
18461 (if (file-exists-p formula-cache)
18462 ;; Successful conversion. Return the link to MathML file.
18463 (org-add-props
18464 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18465 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18466 'org-latex-src-embed-type (if latex-frag-type
18467 'paragraph 'character)))
18468 ;; Failed conversion. Return the LaTeX fragment verbatim
18469 latex-frag)))
18471 (defun org--get-display-dpi ()
18472 "Get the DPI of the display.
18473 The function assumes that the display has the same pixel width in
18474 the horizontal and vertical directions."
18475 (if (display-graphic-p)
18476 (round (/ (display-pixel-height)
18477 (/ (display-mm-height) 25.4)))
18478 (error "Attempt to calculate the dpi of a non-graphic display")))
18480 (defun org-create-formula-image
18481 (string tofile options buffer &optional processing-type)
18482 "Create an image from LaTeX source using external processes.
18484 The LaTeX STRING is saved to a temporary LaTeX file, then
18485 converted to an image file by process PROCESSING-TYPE defined in
18486 `org-preview-latex-process-alist'. A nil value defaults to
18487 `org-preview-latex-default-process'.
18489 The generated image file is eventually moved to TOFILE.
18491 The OPTIONS argument controls the size, foreground color and
18492 background color of the generated image.
18494 When BUFFER non-nil, this function is used for LaTeX previewing.
18495 Otherwise, it is used to deal with LaTeX snippets showed in
18496 a HTML file."
18497 (let* ((processing-type (or processing-type
18498 org-preview-latex-default-process))
18499 (processing-info
18500 (cdr (assq processing-type org-preview-latex-process-alist)))
18501 (programs (plist-get processing-info :programs))
18502 (error-message (or (plist-get processing-info :message) ""))
18503 (use-xcolor (plist-get processing-info :use-xcolor))
18504 (image-input-type (plist-get processing-info :image-input-type))
18505 (image-output-type (plist-get processing-info :image-output-type))
18506 (post-clean (or (plist-get processing-info :post-clean)
18507 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18508 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18509 (latex-header
18510 (or (plist-get processing-info :latex-header)
18511 (org-latex-make-preamble
18512 (org-export-get-environment (org-export-get-backend 'latex))
18513 org-format-latex-header
18514 'snippet)))
18515 (latex-compiler (plist-get processing-info :latex-compiler))
18516 (image-converter (plist-get processing-info :image-converter))
18517 (tmpdir temporary-file-directory)
18518 (texfilebase (make-temp-name
18519 (expand-file-name "orgtex" tmpdir)))
18520 (texfile (concat texfilebase ".tex"))
18521 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18522 '(1.0 . 1.0)))
18523 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18524 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18525 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18526 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18527 "Black"))
18528 (bg (or (plist-get options (if buffer :background :html-background))
18529 "Transparent"))
18530 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18531 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18532 (dolist (program programs)
18533 (org-check-external-command program error-message))
18534 (if use-xcolor
18535 (progn (if (eq fg 'default)
18536 (setq fg (org-latex-color :foreground))
18537 (setq fg (org-latex-color-format fg)))
18538 (if (eq bg 'default)
18539 (setq bg (org-latex-color :background))
18540 (setq bg (org-latex-color-format
18541 (if (string= bg "Transparent") "white" bg))))
18542 (with-temp-file texfile
18543 (insert latex-header)
18544 (insert "\n\\begin{document}\n"
18545 "\\definecolor{fg}{rgb}{" fg "}\n"
18546 "\\definecolor{bg}{rgb}{" bg "}\n"
18547 "\n\\pagecolor{bg}\n"
18548 "\n{\\color{fg}\n"
18549 string
18550 "\n}\n"
18551 "\n\\end{document}\n")))
18552 (if (eq fg 'default)
18553 (setq fg (org-dvipng-color :foreground))
18554 (unless (string= fg "Transparent")
18555 (setq fg (org-dvipng-color-format fg))))
18556 (if (eq bg 'default)
18557 (setq bg (org-dvipng-color :background))
18558 (unless (string= bg "Transparent")
18559 (setq bg (org-dvipng-color-format bg))))
18560 (with-temp-file texfile
18561 (insert latex-header)
18562 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18564 (let* ((err-msg (format "Please adjust `%s' part of \
18565 `org-preview-latex-process-alist'."
18566 processing-type))
18567 (image-input-file
18568 (org-compile-file
18569 texfile latex-compiler image-input-type err-msg log-buf))
18570 (image-output-file
18571 (org-compile-file
18572 image-input-file image-converter image-output-type err-msg log-buf
18573 `((?F . ,(shell-quote-argument fg))
18574 (?B . ,(shell-quote-argument bg))
18575 (?D . ,(shell-quote-argument (format "%s" dpi)))
18576 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18577 (copy-file image-output-file tofile 'replace)
18578 (dolist (e post-clean)
18579 (when (file-exists-p (concat texfilebase e))
18580 (delete-file (concat texfilebase e))))
18581 image-output-file)))
18583 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18584 "Fill a LaTeX header template TPL.
18585 In the template, the following place holders will be recognized:
18587 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18588 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18589 [PACKAGES] \\usepackage statements for PKG
18590 [NO-PACKAGES] do not include PKG
18591 [EXTRA] the string EXTRA
18592 [NO-EXTRA] do not include EXTRA
18594 For backward compatibility, if both the positive and the negative place
18595 holder is missing, the positive one (without the \"NO-\") will be
18596 assumed to be present at the end of the template.
18597 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18598 EXTRA is a string.
18599 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18600 (let (rpl (end ""))
18601 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18602 (setq rpl (if (or (match-end 1) (not def-pkg))
18603 "" (org-latex-packages-to-string def-pkg snippets-p t))
18604 tpl (replace-match rpl t t tpl))
18605 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18607 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18608 (setq rpl (if (or (match-end 1) (not pkg))
18609 "" (org-latex-packages-to-string pkg snippets-p t))
18610 tpl (replace-match rpl t t tpl))
18611 (when pkg (setq end
18612 (concat end "\n"
18613 (org-latex-packages-to-string pkg snippets-p)))))
18615 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18616 (setq rpl (if (or (match-end 1) (not extra))
18617 "" (concat extra "\n"))
18618 tpl (replace-match rpl t t tpl))
18619 (when (and extra (string-match "\\S-" extra))
18620 (setq end (concat end "\n" extra))))
18622 (if (string-match "\\S-" end)
18623 (concat tpl "\n" end)
18624 tpl)))
18626 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18627 "Turn an alist of packages into a string with the \\usepackage macros."
18628 (setq pkg (mapconcat (lambda(p)
18629 (cond
18630 ((stringp p) p)
18631 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18632 (format "%% Package %s omitted" (cadr p)))
18633 ((equal "" (car p))
18634 (format "\\usepackage{%s}" (cadr p)))
18636 (format "\\usepackage[%s]{%s}"
18637 (car p) (cadr p)))))
18639 "\n"))
18640 (if newline (concat pkg "\n") pkg))
18642 (defun org-dvipng-color (attr)
18643 "Return a RGB color specification for dvipng."
18644 (org-dvipng-color-format (face-attribute 'default attr nil)))
18646 (defun org-dvipng-color-format (color-name)
18647 "Convert COLOR-NAME to a RGB color value for dvipng."
18648 (apply #'format "rgb %s %s %s"
18649 (mapcar 'org-normalize-color
18650 (color-values color-name))))
18652 (defun org-latex-color (attr)
18653 "Return a RGB color for the LaTeX color package."
18654 (org-latex-color-format (face-attribute 'default attr nil)))
18656 (defun org-latex-color-format (color-name)
18657 "Convert COLOR-NAME to a RGB color value."
18658 (apply #'format "%s,%s,%s"
18659 (mapcar 'org-normalize-color
18660 (color-values color-name))))
18662 (defun org-normalize-color (value)
18663 "Return string to be used as color value for an RGB component."
18664 (format "%g" (/ value 65535.0)))
18667 ;; Image display
18669 (defvar-local org-inline-image-overlays nil)
18671 (defun org-toggle-inline-images (&optional include-linked)
18672 "Toggle the display of inline images.
18673 INCLUDE-LINKED is passed to `org-display-inline-images'."
18674 (interactive "P")
18675 (if org-inline-image-overlays
18676 (progn
18677 (org-remove-inline-images)
18678 (when (called-interactively-p 'interactive)
18679 (message "Inline image display turned off")))
18680 (org-display-inline-images include-linked)
18681 (when (called-interactively-p 'interactive)
18682 (message (if org-inline-image-overlays
18683 (format "%d images displayed inline"
18684 (length org-inline-image-overlays))
18685 "No images to display inline")))))
18687 (defun org-redisplay-inline-images ()
18688 "Refresh the display of inline images."
18689 (interactive)
18690 (if (not org-inline-image-overlays)
18691 (org-toggle-inline-images)
18692 (org-toggle-inline-images)
18693 (org-toggle-inline-images)))
18695 (defun org-display-inline-images (&optional include-linked refresh beg end)
18696 "Display inline images.
18698 An inline image is a link which follows either of these
18699 conventions:
18701 1. Its path is a file with an extension matching return value
18702 from `image-file-name-regexp' and it has no contents.
18704 2. Its description consists in a single link of the previous
18705 type.
18707 When optional argument INCLUDE-LINKED is non-nil, also links with
18708 a text description part will be inlined. This can be nice for
18709 a quick look at those images, but it does not reflect what
18710 exported files will look like.
18712 When optional argument REFRESH is non-nil, refresh existing
18713 images between BEG and END. This will create new image displays
18714 only if necessary. BEG and END default to the buffer
18715 boundaries."
18716 (interactive "P")
18717 (when (display-graphic-p)
18718 (unless refresh
18719 (org-remove-inline-images)
18720 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18721 (org-with-wide-buffer
18722 (goto-char (or beg (point-min)))
18723 (let* ((case-fold-search t)
18724 (file-extension-re (image-file-name-regexp))
18725 (link-abbrevs (mapcar #'car
18726 (append org-link-abbrev-alist-local
18727 org-link-abbrev-alist)))
18728 ;; Check absolute, relative file names and explicit
18729 ;; "file:" links. Also check link abbreviations since
18730 ;; some might expand to "file" links.
18731 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18732 (if (not link-abbrevs) ""
18733 (format "\\|\\(?:%s:\\)"
18734 (regexp-opt link-abbrevs))))))
18735 (while (re-search-forward file-types-re end t)
18736 (let ((link (save-match-data (org-element-context))))
18737 ;; Check if we're at an inline image, i.e., an image file
18738 ;; link without a description (unless INCLUDE-LINKED is
18739 ;; non-nil).
18740 (when (and (equal "file" (org-element-property :type link))
18741 (or include-linked
18742 (null (org-element-contents link)))
18743 (string-match-p file-extension-re
18744 (org-element-property :path link)))
18745 (let ((file (expand-file-name
18746 (org-link-unescape
18747 (org-element-property :path link)))))
18748 (when (file-exists-p file)
18749 (let ((width
18750 ;; Apply `org-image-actual-width' specifications.
18751 (cond
18752 ((not (image-type-available-p 'imagemagick)) nil)
18753 ((eq org-image-actual-width t) nil)
18754 ((listp org-image-actual-width)
18756 ;; First try to find a width among
18757 ;; attributes associated to the paragraph
18758 ;; containing link.
18759 (let ((paragraph
18760 (let ((e link))
18761 (while (and (setq e (org-element-property
18762 :parent e))
18763 (not (eq (org-element-type e)
18764 'paragraph))))
18765 e)))
18766 (when paragraph
18767 (save-excursion
18768 (goto-char (org-element-property :begin paragraph))
18769 (when
18770 (re-search-forward
18771 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18772 (org-element-property
18773 :post-affiliated paragraph)
18775 (string-to-number (match-string 1))))))
18776 ;; Otherwise, fall-back to provided number.
18777 (car org-image-actual-width)))
18778 ((numberp org-image-actual-width)
18779 org-image-actual-width)))
18780 (old (get-char-property-and-overlay
18781 (org-element-property :begin link)
18782 'org-image-overlay)))
18783 (if (and (car-safe old) refresh)
18784 (image-refresh (overlay-get (cdr old) 'display))
18785 (let ((image (create-image file
18786 (and width 'imagemagick)
18788 :width width)))
18789 (when image
18790 (let ((ov (make-overlay
18791 (org-element-property :begin link)
18792 (progn
18793 (goto-char
18794 (org-element-property :end link))
18795 (skip-chars-backward " \t")
18796 (point)))))
18797 (overlay-put ov 'display image)
18798 (overlay-put ov 'face 'default)
18799 (overlay-put ov 'org-image-overlay t)
18800 (overlay-put
18801 ov 'modification-hooks
18802 (list 'org-display-inline-remove-overlay))
18803 (push ov org-inline-image-overlays)))))))))))))))
18805 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18806 "Remove inline-display overlay if a corresponding region is modified."
18807 (let ((inhibit-modification-hooks t))
18808 (when (and ov after)
18809 (delete ov org-inline-image-overlays)
18810 (delete-overlay ov))))
18812 (defun org-remove-inline-images ()
18813 "Remove inline display of images."
18814 (interactive)
18815 (mapc #'delete-overlay org-inline-image-overlays)
18816 (setq org-inline-image-overlays nil))
18819 ;;; Key bindings
18821 (defun org-remap (map &rest commands)
18822 "In MAP, remap the functions given in COMMANDS.
18823 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18824 (let (new old)
18825 (while commands
18826 (setq old (pop commands) new (pop commands))
18827 (org-defkey map (vector 'remap old) new))))
18829 ;;;; Outline functions that can be remapped in Org
18830 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18831 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18832 (define-key org-mode-map [remap outline-forward-same-level]
18833 #'org-forward-heading-same-level)
18834 (define-key org-mode-map [remap outline-backward-same-level]
18835 #'org-backward-heading-same-level)
18836 (define-key org-mode-map [remap outline-show-branches]
18837 #'org-kill-note-or-show-branches)
18838 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18839 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18840 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18841 (define-key org-mode-map [remap outline-next-visible-heading]
18842 #'org-next-visible-heading)
18843 (define-key org-mode-map [remap outline-previous-visible-heading]
18844 #'org-previous-visible-heading)
18845 (define-key org-mode-map [remap show-children] #'org-show-children)
18847 ;;;; Make `C-c C-x' a prefix key
18848 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18850 ;;;; TAB key with modifiers
18851 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18852 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18853 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18854 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18855 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18857 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18858 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18859 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18861 ;;;; RET key with modifiers
18862 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18863 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18864 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18865 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18866 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18868 ;;;; Cursor keys with modifiers
18869 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18870 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18871 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18872 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18873 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18874 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18875 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18877 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18878 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18879 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18880 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18881 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18882 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18883 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18884 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18885 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18886 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18888 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18889 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18890 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18891 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18893 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18894 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18895 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18896 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18898 ;;;; Babel keys
18899 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18900 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18901 (define-key org-babel-map key def))
18903 ;;;; Extra keys for TTY access.
18905 ;; We only set them when really needed because otherwise the
18906 ;; menus don't show the simple keys
18908 (when (or org-use-extra-keys (not window-system))
18909 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18910 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18911 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18912 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18913 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18914 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18915 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18916 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18917 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18918 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18919 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18920 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18921 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18922 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18923 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18924 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18925 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18926 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18927 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18928 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18929 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18931 ;;;; Narrow map
18932 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18933 (org-defkey narrow-map "b" #'org-narrow-to-block)
18934 (org-defkey narrow-map "e" #'org-narrow-to-element)
18936 ;;;; Remap usual Emacs bindings
18937 (org-remap org-mode-map
18938 'self-insert-command 'org-self-insert-command
18939 'delete-char 'org-delete-char
18940 'delete-backward-char 'org-delete-backward-char
18941 'kill-line 'org-kill-line
18942 'open-line 'org-open-line
18943 'yank 'org-yank
18944 'comment-dwim 'org-comment-dwim
18945 'move-beginning-of-line 'org-beginning-of-line
18946 'move-end-of-line 'org-end-of-line
18947 'forward-paragraph 'org-forward-paragraph
18948 'backward-paragraph 'org-backward-paragraph
18949 'backward-sentence 'org-backward-sentence
18950 'forward-sentence 'org-forward-sentence
18951 'fill-paragraph 'org-fill-paragraph
18952 'delete-indentation 'org-delete-indentation
18953 'transpose-words 'org-transpose-words)
18955 ;;;; All the other keys
18956 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18957 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18958 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18959 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18960 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18961 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18962 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18963 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18964 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18965 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18966 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18967 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18968 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18969 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18970 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18971 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18972 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18973 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18974 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18975 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18976 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18977 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18978 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18979 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18980 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18981 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18982 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18983 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18984 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18985 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18986 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18987 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18988 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18989 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18990 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18991 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18992 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18993 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18994 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18995 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18996 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18997 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
18998 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
18999 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19000 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19001 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19002 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19003 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19004 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19005 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19006 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19007 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19008 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19009 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19010 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19011 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19012 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19013 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19014 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19015 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19016 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19017 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19018 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19019 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19020 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19021 (org-defkey org-mode-map (kbd "RET") #'org-return)
19022 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19023 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19024 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19025 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19026 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19027 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19028 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19029 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19030 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19031 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19032 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19033 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19034 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19035 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19036 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19037 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19038 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19039 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19040 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19041 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19042 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19043 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19044 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19046 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19047 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19048 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19050 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19051 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19052 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19053 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19054 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19055 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19056 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19057 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19058 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19059 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19060 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19061 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19062 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19063 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19064 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19065 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19066 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19067 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19068 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19069 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19070 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19071 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19072 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19073 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19074 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19075 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19076 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19077 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19079 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19081 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19083 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19084 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19086 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19089 ;;; Speed commands
19091 (defconst org-speed-commands-default
19093 ("Outline Navigation")
19094 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19095 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19096 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19097 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19098 ("F" . org-next-block)
19099 ("B" . org-previous-block)
19100 ("u" . (org-speed-move-safe 'outline-up-heading))
19101 ("j" . org-goto)
19102 ("g" . (org-refile t))
19103 ("Outline Visibility")
19104 ("c" . org-cycle)
19105 ("C" . org-shifttab)
19106 (" " . org-display-outline-path)
19107 ("s" . org-narrow-to-subtree)
19108 ("=" . org-columns)
19109 ("Outline Structure Editing")
19110 ("U" . org-metaup)
19111 ("D" . org-metadown)
19112 ("r" . org-metaright)
19113 ("l" . org-metaleft)
19114 ("R" . org-shiftmetaright)
19115 ("L" . org-shiftmetaleft)
19116 ("i" . (progn (forward-char 1) (call-interactively
19117 'org-insert-heading-respect-content)))
19118 ("^" . org-sort)
19119 ("w" . org-refile)
19120 ("a" . org-archive-subtree-default-with-confirmation)
19121 ("@" . org-mark-subtree)
19122 ("#" . org-toggle-comment)
19123 ("Clock Commands")
19124 ("I" . org-clock-in)
19125 ("O" . org-clock-out)
19126 ("Meta Data Editing")
19127 ("t" . org-todo)
19128 ("," . (org-priority))
19129 ("0" . (org-priority ?\ ))
19130 ("1" . (org-priority ?A))
19131 ("2" . (org-priority ?B))
19132 ("3" . (org-priority ?C))
19133 (":" . org-set-tags-command)
19134 ("e" . org-set-effort)
19135 ("E" . org-inc-effort)
19136 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19137 (org-entry-put (point) "APPT_WARNTIME" m)))
19138 ("Agenda Views etc")
19139 ("v" . org-agenda)
19140 ("/" . org-sparse-tree)
19141 ("Misc")
19142 ("o" . org-open-at-point)
19143 ("?" . org-speed-command-help)
19144 ("<" . (org-agenda-set-restriction-lock 'subtree))
19145 (">" . (org-agenda-remove-restriction-lock))
19147 "The default speed commands.")
19149 (defun org-print-speed-command (e)
19150 (if (> (length (car e)) 1)
19151 (progn
19152 (princ "\n")
19153 (princ (car e))
19154 (princ "\n")
19155 (princ (make-string (length (car e)) ?-))
19156 (princ "\n"))
19157 (princ (car e))
19158 (princ " ")
19159 (if (symbolp (cdr e))
19160 (princ (symbol-name (cdr e)))
19161 (prin1 (cdr e)))
19162 (princ "\n")))
19164 (defun org-speed-command-help ()
19165 "Show the available speed commands."
19166 (interactive)
19167 (if (not org-use-speed-commands)
19168 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19169 (with-output-to-temp-buffer "*Help*"
19170 (princ "User-defined Speed commands\n===========================\n")
19171 (mapc #'org-print-speed-command org-speed-commands-user)
19172 (princ "\n")
19173 (princ "Built-in Speed commands\n=======================\n")
19174 (mapc #'org-print-speed-command org-speed-commands-default))
19175 (with-current-buffer "*Help*"
19176 (setq truncate-lines t))))
19178 (defun org-speed-move-safe (cmd)
19179 "Execute CMD, but make sure that the cursor always ends up in a headline.
19180 If not, return to the original position and throw an error."
19181 (interactive)
19182 (let ((pos (point)))
19183 (call-interactively cmd)
19184 (unless (and (bolp) (org-at-heading-p))
19185 (goto-char pos)
19186 (error "Boundary reached while executing %s" cmd))))
19188 (defvar org-self-insert-command-undo-counter 0)
19190 (defvar org-table-auto-blank-field) ; defined in org-table.el
19191 (defvar org-speed-command nil)
19193 (defun org-speed-command-activate (keys)
19194 "Hook for activating single-letter speed commands.
19195 `org-speed-commands-default' specifies a minimal command set.
19196 Use `org-speed-commands-user' for further customization."
19197 (when (or (and (bolp) (looking-at org-outline-regexp))
19198 (and (functionp org-use-speed-commands)
19199 (funcall org-use-speed-commands)))
19200 (cdr (assoc keys (append org-speed-commands-user
19201 org-speed-commands-default)))))
19203 (defun org-babel-speed-command-activate (keys)
19204 "Hook for activating single-letter code block commands."
19205 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19206 (cdr (assoc keys org-babel-key-bindings))))
19208 (defcustom org-speed-command-hook
19209 '(org-speed-command-activate org-babel-speed-command-activate)
19210 "Hook for activating speed commands at strategic locations.
19211 Hook functions are called in sequence until a valid handler is
19212 found.
19214 Each hook takes a single argument, a user-pressed command key
19215 which is also a `self-insert-command' from the global map.
19217 Within the hook, examine the cursor position and the command key
19218 and return nil or a valid handler as appropriate. Handler could
19219 be one of an interactive command, a function, or a form.
19221 Set `org-use-speed-commands' to non-nil value to enable this
19222 hook. The default setting is `org-speed-command-activate'."
19223 :group 'org-structure
19224 :version "24.1"
19225 :type 'hook)
19227 (defun org-self-insert-command (N)
19228 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19229 If the cursor is in a table looking at whitespace, the whitespace is
19230 overwritten, and the table is not marked as requiring realignment."
19231 (interactive "p")
19232 (org-check-before-invisible-edit 'insert)
19233 (cond
19234 ((and org-use-speed-commands
19235 (let ((kv (this-command-keys-vector)))
19236 (setq org-speed-command
19237 (run-hook-with-args-until-success
19238 'org-speed-command-hook
19239 (make-string 1 (aref kv (1- (length kv))))))))
19240 (cond
19241 ((commandp org-speed-command)
19242 (setq this-command org-speed-command)
19243 (call-interactively org-speed-command))
19244 ((functionp org-speed-command)
19245 (funcall org-speed-command))
19246 ((and org-speed-command (listp org-speed-command))
19247 (eval org-speed-command))
19248 (t (let (org-use-speed-commands)
19249 (call-interactively 'org-self-insert-command)))))
19250 ((and
19251 (= N 1)
19252 (not (org-region-active-p))
19253 (org-at-table-p)
19254 (progn
19255 ;; Check if we blank the field, and if that triggers align.
19256 (and (featurep 'org-table)
19257 org-table-auto-blank-field
19258 (memq last-command
19259 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19260 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19261 ;; Got extra space, this field does not determine
19262 ;; column width.
19263 (let (org-table-may-need-update) (org-table-blank-field))
19264 ;; No extra space, this field may determine column
19265 ;; width.
19266 (org-table-blank-field)))
19268 (looking-at "[^|\n]* |"))
19269 ;; There is room for insertion without re-aligning the table.
19270 (self-insert-command N)
19271 (org-table-with-shrunk-field
19272 (save-excursion
19273 (skip-chars-forward "^|")
19274 ;; Do not delete last space, which is
19275 ;; `org-table-separator-space', but the regular space before
19276 ;; it.
19277 (delete-region (- (point) 2) (1- (point))))))
19279 (setq org-table-may-need-update t)
19280 (self-insert-command N)
19281 (org-fix-tags-on-the-fly)
19282 (when org-self-insert-cluster-for-undo
19283 (if (not (eq last-command 'org-self-insert-command))
19284 (setq org-self-insert-command-undo-counter 1)
19285 (if (>= org-self-insert-command-undo-counter 20)
19286 (setq org-self-insert-command-undo-counter 1)
19287 (and (> org-self-insert-command-undo-counter 0)
19288 buffer-undo-list (listp buffer-undo-list)
19289 (not (cadr buffer-undo-list)) ; remove nil entry
19290 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19291 (setq org-self-insert-command-undo-counter
19292 (1+ org-self-insert-command-undo-counter))))))))
19294 (defun org-check-before-invisible-edit (kind)
19295 "Check is editing if kind KIND would be dangerous with invisible text around.
19296 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19297 ;; First, try to get out of here as quickly as possible, to reduce overhead
19298 (when (and org-catch-invisible-edits
19299 (or (not (boundp 'visible-mode)) (not visible-mode))
19300 (or (get-char-property (point) 'invisible)
19301 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19302 ;; OK, we need to take a closer look. Do not consider
19303 ;; invisibility obtained through text properties (e.g., link
19304 ;; fontification), as it cannot be toggled.
19305 (let* ((invisible-at-point
19306 (pcase (get-char-property-and-overlay (point) 'invisible)
19307 (`(,_ . ,(and (pred overlayp) o)) o)))
19308 ;; Assume that point cannot land in the middle of an
19309 ;; overlay, or between two overlays.
19310 (invisible-before-point
19311 (and (not invisible-at-point)
19312 (not (bobp))
19313 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19314 (`(,_ . ,(and (pred overlayp) o)) o))))
19315 (border-and-ok-direction
19317 ;; Check if we are acting predictably before invisible
19318 ;; text.
19319 (and invisible-at-point
19320 (memq kind '(insert delete-backward)))
19321 ;; Check if we are acting predictably after invisible text
19322 ;; This works not well, and I have turned it off. It seems
19323 ;; better to always show and stop after invisible text.
19324 ;; (and (not invisible-at-point) invisible-before-point
19325 ;; (memq kind '(insert delete)))
19327 (when (or invisible-at-point invisible-before-point)
19328 (when (eq org-catch-invisible-edits 'error)
19329 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19330 (if (and org-custom-properties-overlays
19331 (y-or-n-p "Display invisible properties in this buffer? "))
19332 (org-toggle-custom-properties-visibility)
19333 ;; Make the area visible
19334 (save-excursion
19335 (when invisible-before-point
19336 (goto-char
19337 (previous-single-char-property-change (point) 'invisible)))
19338 ;; Remove whatever overlay is currently making yet-to-be
19339 ;; edited text invisible. Also remove nested invisibility
19340 ;; related overlays.
19341 (delete-overlay (or invisible-at-point invisible-before-point))
19342 (let ((origin (if invisible-at-point (point) (1- (point)))))
19343 (while (pcase (get-char-property-and-overlay origin 'invisible)
19344 (`(,_ . ,(and (pred overlayp) o))
19345 (delete-overlay o)
19346 t)))))
19347 (cond
19348 ((eq org-catch-invisible-edits 'show)
19349 ;; That's it, we do the edit after showing
19350 (message
19351 "Unfolding invisible region around point before editing")
19352 (sit-for 1))
19353 ((and (eq org-catch-invisible-edits 'smart)
19354 border-and-ok-direction)
19355 (message "Unfolding invisible region around point before editing"))
19357 ;; Don't do the edit, make the user repeat it in full visibility
19358 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19360 (defun org-fix-tags-on-the-fly ()
19361 "Align tags in headline at point.
19362 Unlike to `org-align-tags', this function does nothing if point
19363 is not currently on a headline."
19364 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19365 (org-at-heading-p))
19366 (org-align-tags)))
19368 (defun org-delete-backward-char (N)
19369 "Like `delete-backward-char', insert whitespace at field end in tables.
19370 When deleting backwards, in tables this function will insert whitespace in
19371 front of the next \"|\" separator, to keep the table aligned. The table will
19372 still be marked for re-alignment if the field did fill the entire column,
19373 because, in this case the deletion might narrow the column."
19374 (interactive "p")
19375 (save-match-data
19376 (org-check-before-invisible-edit 'delete-backward)
19377 (if (and (= N 1)
19378 (not overwrite-mode)
19379 (not (org-region-active-p))
19380 (not (eq (char-before) ?|))
19381 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19382 (looking-at-p ".*?|")
19383 (org-at-table-p))
19384 (progn (forward-char -1) (org-delete-char 1))
19385 (backward-delete-char N)
19386 (org-fix-tags-on-the-fly))))
19388 (defun org-delete-char (N)
19389 "Like `delete-char', but insert whitespace at field end in tables.
19390 When deleting characters, in tables this function will insert whitespace in
19391 front of the next \"|\" separator, to keep the table aligned. The table will
19392 still be marked for re-alignment if the field did fill the entire column,
19393 because, in this case the deletion might narrow the column."
19394 (interactive "p")
19395 (save-match-data
19396 (org-check-before-invisible-edit 'delete)
19397 (cond
19398 ((or (/= N 1)
19399 (eq (char-after) ?|)
19400 (save-excursion (skip-chars-backward " \t") (bolp))
19401 (not (org-at-table-p)))
19402 (delete-char N)
19403 (org-fix-tags-on-the-fly))
19404 ((looking-at ".\\(.*?\\)|")
19405 (let* ((update? org-table-may-need-update)
19406 (noalign (looking-at-p ".*? |")))
19407 (delete-char 1)
19408 (org-table-with-shrunk-field
19409 (save-excursion
19410 ;; Last space is `org-table-separator-space', so insert
19411 ;; a regular one before it instead.
19412 (goto-char (- (match-end 0) 2))
19413 (insert " ")))
19414 ;; If there were two spaces at the end, this field does not
19415 ;; determine the width of the column.
19416 (when noalign (setq org-table-may-need-update update?))))
19418 (delete-char N)))))
19420 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19421 (put 'org-self-insert-command 'delete-selection
19422 (lambda ()
19423 (not (run-hook-with-args-until-success
19424 'self-insert-uses-region-functions))))
19425 (put 'orgtbl-self-insert-command 'delete-selection
19426 (lambda ()
19427 (not (run-hook-with-args-until-success
19428 'self-insert-uses-region-functions))))
19429 (put 'org-delete-char 'delete-selection 'supersede)
19430 (put 'org-delete-backward-char 'delete-selection 'supersede)
19431 (put 'org-yank 'delete-selection 'yank)
19433 ;; Make `flyspell-mode' delay after some commands
19434 (put 'org-self-insert-command 'flyspell-delayed t)
19435 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19436 (put 'org-delete-char 'flyspell-delayed t)
19437 (put 'org-delete-backward-char 'flyspell-delayed t)
19439 ;; Make pabbrev-mode expand after Org mode commands
19440 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19441 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19443 (defun org-transpose-words ()
19444 "Transpose words for Org.
19445 This uses the `org-mode-transpose-word-syntax-table' syntax
19446 table, which interprets characters in `org-emphasis-alist' as
19447 word constituents."
19448 (interactive)
19449 (with-syntax-table org-mode-transpose-word-syntax-table
19450 (call-interactively 'transpose-words)))
19452 (defvar org-ctrl-c-ctrl-c-hook nil
19453 "Hook for functions attaching themselves to `C-c C-c'.
19455 This can be used to add additional functionality to the C-c C-c
19456 key which executes context-dependent commands. This hook is run
19457 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19458 run after the last test.
19460 Each function will be called with no arguments. The function
19461 must check if the context is appropriate for it to act. If yes,
19462 it should do its thing and then return a non-nil value. If the
19463 context is wrong, just do nothing and return nil.")
19465 (defvar org-ctrl-c-ctrl-c-final-hook nil
19466 "Hook for functions attaching themselves to `C-c C-c'.
19468 This can be used to add additional functionality to the C-c C-c
19469 key which executes context-dependent commands. This hook is run
19470 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19471 before the first test.
19473 Each function will be called with no arguments. The function
19474 must check if the context is appropriate for it to act. If yes,
19475 it should do its thing and then return a non-nil value. If the
19476 context is wrong, just do nothing and return nil.")
19478 (defvar org-tab-first-hook nil
19479 "Hook for functions to attach themselves to TAB.
19480 See `org-ctrl-c-ctrl-c-hook' for more information.
19481 This hook runs as the first action when TAB is pressed, even before
19482 `org-cycle' messes around with the `outline-regexp' to cater for
19483 inline tasks and plain list item folding.
19484 If any function in this hook returns t, any other actions that
19485 would have been caused by TAB (such as table field motion or visibility
19486 cycling) will not occur.")
19488 (defvar org-tab-after-check-for-table-hook nil
19489 "Hook for functions to attach themselves to TAB.
19490 See `org-ctrl-c-ctrl-c-hook' for more information.
19491 This hook runs after it has been established that the cursor is not in a
19492 table, but before checking if the cursor is in a headline or if global cycling
19493 should be done.
19494 If any function in this hook returns t, not other actions like visibility
19495 cycling will be done.")
19497 (defvar org-tab-after-check-for-cycling-hook nil
19498 "Hook for functions to attach themselves to TAB.
19499 See `org-ctrl-c-ctrl-c-hook' for more information.
19500 This hook runs after it has been established that not table field motion and
19501 not visibility should be done because of current context. This is probably
19502 the place where a package like yasnippets can hook in.")
19504 (defvar org-tab-before-tab-emulation-hook nil
19505 "Hook for functions to attach themselves to TAB.
19506 See `org-ctrl-c-ctrl-c-hook' for more information.
19507 This hook runs after every other options for TAB have been exhausted, but
19508 before indentation and \t insertion takes place.")
19510 (defvar org-metaleft-hook nil
19511 "Hook for functions attaching themselves to `M-left'.
19512 See `org-ctrl-c-ctrl-c-hook' for more information.")
19513 (defvar org-metaright-hook nil
19514 "Hook for functions attaching themselves to `M-right'.
19515 See `org-ctrl-c-ctrl-c-hook' for more information.")
19516 (defvar org-metaup-hook nil
19517 "Hook for functions attaching themselves to `M-up'.
19518 See `org-ctrl-c-ctrl-c-hook' for more information.")
19519 (defvar org-metadown-hook nil
19520 "Hook for functions attaching themselves to `M-down'.
19521 See `org-ctrl-c-ctrl-c-hook' for more information.")
19522 (defvar org-shiftmetaleft-hook nil
19523 "Hook for functions attaching themselves to `M-S-left'.
19524 See `org-ctrl-c-ctrl-c-hook' for more information.")
19525 (defvar org-shiftmetaright-hook nil
19526 "Hook for functions attaching themselves to `M-S-right'.
19527 See `org-ctrl-c-ctrl-c-hook' for more information.")
19528 (defvar org-shiftmetaup-hook nil
19529 "Hook for functions attaching themselves to `M-S-up'.
19530 See `org-ctrl-c-ctrl-c-hook' for more information.")
19531 (defvar org-shiftmetadown-hook nil
19532 "Hook for functions attaching themselves to `M-S-down'.
19533 See `org-ctrl-c-ctrl-c-hook' for more information.")
19534 (defvar org-metareturn-hook nil
19535 "Hook for functions attaching themselves to `M-RET'.
19536 See `org-ctrl-c-ctrl-c-hook' for more information.")
19537 (defvar org-shiftup-hook nil
19538 "Hook for functions attaching themselves to `S-up'.
19539 See `org-ctrl-c-ctrl-c-hook' for more information.")
19540 (defvar org-shiftup-final-hook nil
19541 "Hook for functions attaching themselves to `S-up'.
19542 This one runs after all other options except shift-select have been excluded.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-shiftdown-hook nil
19545 "Hook for functions attaching themselves to `S-down'.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-shiftdown-final-hook nil
19548 "Hook for functions attaching themselves to `S-down'.
19549 This one runs after all other options except shift-select have been excluded.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-shiftleft-hook nil
19552 "Hook for functions attaching themselves to `S-left'.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defvar org-shiftleft-final-hook nil
19555 "Hook for functions attaching themselves to `S-left'.
19556 This one runs after all other options except shift-select have been excluded.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19558 (defvar org-shiftright-hook nil
19559 "Hook for functions attaching themselves to `S-right'.
19560 See `org-ctrl-c-ctrl-c-hook' for more information.")
19561 (defvar org-shiftright-final-hook nil
19562 "Hook for functions attaching themselves to `S-right'.
19563 This one runs after all other options except shift-select have been excluded.
19564 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defun org-modifier-cursor-error ()
19567 "Throw an error, a modified cursor command was applied in wrong context."
19568 (user-error "This command is active in special context like tables, headlines or items"))
19570 (defun org-shiftselect-error ()
19571 "Throw an error because Shift-Cursor command was applied in wrong context."
19572 (if (and (boundp 'shift-select-mode) shift-select-mode)
19573 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19574 (user-error "This command works only in special context like headlines or timestamps")))
19576 (defun org-call-for-shift-select (cmd)
19577 (let ((this-command-keys-shift-translated t))
19578 (call-interactively cmd)))
19580 (defun org-shifttab (&optional arg)
19581 "Global visibility cycling or move to previous table field.
19582 Call `org-table-previous-field' within a table.
19583 When ARG is nil, cycle globally through visibility states.
19584 When ARG is a numeric prefix, show contents of this level."
19585 (interactive "P")
19586 (cond
19587 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19588 ((integerp arg)
19589 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19590 (message "Content view to level: %d" arg)
19591 (org-content (prefix-numeric-value arg2))
19592 (org-cycle-show-empty-lines t)
19593 (setq org-cycle-global-status 'overview)))
19594 (t (call-interactively 'org-global-cycle))))
19596 (defun org-shiftmetaleft ()
19597 "Promote subtree or delete table column.
19598 Calls `org-promote-subtree', `org-outdent-item-tree', or
19599 `org-table-delete-column', depending on context. See the
19600 individual commands for more information."
19601 (interactive)
19602 (cond
19603 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19604 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19605 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19606 ((if (not (org-region-active-p)) (org-at-item-p)
19607 (save-excursion (goto-char (region-beginning))
19608 (org-at-item-p)))
19609 (call-interactively 'org-outdent-item-tree))
19610 (t (org-modifier-cursor-error))))
19612 (defun org-shiftmetaright ()
19613 "Demote subtree or insert table column.
19614 Calls `org-demote-subtree', `org-indent-item-tree', or
19615 `org-table-insert-column', depending on context. See the
19616 individual commands for more information."
19617 (interactive)
19618 (cond
19619 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19620 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19621 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19622 ((if (not (org-region-active-p)) (org-at-item-p)
19623 (save-excursion (goto-char (region-beginning))
19624 (org-at-item-p)))
19625 (call-interactively 'org-indent-item-tree))
19626 (t (org-modifier-cursor-error))))
19628 (defun org-shiftmetaup (&optional _arg)
19629 "Drag the line at point up.
19630 In a table, kill the current row.
19631 On a clock timestamp, update the value of the timestamp like `S-<up>'
19632 but also adjust the previous clocked item in the clock history.
19633 Everywhere else, drag the line at point up."
19634 (interactive "P")
19635 (cond
19636 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19637 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19638 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19639 (call-interactively 'org-timestamp-up)))
19640 (t (call-interactively 'org-drag-line-backward))))
19642 (defun org-shiftmetadown (&optional _arg)
19643 "Drag the line at point down.
19644 In a table, insert an empty row at the current line.
19645 On a clock timestamp, update the value of the timestamp like `S-<down>'
19646 but also adjust the previous clocked item in the clock history.
19647 Everywhere else, drag the line at point down."
19648 (interactive "P")
19649 (cond
19650 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19651 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19652 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19653 (call-interactively 'org-timestamp-down)))
19654 (t (call-interactively 'org-drag-line-forward))))
19656 (defsubst org-hidden-tree-error ()
19657 (user-error
19658 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19660 (defun org-metaleft (&optional _arg)
19661 "Promote heading, list item at point or move table column left.
19663 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19664 depending on context. With no specific context, calls the Emacs
19665 default `backward-word'. See the individual commands for more
19666 information.
19668 This function runs the hook `org-metaleft-hook' as a first step,
19669 and returns at first non-nil value."
19670 (interactive "P")
19671 (cond
19672 ((run-hook-with-args-until-success 'org-metaleft-hook))
19673 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19674 ((org-with-limited-levels
19675 (or (org-at-heading-p)
19676 (and (org-region-active-p)
19677 (save-excursion
19678 (goto-char (region-beginning))
19679 (org-at-heading-p)))))
19680 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19681 (call-interactively 'org-do-promote))
19682 ;; At an inline task.
19683 ((org-at-heading-p)
19684 (call-interactively 'org-inlinetask-promote))
19685 ((or (org-at-item-p)
19686 (and (org-region-active-p)
19687 (save-excursion
19688 (goto-char (region-beginning))
19689 (org-at-item-p))))
19690 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19691 (call-interactively 'org-outdent-item))
19692 (t (call-interactively 'backward-word))))
19694 (defun org-metaright (&optional _arg)
19695 "Demote heading, list item at point or move table column right.
19697 In front of a drawer or a block keyword, indent it correctly.
19699 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19700 `org-indent-drawer' or `org-indent-block' depending on context.
19701 With no specific context, calls the Emacs default `forward-word'.
19702 See the individual commands for more information.
19704 This function runs the hook `org-metaright-hook' as a first step,
19705 and returns at first non-nil value."
19706 (interactive "P")
19707 (cond
19708 ((run-hook-with-args-until-success 'org-metaright-hook))
19709 ((org-at-table-p) (call-interactively 'org-table-move-column))
19710 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19711 ((org-at-block-p) (call-interactively 'org-indent-block))
19712 ((org-with-limited-levels
19713 (or (org-at-heading-p)
19714 (and (org-region-active-p)
19715 (save-excursion
19716 (goto-char (region-beginning))
19717 (org-at-heading-p)))))
19718 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19719 (call-interactively 'org-do-demote))
19720 ;; At an inline task.
19721 ((org-at-heading-p)
19722 (call-interactively 'org-inlinetask-demote))
19723 ((or (org-at-item-p)
19724 (and (org-region-active-p)
19725 (save-excursion
19726 (goto-char (region-beginning))
19727 (org-at-item-p))))
19728 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19729 (call-interactively 'org-indent-item))
19730 (t (call-interactively 'forward-word))))
19732 (defun org-check-for-hidden (what)
19733 "Check if there are hidden headlines/items in the current visual line.
19734 WHAT can be either `headlines' or `items'. If the current line is
19735 an outline or item heading and it has a folded subtree below it,
19736 this function returns t, nil otherwise."
19737 (let ((re (cond
19738 ((eq what 'headlines) org-outline-regexp-bol)
19739 ((eq what 'items) (org-item-beginning-re))
19740 (t (error "This should not happen"))))
19741 beg end)
19742 (save-excursion
19743 (catch 'exit
19744 (unless (org-region-active-p)
19745 (setq beg (point-at-bol))
19746 (beginning-of-line 2)
19747 (while (and (not (eobp)) ;; this is like `next-line'
19748 (get-char-property (1- (point)) 'invisible))
19749 (beginning-of-line 2))
19750 (setq end (point))
19751 (goto-char beg)
19752 (goto-char (point-at-eol))
19753 (setq end (max end (point)))
19754 (while (re-search-forward re end t)
19755 (when (get-char-property (match-beginning 0) 'invisible)
19756 (throw 'exit t))))
19757 nil))))
19759 (defun org-metaup (&optional _arg)
19760 "Move subtree up or move table row up.
19761 Calls `org-move-subtree-up' or `org-table-move-row' or
19762 `org-move-item-up', depending on context. See the individual commands
19763 for more information."
19764 (interactive "P")
19765 (cond
19766 ((run-hook-with-args-until-success 'org-metaup-hook))
19767 ((org-region-active-p)
19768 (let* ((a (min (region-beginning) (region-end)))
19769 (b (1- (max (region-beginning) (region-end))))
19770 (c (save-excursion (goto-char a)
19771 (move-beginning-of-line 0)))
19772 (d (save-excursion (goto-char a)
19773 (move-end-of-line 0) (point))))
19774 (transpose-regions a b c d)
19775 (goto-char c)))
19776 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19777 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19778 ((org-at-item-p) (call-interactively 'org-move-item-up))
19779 (t (org-drag-element-backward))))
19781 (defun org-metadown (&optional _arg)
19782 "Move subtree down or move table row down.
19783 Calls `org-move-subtree-down' or `org-table-move-row' or
19784 `org-move-item-down', depending on context. See the individual
19785 commands for more information."
19786 (interactive "P")
19787 (cond
19788 ((run-hook-with-args-until-success 'org-metadown-hook))
19789 ((org-region-active-p)
19790 (let* ((a (min (region-beginning) (region-end)))
19791 (b (max (region-beginning) (region-end)))
19792 (c (save-excursion (goto-char b)
19793 (move-beginning-of-line 1)))
19794 (d (save-excursion (goto-char b)
19795 (move-end-of-line 1) (1+ (point)))))
19796 (transpose-regions a b c d)
19797 (goto-char d)))
19798 ((org-at-table-p) (call-interactively 'org-table-move-row))
19799 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19800 ((org-at-item-p) (call-interactively 'org-move-item-down))
19801 (t (org-drag-element-forward))))
19803 (defun org-shiftup (&optional arg)
19804 "Increase item in timestamp or increase priority of current headline.
19805 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19806 depending on context. See the individual commands for more information."
19807 (interactive "P")
19808 (cond
19809 ((run-hook-with-args-until-success 'org-shiftup-hook))
19810 ((and org-support-shift-select (org-region-active-p))
19811 (org-call-for-shift-select 'previous-line))
19812 ((org-at-timestamp-p 'lax)
19813 (call-interactively (if org-edit-timestamp-down-means-later
19814 'org-timestamp-down 'org-timestamp-up)))
19815 ((and (not (eq org-support-shift-select 'always))
19816 org-enable-priority-commands
19817 (org-at-heading-p))
19818 (call-interactively 'org-priority-up))
19819 ((and (not org-support-shift-select) (org-at-item-p))
19820 (call-interactively 'org-previous-item))
19821 ((org-clocktable-try-shift 'up arg))
19822 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19823 (org-support-shift-select
19824 (org-call-for-shift-select 'previous-line))
19825 (t (org-shiftselect-error))))
19827 (defun org-shiftdown (&optional arg)
19828 "Decrease item in timestamp or decrease priority of current headline.
19829 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19830 depending on context. See the individual commands for more information."
19831 (interactive "P")
19832 (cond
19833 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19834 ((and org-support-shift-select (org-region-active-p))
19835 (org-call-for-shift-select 'next-line))
19836 ((org-at-timestamp-p 'lax)
19837 (call-interactively (if org-edit-timestamp-down-means-later
19838 'org-timestamp-up 'org-timestamp-down)))
19839 ((and (not (eq org-support-shift-select 'always))
19840 org-enable-priority-commands
19841 (org-at-heading-p))
19842 (call-interactively 'org-priority-down))
19843 ((and (not org-support-shift-select) (org-at-item-p))
19844 (call-interactively 'org-next-item))
19845 ((org-clocktable-try-shift 'down arg))
19846 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19847 (org-support-shift-select
19848 (org-call-for-shift-select 'next-line))
19849 (t (org-shiftselect-error))))
19851 (defun org-shiftright (&optional arg)
19852 "Cycle the thing at point or in the current line, depending on context.
19853 Depending on context, this does one of the following:
19855 - switch a timestamp at point one day into the future
19856 - on a headline, switch to the next TODO keyword.
19857 - on an item, switch entire list to the next bullet type
19858 - on a property line, switch to the next allowed value
19859 - on a clocktable definition line, move time block into the future"
19860 (interactive "P")
19861 (cond
19862 ((run-hook-with-args-until-success 'org-shiftright-hook))
19863 ((and org-support-shift-select (org-region-active-p))
19864 (org-call-for-shift-select 'forward-char))
19865 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19866 ((and (not (eq org-support-shift-select 'always))
19867 (org-at-heading-p))
19868 (let ((org-inhibit-logging
19869 (not org-treat-S-cursor-todo-selection-as-state-change))
19870 (org-inhibit-blocking
19871 (not org-treat-S-cursor-todo-selection-as-state-change)))
19872 (org-call-with-arg 'org-todo 'right)))
19873 ((or (and org-support-shift-select
19874 (not (eq org-support-shift-select 'always))
19875 (org-at-item-bullet-p))
19876 (and (not org-support-shift-select) (org-at-item-p)))
19877 (org-call-with-arg 'org-cycle-list-bullet nil))
19878 ((and (not (eq org-support-shift-select 'always))
19879 (org-at-property-p))
19880 (call-interactively 'org-property-next-allowed-value))
19881 ((org-clocktable-try-shift 'right arg))
19882 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19883 (org-support-shift-select
19884 (org-call-for-shift-select 'forward-char))
19885 (t (org-shiftselect-error))))
19887 (defun org-shiftleft (&optional arg)
19888 "Cycle the thing at point or in the current line, depending on context.
19889 Depending on context, this does one of the following:
19891 - switch a timestamp at point one day into the past
19892 - on a headline, switch to the previous TODO keyword.
19893 - on an item, switch entire list to the previous bullet type
19894 - on a property line, switch to the previous allowed value
19895 - on a clocktable definition line, move time block into the past"
19896 (interactive "P")
19897 (cond
19898 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19899 ((and org-support-shift-select (org-region-active-p))
19900 (org-call-for-shift-select 'backward-char))
19901 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19902 ((and (not (eq org-support-shift-select 'always))
19903 (org-at-heading-p))
19904 (let ((org-inhibit-logging
19905 (not org-treat-S-cursor-todo-selection-as-state-change))
19906 (org-inhibit-blocking
19907 (not org-treat-S-cursor-todo-selection-as-state-change)))
19908 (org-call-with-arg 'org-todo 'left)))
19909 ((or (and org-support-shift-select
19910 (not (eq org-support-shift-select 'always))
19911 (org-at-item-bullet-p))
19912 (and (not org-support-shift-select) (org-at-item-p)))
19913 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19914 ((and (not (eq org-support-shift-select 'always))
19915 (org-at-property-p))
19916 (call-interactively 'org-property-previous-allowed-value))
19917 ((org-clocktable-try-shift 'left arg))
19918 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19919 (org-support-shift-select
19920 (org-call-for-shift-select 'backward-char))
19921 (t (org-shiftselect-error))))
19923 (defun org-shiftcontrolright ()
19924 "Switch to next TODO set."
19925 (interactive)
19926 (cond
19927 ((and org-support-shift-select (org-region-active-p))
19928 (org-call-for-shift-select 'forward-word))
19929 ((and (not (eq org-support-shift-select 'always))
19930 (org-at-heading-p))
19931 (org-call-with-arg 'org-todo 'nextset))
19932 (org-support-shift-select
19933 (org-call-for-shift-select 'forward-word))
19934 (t (org-shiftselect-error))))
19936 (defun org-shiftcontrolleft ()
19937 "Switch to previous TODO set."
19938 (interactive)
19939 (cond
19940 ((and org-support-shift-select (org-region-active-p))
19941 (org-call-for-shift-select 'backward-word))
19942 ((and (not (eq org-support-shift-select 'always))
19943 (org-at-heading-p))
19944 (org-call-with-arg 'org-todo 'previousset))
19945 (org-support-shift-select
19946 (org-call-for-shift-select 'backward-word))
19947 (t (org-shiftselect-error))))
19949 (defun org-shiftcontrolup (&optional n)
19950 "Change timestamps synchronously up in CLOCK log lines.
19951 Optional argument N tells to change by that many units."
19952 (interactive "P")
19953 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19954 (let (org-support-shift-select)
19955 (org-clock-timestamps-up n))
19956 (user-error "Not at a clock log")))
19958 (defun org-shiftcontroldown (&optional n)
19959 "Change timestamps synchronously down in CLOCK log lines.
19960 Optional argument N tells to change by that many units."
19961 (interactive "P")
19962 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19963 (let (org-support-shift-select)
19964 (org-clock-timestamps-down n))
19965 (user-error "Not at a clock log")))
19967 (defun org-increase-number-at-point (&optional inc)
19968 "Increment the number at point.
19969 With an optional prefix numeric argument INC, increment using
19970 this numeric value."
19971 (interactive "p")
19972 (if (not (number-at-point))
19973 (user-error "Not on a number")
19974 (unless inc (setq inc 1))
19975 (let ((pos (point))
19976 (beg (skip-chars-backward "-+^/*0-9eE."))
19977 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19978 (setq nap (buffer-substring-no-properties
19979 (+ pos beg) (+ pos beg end)))
19980 (delete-region (+ pos beg) (+ pos beg end))
19981 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19982 (when (org-at-table-p)
19983 (org-table-align)
19984 (org-table-end-of-field 1))))
19986 (defun org-decrease-number-at-point (&optional inc)
19987 "Decrement the number at point.
19988 With an optional prefix numeric argument INC, decrement using
19989 this numeric value."
19990 (interactive "p")
19991 (org-increase-number-at-point (- (or inc 1))))
19993 (defun org-ctrl-c-ret ()
19994 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19995 (interactive)
19996 (cond
19997 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19998 (t (call-interactively 'org-insert-heading))))
20000 (defun org-find-visible ()
20001 (let ((s (point)))
20002 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20003 (get-char-property s 'invisible)))
20005 (defun org-find-invisible ()
20006 (let ((s (point)))
20007 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20008 (not (get-char-property s 'invisible))))
20011 (defun org-copy-visible (beg end)
20012 "Copy the visible parts of the region."
20013 (interactive "r")
20014 (let ((result ""))
20015 (while (/= beg end)
20016 (when (get-char-property beg 'invisible)
20017 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20018 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20019 (setq result (concat result (buffer-substring beg next)))
20020 (setq beg next)))
20021 (kill-new result)))
20023 (defun org-copy-special ()
20024 "Copy region in table or copy current subtree.
20025 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20026 context. See the individual commands for more information."
20027 (interactive)
20028 (call-interactively
20029 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20031 (defun org-cut-special ()
20032 "Cut region in table or cut current subtree.
20033 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20034 context. See the individual commands for more information."
20035 (interactive)
20036 (call-interactively
20037 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20039 (defun org-paste-special (arg)
20040 "Paste rectangular region into table, or past subtree relative to level.
20041 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20042 See the individual commands for more information."
20043 (interactive "P")
20044 (if (org-at-table-p)
20045 (org-table-paste-rectangle)
20046 (org-paste-subtree arg)))
20048 (defun org-edit-special (&optional arg)
20049 "Call a special editor for the element at point.
20050 When at a table, call the formula editor with `org-table-edit-formulas'.
20051 When in a source code block, call `org-edit-src-code'.
20052 When in a fixed-width region, call `org-edit-fixed-width-region'.
20053 When in an export block, call `org-edit-export-block'.
20054 When in a LaTeX environment, call `org-edit-latex-environment'.
20055 When at an #+INCLUDE keyword, visit the included file.
20056 When at a footnote reference, call `org-edit-footnote-reference'
20057 On a link, call `ffap' to visit the link at point.
20058 Otherwise, return a user error."
20059 (interactive "P")
20060 (let ((element (org-element-at-point)))
20061 (barf-if-buffer-read-only)
20062 (pcase (org-element-type element)
20063 (`src-block
20064 (if (not arg) (org-edit-src-code)
20065 (let* ((info (org-babel-get-src-block-info))
20066 (lang (nth 0 info))
20067 (params (nth 2 info))
20068 (session (cdr (assq :session params))))
20069 (if (not session) (org-edit-src-code)
20070 ;; At a src-block with a session and function called with
20071 ;; an ARG: switch to the buffer related to the inferior
20072 ;; process.
20073 (switch-to-buffer
20074 (funcall (intern (concat "org-babel-prep-session:" lang))
20075 session params))))))
20076 (`keyword
20077 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20078 (org-open-link-from-string
20079 (format "[[%s]]"
20080 (expand-file-name
20081 (let ((value (org-element-property :value element)))
20082 (cond ((org-file-url-p value)
20083 (user-error "The file is specified as a URL, cannot be edited"))
20084 ((not (org-string-nw-p value))
20085 (user-error "No file to edit"))
20086 ((string-match "\\`\"\\(.*?\\)\"" value)
20087 (match-string 1 value))
20088 ((string-match "\\`[^ \t\"]\\S-*" value)
20089 (match-string 0 value))
20090 (t (user-error "No valid file specified")))))))
20091 (user-error "No special environment to edit here")))
20092 (`table
20093 (if (eq (org-element-property :type element) 'table.el)
20094 (org-edit-table.el)
20095 (call-interactively 'org-table-edit-formulas)))
20096 ;; Only Org tables contain `table-row' type elements.
20097 (`table-row (call-interactively 'org-table-edit-formulas))
20098 (`example-block (org-edit-src-code))
20099 (`export-block (org-edit-export-block))
20100 (`fixed-width (org-edit-fixed-width-region))
20101 (`latex-environment (org-edit-latex-environment))
20103 ;; No notable element at point. Though, we may be at a link or
20104 ;; a footnote reference, which are objects. Thus, scan deeper.
20105 (let ((context (org-element-context element)))
20106 (pcase (org-element-type context)
20107 (`footnote-reference (org-edit-footnote-reference))
20108 (`inline-src-block (org-edit-inline-src-code))
20109 (`link (call-interactively #'ffap))
20110 (_ (user-error "No special environment to edit here"))))))))
20112 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20113 (defun org-ctrl-c-ctrl-c (&optional arg)
20114 "Set tags in headline, or update according to changed information at point.
20116 This command does many different things, depending on context:
20118 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20119 this is what we do.
20121 - If the cursor is on a statistics cookie, update it.
20123 - If the cursor is in a headline, prompt for tags and insert them
20124 into the current line, aligned to `org-tags-column'. When called
20125 with prefix arg, realign all tags in the current buffer.
20127 - If the cursor is in one of the special #+KEYWORD lines, this
20128 triggers scanning the buffer for these lines and updating the
20129 information.
20131 - If the cursor is inside a table, realign the table. This command
20132 works even if the automatic table editor has been turned off.
20134 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20135 the entire table.
20137 - If the cursor is at a footnote reference or definition, jump to
20138 the corresponding definition or references, respectively.
20140 - If the cursor is a the beginning of a dynamic block, update it.
20142 - If the current buffer is a capture buffer, close note and file it.
20144 - If the cursor is on a <<<target>>>, update radio targets and
20145 corresponding links in this buffer.
20147 - If the cursor is on a numbered item in a plain list, renumber the
20148 ordered list.
20150 - If the cursor is on a checkbox, toggle it.
20152 - If the cursor is on a code block, evaluate it. The variable
20153 `org-confirm-babel-evaluate' can be used to control prompting
20154 before code block evaluation, by default every code block
20155 evaluation requires confirmation. Code block evaluation can be
20156 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20157 (interactive "P")
20158 (cond
20159 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20160 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20161 (org-remove-occur-highlights)
20162 (message "Temporary highlights/overlays removed from current buffer"))
20163 ((and (local-variable-p 'org-finish-function)
20164 (fboundp org-finish-function))
20165 (funcall org-finish-function))
20166 ((org-babel-hash-at-point))
20167 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20169 (let* ((context
20170 (org-element-lineage
20171 (org-element-context)
20172 ;; Limit to supported contexts.
20173 '(babel-call clock dynamic-block footnote-definition
20174 footnote-reference inline-babel-call inline-src-block
20175 inlinetask item keyword node-property paragraph
20176 plain-list planning property-drawer radio-target
20177 src-block statistics-cookie table table-cell table-row
20178 timestamp)
20180 (type (org-element-type context)))
20181 ;; For convenience: at the first line of a paragraph on the same
20182 ;; line as an item, apply function on that item instead.
20183 (when (eq type 'paragraph)
20184 (let ((parent (org-element-property :parent context)))
20185 (when (and (eq (org-element-type parent) 'item)
20186 (= (line-beginning-position)
20187 (org-element-property :begin parent)))
20188 (setq context parent)
20189 (setq type 'item))))
20190 ;; Act according to type of element or object at point.
20192 ;; Do nothing on a blank line, except if it is contained in
20193 ;; a src block. Hence, we first check if point is in such
20194 ;; a block and then if it is at a blank line.
20195 (pcase type
20196 ((or `inline-src-block `src-block)
20197 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20198 (org-babel-eval-wipe-error-buffer)
20199 (org-babel-execute-src-block
20200 current-prefix-arg (org-babel-get-src-block-info nil context))))
20201 ((guard (org-match-line "[ \t]*$"))
20202 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20203 (user-error
20204 (substitute-command-keys
20205 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20206 ((or `babel-call `inline-babel-call)
20207 (let ((info (org-babel-lob-get-info context)))
20208 (when info (org-babel-execute-src-block nil info))))
20209 (`clock (org-clock-update-time-maybe))
20210 (`dynamic-block
20211 (save-excursion
20212 (goto-char (org-element-property :post-affiliated context))
20213 (org-update-dblock)))
20214 (`footnote-definition
20215 (goto-char (org-element-property :post-affiliated context))
20216 (call-interactively 'org-footnote-action))
20217 (`footnote-reference (call-interactively #'org-footnote-action))
20218 ((or `headline `inlinetask)
20219 (save-excursion (goto-char (org-element-property :begin context))
20220 (call-interactively #'org-set-tags-command)))
20221 (`item
20222 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20223 ;; unconditionally, whereas `C-u' will toggle its presence.
20224 ;; Without a universal argument, if the item has a checkbox,
20225 ;; toggle it. Otherwise repair the list.
20226 (let* ((box (org-element-property :checkbox context))
20227 (struct (org-element-property :structure context))
20228 (old-struct (copy-tree struct))
20229 (parents (org-list-parents-alist struct))
20230 (prevs (org-list-prevs-alist struct))
20231 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20232 (org-list-set-checkbox
20233 (org-element-property :begin context) struct
20234 (cond ((equal arg '(16)) "[-]")
20235 ((and (not box) (equal arg '(4))) "[ ]")
20236 ((or (not box) (equal arg '(4))) nil)
20237 ((eq box 'on) "[ ]")
20238 (t "[X]")))
20239 ;; Mimic `org-list-write-struct' but with grabbing a return
20240 ;; value from `org-list-struct-fix-box'.
20241 (org-list-struct-fix-ind struct parents 2)
20242 (org-list-struct-fix-item-end struct)
20243 (org-list-struct-fix-bul struct prevs)
20244 (org-list-struct-fix-ind struct parents)
20245 (let ((block-item
20246 (org-list-struct-fix-box struct parents prevs orderedp)))
20247 (if (and box (equal struct old-struct))
20248 (if (equal arg '(16))
20249 (message "Checkboxes already reset")
20250 (user-error "Cannot toggle this checkbox: %s"
20251 (if (eq box 'on)
20252 "all subitems checked"
20253 "unchecked subitems")))
20254 (org-list-struct-apply-struct struct old-struct)
20255 (org-update-checkbox-count-maybe))
20256 (when block-item
20257 (message "Checkboxes were removed due to empty box at line %d"
20258 (org-current-line block-item))))))
20259 (`keyword
20260 (let ((org-inhibit-startup-visibility-stuff t)
20261 (org-startup-align-all-tables nil))
20262 (when (boundp 'org-table-coordinate-overlays)
20263 (mapc #'delete-overlay org-table-coordinate-overlays)
20264 (setq org-table-coordinate-overlays nil))
20265 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20266 (message "Local setup has been refreshed"))
20267 (`plain-list
20268 ;; At a plain list, with a double C-u argument, set
20269 ;; checkboxes of each item to "[-]", whereas a single one
20270 ;; will toggle their presence according to the state of the
20271 ;; first item in the list. Without an argument, repair the
20272 ;; list.
20273 (let* ((begin (org-element-property :contents-begin context))
20274 (struct (org-element-property :structure context))
20275 (old-struct (copy-tree struct))
20276 (first-box (save-excursion
20277 (goto-char begin)
20278 (looking-at org-list-full-item-re)
20279 (match-string-no-properties 3)))
20280 (new-box (cond ((equal arg '(16)) "[-]")
20281 ((equal arg '(4)) (unless first-box "[ ]"))
20282 ((equal first-box "[X]") "[ ]")
20283 (t "[X]"))))
20284 (cond
20285 (arg
20286 (dolist (pos
20287 (org-list-get-all-items
20288 begin struct (org-list-prevs-alist struct)))
20289 (org-list-set-checkbox pos struct new-box)))
20290 ((and first-box (eq (point) begin))
20291 ;; For convenience, when point is at bol on the first
20292 ;; item of the list and no argument is provided, simply
20293 ;; toggle checkbox of that item, if any.
20294 (org-list-set-checkbox begin struct new-box)))
20295 (org-list-write-struct
20296 struct (org-list-parents-alist struct) old-struct)
20297 (org-update-checkbox-count-maybe)))
20298 ((or `property-drawer `node-property)
20299 (call-interactively #'org-property-action))
20300 (`radio-target
20301 (call-interactively #'org-update-radio-target-regexp))
20302 (`statistics-cookie
20303 (call-interactively #'org-update-statistics-cookies))
20304 ((or `table `table-cell `table-row)
20305 ;; At a table, recalculate every field and align it. Also
20306 ;; send the table if necessary. If the table has
20307 ;; a `table.el' type, just give up. At a table row or cell,
20308 ;; maybe recalculate line but always align table.
20309 (if (eq (org-element-property :type context) 'table.el)
20310 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20311 Use `\\[org-edit-special]' to edit table.el tables"))
20312 (if (or (eq type 'table)
20313 ;; Check if point is at a TBLFM line.
20314 (and (eq type 'table-row)
20315 (= (point) (org-element-property :end context))))
20316 (save-excursion
20317 (if (org-at-TBLFM-p)
20318 (progn (require 'org-table)
20319 (org-table-calc-current-TBLFM))
20320 (goto-char (org-element-property :contents-begin context))
20321 (org-call-with-arg 'org-table-recalculate (or arg t))
20322 (orgtbl-send-table 'maybe)))
20323 (org-table-maybe-eval-formula)
20324 (cond (arg (call-interactively #'org-table-recalculate))
20325 ((org-table-maybe-recalculate-line))
20326 (t (org-table-align))))))
20327 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20328 (org-timestamp-change 0 'day))
20329 ((and `nil (guard (org-at-heading-p)))
20330 ;; When point is on an unsupported object type, we can miss
20331 ;; the fact that it also is at a heading. Handle it here.
20332 (call-interactively #'org-set-tags-command))
20333 ((guard
20334 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20336 (user-error
20337 (substitute-command-keys
20338 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20340 (defun org-mode-restart ()
20341 (interactive)
20342 (let ((indent-status (bound-and-true-p org-indent-mode)))
20343 (funcall major-mode)
20344 (hack-local-variables)
20345 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20346 (org-indent-mode -1))
20347 (org-reset-file-cache))
20348 (message "%s restarted" major-mode))
20350 (defun org-kill-note-or-show-branches ()
20351 "Abort storing current note, or call `outline-show-branches'."
20352 (interactive)
20353 (if (not org-finish-function)
20354 (save-excursion
20355 (save-restriction
20356 (org-narrow-to-subtree)
20357 (org-flag-subtree t)
20358 (call-interactively 'outline-show-branches)
20359 (org-hide-archived-subtrees (point-min) (point-max))))
20360 (let ((org-note-abort t))
20361 (funcall org-finish-function))))
20363 (defun org-delete-indentation (&optional arg)
20364 "Join current line to previous and fix whitespace at join.
20366 If previous line is a headline add to headline title. Otherwise
20367 the function calls `delete-indentation'.
20369 With a non-nil optional argument, join it to the following one."
20370 (interactive "*P")
20371 (if (save-excursion
20372 (beginning-of-line (if arg 1 0))
20373 (let ((case-fold-search nil))
20374 (looking-at org-complex-heading-regexp)))
20375 ;; At headline.
20376 (let ((tags-column (when (match-beginning 5)
20377 (save-excursion (goto-char (match-beginning 5))
20378 (current-column))))
20379 (string (concat " " (progn (when arg (forward-line 1))
20380 (org-trim (delete-and-extract-region
20381 (line-beginning-position)
20382 (line-end-position)))))))
20383 (unless (bobp) (delete-region (point) (1- (point))))
20384 (goto-char (or (match-end 4)
20385 (match-beginning 5)
20386 (match-end 0)))
20387 (skip-chars-backward " \t")
20388 (save-excursion (insert string))
20389 ;; Adjust alignment of tags.
20390 (cond
20391 ((not tags-column)) ;no tags
20392 (org-auto-align-tags (org-align-tags))
20393 (t (org--align-tags-here tags-column)))) ;preserve tags column
20394 (delete-indentation arg)))
20396 (defun org-open-line (n)
20397 "Insert a new row in tables, call `open-line' elsewhere.
20398 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20399 As a special case, when a document starts with a table, allow to
20400 call `open-line' on the very first character."
20401 (interactive "*p")
20402 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20403 (org-table-insert-row)
20404 (open-line n)))
20406 (defun org-return (&optional indent)
20407 "Goto next table row or insert a newline.
20409 Calls `org-table-next-row' or `newline', depending on context.
20411 When optional INDENT argument is non-nil, call
20412 `newline-and-indent' instead of `newline'.
20414 When `org-return-follows-link' is non-nil and point is on
20415 a timestamp or a link, call `org-open-at-point'. However, it
20416 will not happen if point is in a table or on a \"dead\"
20417 object (e.g., within a comment). In these case, you need to use
20418 `org-open-at-point' directly."
20419 (interactive)
20420 (let ((context (if org-return-follows-link (org-element-context)
20421 (org-element-at-point))))
20422 (cond
20423 ;; In a table, call `org-table-next-row'. However, before first
20424 ;; column or after last one, split the table.
20425 ((or (and (eq (org-element-type context) 'table)
20426 (>= (point) (org-element-property :contents-begin context))
20427 (< (point) (org-element-property :contents-end context)))
20428 (org-element-lineage context '(table-row table-cell) t))
20429 (if (or (looking-at-p "[ \t]*$")
20430 (save-excursion (skip-chars-backward " \t") (bolp)))
20431 (insert "\n")
20432 (org-table-justify-field-maybe)
20433 (call-interactively #'org-table-next-row)))
20434 ;; On a link or a timestamp, call `org-open-at-point' if
20435 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20436 ;; locations, e.g., in a comment, as `org-open-at-point'.
20437 ((and org-return-follows-link
20438 (or (and (eq 'link (org-element-type context))
20439 ;; Ensure point is not on the white spaces after
20440 ;; the link.
20441 (let ((origin (point)))
20442 (org-with-point-at (org-element-property :end context)
20443 (skip-chars-backward " \t")
20444 (> (point) origin))))
20445 (org-in-regexp org-ts-regexp-both nil t)
20446 (org-in-regexp org-tsr-regexp-both nil t)
20447 (org-in-regexp org-any-link-re nil t)))
20448 (call-interactively #'org-open-at-point))
20449 ;; Insert newline in heading, but preserve tags.
20450 ((and (not (bolp))
20451 (save-excursion (beginning-of-line)
20452 (let ((case-fold-search nil))
20453 (looking-at org-complex-heading-regexp))))
20454 ;; At headline. Split line. However, if point is on keyword,
20455 ;; priority cookie or tags, do not break any of them: add
20456 ;; a newline after the headline instead.
20457 (let ((tags-column (and (match-beginning 5)
20458 (save-excursion (goto-char (match-beginning 5))
20459 (current-column))))
20460 (string
20461 (when (and (match-end 4) (org-point-in-group (point) 4))
20462 (delete-and-extract-region (point) (match-end 4)))))
20463 ;; Adjust tag alignment.
20464 (cond
20465 ((not (and tags-column string)))
20466 (org-auto-align-tags (org-align-tags))
20467 (t (org--align-tags-here tags-column))) ;preserve tags column
20468 (end-of-line)
20469 (org-show-entry)
20470 (if indent (newline-and-indent) (newline))
20471 (when string (save-excursion (insert (org-trim string))))))
20472 ;; In a list, make sure indenting keeps trailing text within.
20473 ((and indent
20474 (not (eolp))
20475 (org-element-lineage context '(item)))
20476 (let ((trailing-data
20477 (delete-and-extract-region (point) (line-end-position))))
20478 (newline-and-indent)
20479 (save-excursion (insert trailing-data))))
20481 ;; Do not auto-fill when point is in an Org property drawer.
20482 (let ((auto-fill-function (and (not (org-at-property-p))
20483 auto-fill-function)))
20484 (if indent
20485 (newline-and-indent)
20486 (newline)))))))
20488 (defun org-return-indent ()
20489 "Goto next table row or insert a newline and indent.
20490 Calls `org-table-next-row' or `newline-and-indent', depending on
20491 context. See the individual commands for more information."
20492 (interactive)
20493 (org-return t))
20495 (defun org-ctrl-c-tab (&optional _arg)
20496 "Toggle columns width in a table, or show children.
20497 Call `org-table-toggle-column-width' if point is in a table.
20498 Otherwise, call `org-show-children'."
20499 (interactive "p")
20500 (call-interactively
20501 (if (org-at-table-p) #'org-table-toggle-column-width
20502 #'org-show-children)))
20504 (defun org-ctrl-c-star ()
20505 "Compute table, or change heading status of lines.
20506 Calls `org-table-recalculate' or `org-toggle-heading',
20507 depending on context."
20508 (interactive)
20509 (cond
20510 ((org-at-table-p)
20511 (call-interactively 'org-table-recalculate))
20513 ;; Convert all lines in region to list items
20514 (call-interactively 'org-toggle-heading))))
20516 (defun org-ctrl-c-minus ()
20517 "Insert separator line in table or modify bullet status of line.
20518 Also turns a plain line or a region of lines into list items.
20519 Calls `org-table-insert-hline', `org-toggle-item', or
20520 `org-cycle-list-bullet', depending on context."
20521 (interactive)
20522 (cond
20523 ((org-at-table-p)
20524 (call-interactively 'org-table-insert-hline))
20525 ((org-region-active-p)
20526 (call-interactively 'org-toggle-item))
20527 ((org-in-item-p)
20528 (call-interactively 'org-cycle-list-bullet))
20530 (call-interactively 'org-toggle-item))))
20532 (defun org-toggle-heading (&optional nstars)
20533 "Convert headings to normal text, or items or text to headings.
20534 If there is no active region, only convert the current line.
20536 With a `\\[universal-argument]' prefix, convert the whole list at
20537 point into heading.
20539 In a region:
20541 - If the first non blank line is a headline, remove the stars
20542 from all headlines in the region.
20544 - If it is a normal line, turn each and every normal line (i.e.,
20545 not an heading or an item) in the region into headings. If you
20546 want to convert only the first line of this region, use one
20547 universal prefix argument.
20549 - If it is a plain list item, turn all plain list items into headings.
20551 When converting a line into a heading, the number of stars is chosen
20552 such that the lines become children of the current entry. However,
20553 when a numeric prefix argument is given, its value determines the
20554 number of stars to add."
20555 (interactive "P")
20556 (let ((skip-blanks
20557 (function
20558 ;; Return beginning of first non-blank line, starting from
20559 ;; line at POS.
20560 (lambda (pos)
20561 (save-excursion
20562 (goto-char pos)
20563 (while (org-at-comment-p) (forward-line))
20564 (skip-chars-forward " \r\t\n")
20565 (point-at-bol)))))
20566 beg end toggled)
20567 ;; Determine boundaries of changes. If a universal prefix has
20568 ;; been given, put the list in a region. If region ends at a bol,
20569 ;; do not consider the last line to be in the region.
20571 (when (and current-prefix-arg (org-at-item-p))
20572 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20573 (org-mark-element))
20575 (if (org-region-active-p)
20576 (setq beg (funcall skip-blanks (region-beginning))
20577 end (copy-marker (save-excursion
20578 (goto-char (region-end))
20579 (if (bolp) (point) (point-at-eol)))))
20580 (setq beg (funcall skip-blanks (point-at-bol))
20581 end (copy-marker (point-at-eol))))
20582 ;; Ensure inline tasks don't count as headings.
20583 (org-with-limited-levels
20584 (save-excursion
20585 (goto-char beg)
20586 (cond
20587 ;; Case 1. Started at an heading: de-star headings.
20588 ((org-at-heading-p)
20589 (while (< (point) end)
20590 (when (org-at-heading-p t)
20591 (looking-at org-outline-regexp) (replace-match "")
20592 (setq toggled t))
20593 (forward-line)))
20594 ;; Case 2. Started at an item: change items into headlines.
20595 ;; One star will be added by `org-list-to-subtree'.
20596 ((org-at-item-p)
20597 (while (< (point) end)
20598 (when (org-at-item-p)
20599 ;; Pay attention to cases when region ends before list.
20600 (let* ((struct (org-list-struct))
20601 (list-end
20602 (min (org-list-get-bottom-point struct) (1+ end))))
20603 (save-restriction
20604 (narrow-to-region (point) list-end)
20605 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20606 (setq toggled t))
20607 (forward-line)))
20608 ;; Case 3. Started at normal text: make every line an heading,
20609 ;; skipping headlines and items.
20610 (t (let* ((stars
20611 (make-string
20612 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20613 (add-stars
20614 (cond (nstars "") ; stars from prefix only
20615 ((equal stars "") "*") ; before first heading
20616 (org-odd-levels-only "**") ; inside heading, odd
20617 (t "*"))) ; inside heading, oddeven
20618 (rpl (concat stars add-stars " "))
20619 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20620 (while (< (point) (if (equal nstars '(4)) lend end))
20621 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20622 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20623 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20624 (forward-line)))))))
20625 (unless toggled (message "Cannot toggle heading from here"))))
20627 (defun org-meta-return (&optional arg)
20628 "Insert a new heading or wrap a region in a table.
20629 Calls `org-insert-heading', `org-insert-item' or
20630 `org-table-wrap-region', depending on context. When called with
20631 an argument, unconditionally call `org-insert-heading'."
20632 (interactive "P")
20633 (org-check-before-invisible-edit 'insert)
20634 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20635 (call-interactively (cond (arg #'org-insert-heading)
20636 ((org-at-table-p) #'org-table-wrap-region)
20637 ((org-in-item-p) #'org-insert-item)
20638 (t #'org-insert-heading)))))
20640 ;;; Menu entries
20642 (defsubst org-in-subtree-not-table-p ()
20643 "Are we in a subtree and not in a table?"
20644 (and (not (org-before-first-heading-p))
20645 (not (org-at-table-p))))
20647 ;; Define the Org mode menus
20648 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20649 '("Tbl"
20650 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20651 ["Next Field" org-cycle (org-at-table-p)]
20652 ["Previous Field" org-shifttab (org-at-table-p)]
20653 ["Next Row" org-return (org-at-table-p)]
20654 "--"
20655 ["Blank Field" org-table-blank-field (org-at-table-p)]
20656 ["Edit Field" org-table-edit-field (org-at-table-p)]
20657 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20658 "--"
20659 ("Column"
20660 ["Move Column Left" org-metaleft (org-at-table-p)]
20661 ["Move Column Right" org-metaright (org-at-table-p)]
20662 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20663 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20664 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20665 ("Row"
20666 ["Move Row Up" org-metaup (org-at-table-p)]
20667 ["Move Row Down" org-metadown (org-at-table-p)]
20668 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20669 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20670 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20671 "--"
20672 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20673 ("Rectangle"
20674 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20675 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20676 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20677 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20678 "--"
20679 ("Calculate"
20680 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20681 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20682 ["Edit Formulas" org-edit-special (org-at-table-p)]
20683 "--"
20684 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20685 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20686 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20687 "--"
20688 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20689 "--"
20690 ["Sum Column/Rectangle" org-table-sum
20691 (or (org-at-table-p) (org-region-active-p))]
20692 ["Which Column?" org-table-current-column (org-at-table-p)])
20693 ["Debug Formulas"
20694 org-table-toggle-formula-debugger
20695 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20696 ["Show Col/Row Numbers"
20697 org-table-toggle-coordinate-overlays
20698 :style toggle
20699 :selected (bound-and-true-p org-table-overlay-coordinates)]
20700 "--"
20701 ["Create" org-table-create (not (org-at-table-p))]
20702 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20703 ["Import from File" org-table-import (not (org-at-table-p))]
20704 ["Export to File" org-table-export (org-at-table-p)]
20705 "--"
20706 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20707 "--"
20708 ("Plot"
20709 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20710 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20712 (easy-menu-define org-org-menu org-mode-map "Org menu"
20713 '("Org"
20714 ("Show/Hide"
20715 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20716 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20717 ["Sparse Tree..." org-sparse-tree t]
20718 ["Reveal Context" org-reveal t]
20719 ["Show All" org-show-all t]
20720 "--"
20721 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20722 "--"
20723 ["New Heading" org-insert-heading t]
20724 ("Navigate Headings"
20725 ["Up" outline-up-heading t]
20726 ["Next" outline-next-visible-heading t]
20727 ["Previous" outline-previous-visible-heading t]
20728 ["Next Same Level" outline-forward-same-level t]
20729 ["Previous Same Level" outline-backward-same-level t]
20730 "--"
20731 ["Jump" org-goto t])
20732 ("Edit Structure"
20733 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20734 "--"
20735 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20736 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20737 "--"
20738 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20739 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20740 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20741 "--"
20742 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20743 "--"
20744 ["Copy visible text" org-copy-visible t]
20745 "--"
20746 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20747 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20748 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20749 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20750 "--"
20751 ["Sort Region/Children" org-sort t]
20752 "--"
20753 ["Convert to odd levels" org-convert-to-odd-levels t]
20754 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20755 ("Editing"
20756 ["Emphasis..." org-emphasize t]
20757 ["Edit Source Example" org-edit-special t]
20758 "--"
20759 ["Footnote new/jump" org-footnote-action t]
20760 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20761 ("Archive"
20762 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20763 "--"
20764 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20765 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20766 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20768 "--"
20769 ("Hyperlinks"
20770 ["Store Link (Global)" org-store-link t]
20771 ["Find existing link to here" org-occur-link-in-agenda-files t]
20772 ["Insert Link" org-insert-link t]
20773 ["Follow Link" org-open-at-point t]
20774 "--"
20775 ["Next link" org-next-link t]
20776 ["Previous link" org-previous-link t]
20777 "--"
20778 ["Descriptive Links"
20779 org-toggle-link-display
20780 :style radio
20781 :selected org-descriptive-links
20783 ["Literal Links"
20784 org-toggle-link-display
20785 :style radio
20786 :selected (not org-descriptive-links)])
20787 "--"
20788 ("TODO Lists"
20789 ["TODO/DONE/-" org-todo t]
20790 ("Select keyword"
20791 ["Next keyword" org-shiftright (org-at-heading-p)]
20792 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20793 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20794 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20795 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20796 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20797 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20798 "--"
20799 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20800 :selected org-enforce-todo-dependencies :style toggle :active t]
20801 "Settings for tree at point"
20802 ["Do Children sequentially" org-toggle-ordered-property :style radio
20803 :selected (org-entry-get nil "ORDERED")
20804 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20805 ["Do Children parallel" org-toggle-ordered-property :style radio
20806 :selected (not (org-entry-get nil "ORDERED"))
20807 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20808 "--"
20809 ["Set Priority" org-priority t]
20810 ["Priority Up" org-shiftup t]
20811 ["Priority Down" org-shiftdown t]
20812 "--"
20813 ["Get news from all feeds" org-feed-update-all t]
20814 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20815 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20816 ("TAGS and Properties"
20817 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20818 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20819 "--"
20820 ["Set property" org-set-property (not (org-before-first-heading-p))]
20821 ["Column view of properties" org-columns t]
20822 ["Insert Column View DBlock" org-columns-insert-dblock t])
20823 ("Dates and Scheduling"
20824 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20825 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20826 ("Change Date"
20827 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20828 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20829 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20830 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20831 ["Compute Time Range" org-evaluate-time-range t]
20832 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20833 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20834 "--"
20835 ["Custom time format" org-toggle-time-stamp-overlays
20836 :style radio :selected org-display-custom-times]
20837 "--"
20838 ["Goto Calendar" org-goto-calendar t]
20839 ["Date from Calendar" org-date-from-calendar t]
20840 "--"
20841 ["Start/Restart Timer" org-timer-start t]
20842 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20843 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20844 ["Insert Timer String" org-timer t]
20845 ["Insert Timer Item" org-timer-item t])
20846 ("Logging work"
20847 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20848 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20849 ["Clock out" org-clock-out t]
20850 ["Clock cancel" org-clock-cancel t]
20851 "--"
20852 ["Mark as default task" org-clock-mark-default-task t]
20853 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20854 ["Goto running clock" org-clock-goto t]
20855 "--"
20856 ["Display times" org-clock-display t]
20857 ["Create clock table" org-clock-report t]
20858 "--"
20859 ["Record DONE time"
20860 (progn (setq org-log-done (not org-log-done))
20861 (message "Switching to %s will %s record a timestamp"
20862 (car org-done-keywords)
20863 (if org-log-done "automatically" "not")))
20864 :style toggle :selected org-log-done])
20865 "--"
20866 ["Agenda Command..." org-agenda t]
20867 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20868 ("File List for Agenda")
20869 ("Special views current file"
20870 ["TODO Tree" org-show-todo-tree t]
20871 ["Check Deadlines" org-check-deadlines t]
20872 ["Tags/Property tree" org-match-sparse-tree t])
20873 "--"
20874 ["Export/Publish..." org-export-dispatch t]
20875 ("LaTeX"
20876 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20877 :style toggle :selected org-cdlatex-mode]
20878 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20879 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20880 ["Modify math symbol" org-cdlatex-math-modify
20881 (org-inside-LaTeX-fragment-p)]
20882 ["Insert citation" org-reftex-citation t])
20883 "--"
20884 ("MobileOrg"
20885 ["Push Files and Views" org-mobile-push t]
20886 ["Get Captured and Flagged" org-mobile-pull t]
20887 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20888 "--"
20889 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20890 "--"
20891 ("Documentation"
20892 ["Show Version" org-version t]
20893 ["Info Documentation" org-info t])
20894 ("Customize"
20895 ["Browse Org Group" org-customize t]
20896 "--"
20897 ["Expand This Menu" org-create-customize-menu
20898 (fboundp 'customize-menu-create)])
20899 ["Send bug report" org-submit-bug-report t]
20900 "--"
20901 ("Refresh/Reload"
20902 ["Refresh setup current buffer" org-mode-restart t]
20903 ["Reload Org (after update)" org-reload t]
20904 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20907 (defun org-info (&optional node)
20908 "Read documentation for Org in the info system.
20909 With optional NODE, go directly to that node."
20910 (interactive)
20911 (info (format "(org)%s" (or node ""))))
20913 ;;;###autoload
20914 (defun org-submit-bug-report ()
20915 "Submit a bug report on Org via mail.
20917 Don't hesitate to report any problems or inaccurate documentation.
20919 If you don't have setup sending mail from (X)Emacs, please copy the
20920 output buffer into your mail program, as it gives us important
20921 information about your Org version and configuration."
20922 (interactive)
20923 (require 'reporter)
20924 (defvar reporter-prompt-for-summary-p)
20925 (org-load-modules-maybe)
20926 (org-require-autoloaded-modules)
20927 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20928 (reporter-submit-bug-report
20929 "emacs-orgmode@gnu.org"
20930 (org-version nil 'full)
20931 (let (list)
20932 (save-window-excursion
20933 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20934 (delete-other-windows)
20935 (erase-buffer)
20936 (insert "You are about to submit a bug report to the Org mailing list.
20938 We would like to add your full Org and Outline configuration to the
20939 bug report. This greatly simplifies the work of the maintainer and
20940 other experts on the mailing list.
20942 HOWEVER, some variables you have customized may contain private
20943 information. The names of customers, colleagues, or friends, might
20944 appear in the form of file names, tags, todo states, or search strings.
20945 If you answer yes to the prompt, you might want to check and remove
20946 such private information before sending the email.")
20947 (add-text-properties (point-min) (point-max) '(face org-warning))
20948 (when (yes-or-no-p "Include your Org configuration ")
20949 (mapatoms
20950 (lambda (v)
20951 (and (boundp v)
20952 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20953 (or (and (symbol-value v)
20954 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20955 (and
20956 (get v 'custom-type) (get v 'standard-value)
20957 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20958 (push v list)))))
20959 (kill-buffer (get-buffer "*Warn about privacy*"))
20960 list))
20961 nil nil
20962 "Remember to cover the basics, that is, what you expected to happen and
20963 what in fact did happen. You don't know how to make a good report? See
20965 https://orgmode.org/manual/Feedback.html#Feedback
20967 Your bug report will be posted to the Org mailing list.
20968 ------------------------------------------------------------------------")
20969 (save-excursion
20970 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20971 (replace-match "\\1Bug: \\3 [\\2]")))))
20974 (defun org-install-agenda-files-menu ()
20975 (let ((bl (buffer-list)))
20976 (save-excursion
20977 (while bl
20978 (set-buffer (pop bl))
20979 (when (derived-mode-p 'org-mode) (setq bl nil)))
20980 (when (derived-mode-p 'org-mode)
20981 (easy-menu-change
20982 '("Org") "File List for Agenda"
20983 (append
20984 (list
20985 ["Edit File List" (org-edit-agenda-file-list) t]
20986 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20987 ["Remove Current File from List" org-remove-file t]
20988 ["Cycle through agenda files" org-cycle-agenda-files t]
20989 ["Occur in all agenda files" org-occur-in-agenda-files t]
20990 "--")
20991 (mapcar 'org-file-menu-entry
20992 ;; Prevent initialization from failing.
20993 (ignore-errors (org-agenda-files t)))))))))
20995 ;;;; Documentation
20997 (defun org-require-autoloaded-modules ()
20998 (interactive)
20999 (mapc #'require
21000 '(org-agenda org-archive org-attach org-clock org-colview org-id
21001 org-table org-timer)))
21003 ;;;###autoload
21004 (defun org-reload (&optional uncompiled)
21005 "Reload all Org Lisp files.
21006 With prefix arg UNCOMPILED, load the uncompiled versions."
21007 (interactive "P")
21008 (require 'loadhist)
21009 (let* ((org-dir (org-find-library-dir "org"))
21010 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21011 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21012 (remove-re (format "\\`%s\\'"
21013 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21014 (feats (delete-dups
21015 (mapcar 'file-name-sans-extension
21016 (mapcar 'file-name-nondirectory
21017 (delq nil
21018 (mapcar 'feature-file
21019 features))))))
21020 (lfeat (append
21021 (sort
21022 (setq feats
21023 (delq nil (mapcar
21024 (lambda (f)
21025 (if (and (string-match feature-re f)
21026 (not (string-match remove-re f)))
21027 f nil))
21028 feats)))
21029 'string-lessp)
21030 (list "org-version" "org")))
21031 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21032 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21033 load-uncore load-misses)
21034 (setq load-misses
21035 (delq 't
21036 (mapcar (lambda (f)
21037 (or (org-load-noerror-mustsuffix (concat org-dir f))
21038 (and (string= org-dir contrib-dir)
21039 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21040 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21041 (add-to-list 'load-uncore f 'append)
21044 lfeat)))
21045 (when load-uncore
21046 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21047 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21048 (if load-misses
21049 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21050 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21051 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21053 ;;;###autoload
21054 (defun org-customize ()
21055 "Call the customize function with org as argument."
21056 (interactive)
21057 (org-load-modules-maybe)
21058 (org-require-autoloaded-modules)
21059 (customize-browse 'org))
21061 (defun org-create-customize-menu ()
21062 "Create a full customization menu for Org mode, insert it into the menu."
21063 (interactive)
21064 (org-load-modules-maybe)
21065 (org-require-autoloaded-modules)
21066 (if (fboundp 'customize-menu-create)
21067 (progn
21068 (easy-menu-change
21069 '("Org") "Customize"
21070 `(["Browse Org group" org-customize t]
21071 "--"
21072 ,(customize-menu-create 'org)
21073 ["Set" Custom-set t]
21074 ["Save" Custom-save t]
21075 ["Reset to Current" Custom-reset-current t]
21076 ["Reset to Saved" Custom-reset-saved t]
21077 ["Reset to Standard Settings" Custom-reset-standard t]))
21078 (message "\"Org\"-menu now contains full customization menu"))
21079 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21081 ;;;; Miscellaneous stuff
21083 ;;; Generally useful functions
21085 (defun org-link-display-format (s)
21086 "Replace links in string S with their description.
21087 If there is no description, use the link target."
21088 (save-match-data
21089 (replace-regexp-in-string
21090 org-bracket-link-analytic-regexp
21091 (lambda (m)
21092 (if (match-end 5) (match-string 5 m)
21093 (concat (match-string 1 m) (match-string 3 m))))
21094 s nil t)))
21096 (defun org-toggle-link-display ()
21097 "Toggle the literal or descriptive display of links."
21098 (interactive)
21099 (if org-descriptive-links
21100 (progn (org-remove-from-invisibility-spec '(org-link))
21101 (org-restart-font-lock)
21102 (setq org-descriptive-links nil))
21103 (progn (add-to-invisibility-spec '(org-link))
21104 (org-restart-font-lock)
21105 (setq org-descriptive-links t))))
21107 (defun org-in-clocktable-p ()
21108 "Check if the cursor is in a clocktable."
21109 (let ((pos (point)) start)
21110 (save-excursion
21111 (end-of-line 1)
21112 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21113 (setq start (match-beginning 0))
21114 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21115 (>= (match-end 0) pos)
21116 start))))
21118 (defun org-in-verbatim-emphasis ()
21119 (save-match-data
21120 (and (org-in-regexp org-verbatim-re 2)
21121 (>= (point) (match-beginning 3))
21122 (<= (point) (match-end 4)))))
21124 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21125 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21126 (if (and marker (marker-buffer marker)
21127 (buffer-live-p (marker-buffer marker)))
21128 (progn
21129 (pop-to-buffer-same-window (marker-buffer marker))
21130 (when (or (> marker (point-max)) (< marker (point-min)))
21131 (widen))
21132 (goto-char marker)
21133 (org-show-context 'org-goto))
21134 (if bookmark
21135 (bookmark-jump bookmark)
21136 (error "Cannot find location"))))
21138 (defun org-quote-csv-field (s)
21139 "Quote field for inclusion in CSV material."
21140 (if (string-match "[\",]" s)
21141 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21144 (defun org-force-self-insert (N)
21145 "Needed to enforce self-insert under remapping."
21146 (interactive "p")
21147 (self-insert-command N))
21149 (defun org-fill-template (template alist)
21150 "Find each %key of ALIST in TEMPLATE and replace it."
21151 (let ((case-fold-search nil))
21152 (dolist (entry (sort (copy-sequence alist)
21153 (lambda (a b) (< (length (car a)) (length (car b))))))
21154 (setq template
21155 (replace-regexp-in-string
21156 (concat "%" (regexp-quote (car entry)))
21157 (or (cdr entry) "") template t t)))
21158 template))
21160 (defun org-quote-vert (s)
21161 "Replace \"|\" with \"\\vert\"."
21162 (while (string-match "|" s)
21163 (setq s (replace-match "\\vert" t t s)))
21166 (defun org-uuidgen-p (s)
21167 "Is S an ID created by UUIDGEN?"
21168 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21170 (defun org-in-src-block-p (&optional inside)
21171 "Whether point is in a code source block.
21172 When INSIDE is non-nil, don't consider we are within a src block
21173 when point is at #+BEGIN_SRC or #+END_SRC."
21174 (let ((case-fold-search t))
21175 (or (and (eq (get-char-property (point) 'src-block) t))
21176 (and (not inside)
21177 (save-match-data
21178 (save-excursion
21179 (beginning-of-line)
21180 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21182 (defun org-context ()
21183 "Return a list of contexts of the current cursor position.
21184 If several contexts apply, all are returned.
21185 Each context entry is a list with a symbol naming the context, and
21186 two positions indicating start and end of the context. Possible
21187 contexts are:
21189 :headline anywhere in a headline
21190 :headline-stars on the leading stars in a headline
21191 :todo-keyword on a TODO keyword (including DONE) in a headline
21192 :tags on the TAGS in a headline
21193 :priority on the priority cookie in a headline
21194 :item on the first line of a plain list item
21195 :item-bullet on the bullet/number of a plain list item
21196 :checkbox on the checkbox in a plain list item
21197 :table in an Org table
21198 :table-special on a special filed in a table
21199 :table-table in a table.el table
21200 :clocktable in a clocktable
21201 :src-block in a source block
21202 :link on a hyperlink
21203 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21204 :target on a <<target>>
21205 :radio-target on a <<<radio-target>>>
21206 :latex-fragment on a LaTeX fragment
21207 :latex-preview on a LaTeX fragment with overlaid preview image
21209 This function expects the position to be visible because it uses font-lock
21210 faces as a help to recognize the following contexts: :table-special, :link,
21211 and :keyword."
21212 (let* ((f (get-text-property (point) 'face))
21213 (faces (if (listp f) f (list f)))
21214 (case-fold-search t)
21215 (p (point)) clist o)
21216 ;; First the large context
21217 (cond
21218 ((org-at-heading-p t)
21219 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21220 (when (progn
21221 (beginning-of-line 1)
21222 (looking-at org-todo-line-tags-regexp))
21223 (push (org-point-in-group p 1 :headline-stars) clist)
21224 (push (org-point-in-group p 2 :todo-keyword) clist)
21225 (push (org-point-in-group p 4 :tags) clist))
21226 (goto-char p)
21227 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21228 (when (looking-at "\\[#[A-Z0-9]\\]")
21229 (push (org-point-in-group p 0 :priority) clist)))
21231 ((org-at-item-p)
21232 (push (org-point-in-group p 2 :item-bullet) clist)
21233 (push (list :item (point-at-bol)
21234 (save-excursion (org-end-of-item) (point)))
21235 clist)
21236 (and (org-at-item-checkbox-p)
21237 (push (org-point-in-group p 0 :checkbox) clist)))
21239 ((org-at-table-p)
21240 (push (list :table (org-table-begin) (org-table-end)) clist)
21241 (when (memq 'org-formula faces)
21242 (push (list :table-special
21243 (previous-single-property-change p 'face)
21244 (next-single-property-change p 'face)) clist)))
21245 ((org-at-table-p 'any)
21246 (push (list :table-table) clist)))
21247 (goto-char p)
21249 (let ((case-fold-search t))
21250 ;; New the "medium" contexts: clocktables, source blocks
21251 (cond ((org-in-clocktable-p)
21252 (push (list :clocktable
21253 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21254 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21255 (match-beginning 1))
21256 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21257 (match-end 0))) clist))
21258 ((org-in-src-block-p)
21259 (push (list :src-block
21260 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21261 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21262 (match-beginning 1))
21263 (and (search-forward "#+END_SRC" nil t)
21264 (match-beginning 0))) clist))))
21265 (goto-char p)
21267 ;; Now the small context
21268 (cond
21269 ((org-at-timestamp-p)
21270 (push (org-point-in-group p 0 :timestamp) clist))
21271 ((memq 'org-link faces)
21272 (push (list :link
21273 (previous-single-property-change p 'face)
21274 (next-single-property-change p 'face)) clist))
21275 ((memq 'org-special-keyword faces)
21276 (push (list :keyword
21277 (previous-single-property-change p 'face)
21278 (next-single-property-change p 'face)) clist))
21279 ((org-at-target-p)
21280 (push (org-point-in-group p 0 :target) clist)
21281 (goto-char (1- (match-beginning 0)))
21282 (when (looking-at org-radio-target-regexp)
21283 (push (org-point-in-group p 0 :radio-target) clist))
21284 (goto-char p))
21285 ((setq o (cl-some
21286 (lambda (o)
21287 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21289 (overlays-at (point))))
21290 (push (list :latex-fragment
21291 (overlay-start o) (overlay-end o)) clist)
21292 (push (list :latex-preview
21293 (overlay-start o) (overlay-end o)) clist))
21294 ((org-inside-LaTeX-fragment-p)
21295 ;; FIXME: positions wrong.
21296 (push (list :latex-fragment (point) (point)) clist)))
21298 (setq clist (nreverse (delq nil clist)))
21299 clist))
21301 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21302 "Non-nil when point is between matches of START-RE and END-RE.
21304 Also return a non-nil value when point is on one of the matches.
21306 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21307 buffer positions. Default values are the positions of headlines
21308 surrounding the point.
21310 The functions returns a cons cell whose car (resp. cdr) is the
21311 position before START-RE (resp. after END-RE)."
21312 (save-match-data
21313 (let ((pos (point))
21314 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21315 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21316 beg end)
21317 (save-excursion
21318 ;; Point is on a block when on START-RE or if START-RE can be
21319 ;; found before it...
21320 (and (or (org-in-regexp start-re)
21321 (re-search-backward start-re limit-up t))
21322 (setq beg (match-beginning 0))
21323 ;; ... and END-RE after it...
21324 (goto-char (match-end 0))
21325 (re-search-forward end-re limit-down t)
21326 (> (setq end (match-end 0)) pos)
21327 ;; ... without another START-RE in-between.
21328 (goto-char (match-beginning 0))
21329 (not (re-search-backward start-re (1+ beg) t))
21330 ;; Return value.
21331 (cons beg end))))))
21333 (defun org-in-block-p (names)
21334 "Non-nil when point belongs to a block whose name belongs to NAMES.
21336 NAMES is a list of strings containing names of blocks.
21338 Return first block name matched, or nil. Beware that in case of
21339 nested blocks, the returned name may not belong to the closest
21340 block from point."
21341 (save-match-data
21342 (catch 'exit
21343 (let ((case-fold-search t)
21344 (lim-up (save-excursion (outline-previous-heading)))
21345 (lim-down (save-excursion (outline-next-heading))))
21346 (dolist (name names)
21347 (let ((n (regexp-quote name)))
21348 (when (org-between-regexps-p
21349 (concat "^[ \t]*#\\+begin_" n)
21350 (concat "^[ \t]*#\\+end_" n)
21351 lim-up lim-down)
21352 (throw 'exit n)))))
21353 nil)))
21355 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21356 "Call `multi-occur' with buffers for all agenda files."
21357 (interactive "sOrg-files matching: ")
21358 (let* ((files (org-agenda-files))
21359 (tnames (mapcar #'file-truename files))
21360 (extra org-agenda-text-search-extra-files))
21361 (when (eq (car extra) 'agenda-archives)
21362 (setq extra (cdr extra))
21363 (setq files (org-add-archive-files files)))
21364 (dolist (f extra)
21365 (unless (member (file-truename f) tnames)
21366 (unless (member f files) (setq files (append files (list f))))
21367 (setq tnames (append tnames (list (file-truename f))))))
21368 (multi-occur
21369 (mapcar (lambda (x)
21370 (with-current-buffer
21371 ;; FIXME: Why not just (find-file-noselect x)?
21372 ;; Is it to avoid the "revert buffer" prompt?
21373 (or (get-file-buffer x) (find-file-noselect x))
21374 (widen)
21375 (current-buffer)))
21376 files)
21377 regexp)))
21379 (add-hook 'occur-mode-find-occurrence-hook
21380 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21382 (defun org-occur-link-in-agenda-files ()
21383 "Create a link and search for it in the agendas.
21384 The link is not stored in `org-stored-links', it is just created
21385 for the search purpose."
21386 (interactive)
21387 (let ((link (condition-case nil
21388 (org-store-link nil)
21389 (error "Unable to create a link to here"))))
21390 (org-occur-in-agenda-files (regexp-quote link))))
21392 (defun org-back-over-empty-lines ()
21393 "Move backwards over whitespace, to the beginning of the first empty line.
21394 Returns the number of empty lines passed."
21395 (let ((pos (point)))
21396 (if (cdr (assq 'heading org-blank-before-new-entry))
21397 (skip-chars-backward " \t\n\r")
21398 (unless (eobp)
21399 (forward-line -1)))
21400 (beginning-of-line 2)
21401 (goto-char (min (point) pos))
21402 (count-lines (point) pos)))
21404 (defun org-switch-to-buffer-other-window (&rest args)
21405 "Switch to buffer in a second window on the current frame.
21406 In particular, do not allow pop-up frames.
21407 Returns the newly created buffer."
21408 (org-no-popups
21409 (apply 'switch-to-buffer-other-window args)))
21411 (defun org-replace-escapes (string table)
21412 "Replace %-escapes in STRING with values in TABLE.
21413 TABLE is an association list with keys like \"%a\" and string values.
21414 The sequences in STRING may contain normal field width and padding information,
21415 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21416 so values can contain further %-escapes if they are define later in TABLE."
21417 (let ((tbl (copy-alist table))
21418 (case-fold-search nil)
21419 (pchg 0)
21420 re rpl)
21421 (dolist (e tbl)
21422 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21423 (when (and (cdr e) (string-match re (cdr e)))
21424 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21425 (safe "SREF"))
21426 (add-text-properties 0 3 (list 'sref sref) safe)
21427 (setcdr e (replace-match safe t t (cdr e)))))
21428 (while (string-match re string)
21429 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21430 (cdr e)))
21431 (setq string (replace-match rpl t t string))))
21432 (while (setq pchg (next-property-change pchg string))
21433 (let ((sref (get-text-property pchg 'sref string)))
21434 (when (and sref (string-match "SREF" string pchg))
21435 (setq string (replace-match sref t t string)))))
21436 string))
21438 ;;; TODO: Only called once, from ox-odt which should probably use
21439 ;;; org-export-inline-image-p or something.
21440 (defun org-file-image-p (file)
21441 "Return non-nil if FILE is an image."
21442 (save-match-data
21443 (string-match (image-file-name-regexp) file)))
21445 (defun org-get-cursor-date (&optional with-time)
21446 "Return the date at cursor in as a time.
21447 This works in the calendar and in the agenda, anywhere else it just
21448 returns the current time.
21449 If WITH-TIME is non-nil, returns the time of the event at point (in
21450 the agenda) or the current time of the day."
21451 (let (date day defd tp hod mod)
21452 (when with-time
21453 (setq tp (get-text-property (point) 'time))
21454 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21455 (setq hod (string-to-number (match-string 1 tp))
21456 mod (string-to-number (match-string 2 tp))))
21457 (or tp (let ((now (decode-time)))
21458 (setq hod (nth 2 now)
21459 mod (nth 1 now)))))
21460 (cond
21461 ((eq major-mode 'calendar-mode)
21462 (setq date (calendar-cursor-to-date)
21463 defd (encode-time 0 (or mod 0) (or hod 0)
21464 (nth 1 date) (nth 0 date) (nth 2 date))))
21465 ((eq major-mode 'org-agenda-mode)
21466 (setq day (get-text-property (point) 'day))
21467 (when day
21468 (setq date (calendar-gregorian-from-absolute day)
21469 defd (encode-time 0 (or mod 0) (or hod 0)
21470 (nth 1 date) (nth 0 date) (nth 2 date))))))
21471 (or defd (current-time))))
21473 (defun org-mark-subtree (&optional up)
21474 "Mark the current subtree.
21475 This puts point at the start of the current subtree, and mark at
21476 the end. If a numeric prefix UP is given, move up into the
21477 hierarchy of headlines by UP levels before marking the subtree."
21478 (interactive "P")
21479 (org-with-limited-levels
21480 (cond ((org-at-heading-p) (beginning-of-line))
21481 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21482 (t (outline-previous-visible-heading 1))))
21483 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21484 (if (called-interactively-p 'any)
21485 (call-interactively 'org-mark-element)
21486 (org-mark-element)))
21488 ;;; Indentation
21490 (defvar org-element-greater-elements)
21491 (defun org--get-expected-indentation (element contentsp)
21492 "Expected indentation column for current line, according to ELEMENT.
21493 ELEMENT is an element containing point. CONTENTSP is non-nil
21494 when indentation is to be computed according to contents of
21495 ELEMENT."
21496 (let ((type (org-element-type element))
21497 (start (org-element-property :begin element))
21498 (post-affiliated (org-element-property :post-affiliated element)))
21499 (org-with-wide-buffer
21500 (cond
21501 (contentsp
21502 (cl-case type
21503 ((diary-sexp footnote-definition) 0)
21504 ((headline inlinetask nil)
21505 (if (not org-adapt-indentation) 0
21506 (let ((level (org-current-level)))
21507 (if level (1+ level) 0))))
21508 ((item plain-list) (org-list-item-body-column post-affiliated))
21510 (goto-char start)
21511 (org-get-indentation))))
21512 ((memq type '(headline inlinetask nil))
21513 (if (org-match-line "[ \t]*$")
21514 (org--get-expected-indentation element t)
21516 ((memq type '(diary-sexp footnote-definition)) 0)
21517 ;; First paragraph of a footnote definition or an item.
21518 ;; Indent like parent.
21519 ((< (line-beginning-position) start)
21520 (org--get-expected-indentation
21521 (org-element-property :parent element) t))
21522 ;; At first line: indent according to previous sibling, if any,
21523 ;; ignoring footnote definitions and inline tasks, or parent's
21524 ;; contents.
21525 ((= (line-beginning-position) start)
21526 (catch 'exit
21527 (while t
21528 (if (= (point-min) start) (throw 'exit 0)
21529 (goto-char (1- start))
21530 (let* ((previous (org-element-at-point))
21531 (parent previous))
21532 (while (and parent (<= (org-element-property :end parent) start))
21533 (setq previous parent
21534 parent (org-element-property :parent parent)))
21535 (cond
21536 ((not previous) (throw 'exit 0))
21537 ((> (org-element-property :end previous) start)
21538 (throw 'exit (org--get-expected-indentation previous t)))
21539 ((memq (org-element-type previous)
21540 '(footnote-definition inlinetask))
21541 (setq start (org-element-property :begin previous)))
21542 (t (goto-char (org-element-property :begin previous))
21543 (throw 'exit
21544 (if (bolp) (org-get-indentation)
21545 ;; At first paragraph in an item or
21546 ;; a footnote definition.
21547 (org--get-expected-indentation
21548 (org-element-property :parent previous) t))))))))))
21549 ;; Otherwise, move to the first non-blank line above.
21551 (beginning-of-line)
21552 (let ((pos (point)))
21553 (skip-chars-backward " \r\t\n")
21554 (cond
21555 ;; Two blank lines end a footnote definition or a plain
21556 ;; list. When we indent an empty line after them, the
21557 ;; containing list or footnote definition is over, so it
21558 ;; qualifies as a previous sibling. Therefore, we indent
21559 ;; like its first line.
21560 ((and (memq type '(footnote-definition plain-list))
21561 (> (count-lines (point) pos) 2))
21562 (goto-char start)
21563 (org-get-indentation))
21564 ;; Line above is the first one of a paragraph at the
21565 ;; beginning of an item or a footnote definition. Indent
21566 ;; like parent.
21567 ((< (line-beginning-position) start)
21568 (org--get-expected-indentation
21569 (org-element-property :parent element) t))
21570 ;; Line above is the beginning of an element, i.e., point
21571 ;; was originally on the blank lines between element's start
21572 ;; and contents.
21573 ((= (line-beginning-position) post-affiliated)
21574 (org--get-expected-indentation element t))
21575 ;; POS is after contents in a greater element. Indent like
21576 ;; the beginning of the element.
21577 ((and (memq type org-element-greater-elements)
21578 (let ((cend (org-element-property :contents-end element)))
21579 (and cend (<= cend pos))))
21580 ;; As a special case, if point is at the end of a footnote
21581 ;; definition or an item, indent like the very last element
21582 ;; within. If that last element is an item, indent like
21583 ;; its contents.
21584 (if (memq type '(footnote-definition item plain-list))
21585 (let ((last (org-element-at-point)))
21586 (goto-char pos)
21587 (org--get-expected-indentation
21588 last (eq (org-element-type last) 'item)))
21589 (goto-char start)
21590 (org-get-indentation)))
21591 ;; In any other case, indent like the current line.
21592 (t (org-get-indentation)))))))))
21594 (defun org--align-node-property ()
21595 "Align node property at point.
21596 Alignment is done according to `org-property-format', which see."
21597 (when (save-excursion
21598 (beginning-of-line)
21599 (looking-at org-property-re))
21600 (replace-match
21601 (concat (match-string 4)
21602 (org-trim
21603 (format org-property-format (match-string 1) (match-string 3))))
21604 t t)))
21606 (defun org-indent-line ()
21607 "Indent line depending on context.
21609 Indentation is done according to the following rules:
21611 - Footnote definitions, diary sexps, headlines and inline tasks
21612 have to start at column 0.
21614 - On the very first line of an element, consider, in order, the
21615 next rules until one matches:
21617 1. If there's a sibling element before, ignoring footnote
21618 definitions and inline tasks, indent like its first line.
21620 2. If element has a parent, indent like its contents. More
21621 precisely, if parent is an item, indent after the
21622 description part, if any, or the bullet (see
21623 `org-list-description-max-indent'). Else, indent like
21624 parent's first line.
21626 3. Otherwise, indent relatively to current level, if
21627 `org-adapt-indentation' is non-nil, or to left margin.
21629 - On a blank line at the end of an element, indent according to
21630 the type of the element. More precisely
21632 1. If element is a plain list, an item, or a footnote
21633 definition, indent like the very last element within.
21635 2. If element is a paragraph, indent like its last non blank
21636 line.
21638 3. Otherwise, indent like its very first line.
21640 - In the code part of a source block, use language major mode
21641 to indent current line if `org-src-tab-acts-natively' is
21642 non-nil. If it is nil, do nothing.
21644 - Otherwise, indent like the first non-blank line above.
21646 The function doesn't indent an item as it could break the whole
21647 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21648 `\\[org-shiftmetaright]'.
21650 Also align node properties according to `org-property-format'."
21651 (interactive)
21652 (cond
21653 ((org-at-heading-p) 'noindent)
21655 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21656 (type (org-element-type element)))
21657 (cond ((and (memq type '(plain-list item))
21658 (= (line-beginning-position)
21659 (org-element-property :post-affiliated element)))
21660 'noindent)
21661 ((and (eq type 'latex-environment)
21662 (>= (point) (org-element-property :post-affiliated element))
21663 (< (point) (org-with-wide-buffer
21664 (goto-char (org-element-property :end element))
21665 (skip-chars-backward " \r\t\n")
21666 (line-beginning-position 2))))
21667 'noindent)
21668 ((and (eq type 'src-block)
21669 org-src-tab-acts-natively
21670 (> (line-beginning-position)
21671 (org-element-property :post-affiliated element))
21672 (< (line-beginning-position)
21673 (org-with-wide-buffer
21674 (goto-char (org-element-property :end element))
21675 (skip-chars-backward " \r\t\n")
21676 (line-beginning-position))))
21677 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21679 (let ((column (org--get-expected-indentation element nil)))
21680 ;; Preserve current column.
21681 (if (<= (current-column) (current-indentation))
21682 (indent-line-to column)
21683 (save-excursion (indent-line-to column))))
21684 ;; Align node property. Also preserve current column.
21685 (when (eq type 'node-property)
21686 (let ((column (current-column)))
21687 (org--align-node-property)
21688 (org-move-to-column column)))))))))
21690 (defun org-indent-region (start end)
21691 "Indent each non-blank line in the region.
21692 Called from a program, START and END specify the region to
21693 indent. The function will not indent contents of example blocks,
21694 verse blocks and export blocks as leading white spaces are
21695 assumed to be significant there."
21696 (interactive "r")
21697 (save-excursion
21698 (goto-char start)
21699 (skip-chars-forward " \r\t\n")
21700 (unless (eobp) (beginning-of-line))
21701 (let ((indent-to
21702 (lambda (ind pos)
21703 ;; Set IND as indentation for all lines between point and
21704 ;; POS. Blank lines are ignored. Leave point after POS
21705 ;; once done.
21706 (let ((limit (copy-marker pos)))
21707 (while (< (point) limit)
21708 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21709 (forward-line))
21710 (set-marker limit nil))))
21711 (end (copy-marker end)))
21712 (while (< (point) end)
21713 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21714 (let* ((element (org-element-at-point))
21715 (type (org-element-type element))
21716 (element-end (copy-marker (org-element-property :end element)))
21717 (ind (org--get-expected-indentation element nil)))
21718 (cond
21719 ;; Element indented as a single block. Example blocks
21720 ;; preserving indentation are a special case since the
21721 ;; "contents" must not be indented whereas the block
21722 ;; boundaries can.
21723 ((or (memq type '(export-block latex-environment))
21724 (and (eq type 'example-block)
21725 (not
21726 (or org-src-preserve-indentation
21727 (org-element-property :preserve-indent element)))))
21728 (let ((offset (- ind (org-get-indentation))))
21729 (unless (zerop offset)
21730 (indent-rigidly (org-element-property :begin element)
21731 (org-element-property :end element)
21732 offset)))
21733 (goto-char element-end))
21734 ;; Elements indented line wise. Be sure to exclude
21735 ;; example blocks (preserving indentation) and source
21736 ;; blocks from this category as they are treated
21737 ;; specially later.
21738 ((or (memq type '(paragraph table table-row))
21739 (not (or (org-element-property :contents-begin element)
21740 (memq type '(example-block src-block)))))
21741 (when (eq type 'node-property)
21742 (org--align-node-property)
21743 (beginning-of-line))
21744 (funcall indent-to ind (min element-end end)))
21745 ;; Elements consisting of three parts: before the
21746 ;; contents, the contents, and after the contents. The
21747 ;; contents are treated specially, according to the
21748 ;; element type, or not indented at all. Other parts are
21749 ;; indented as a single block.
21751 (let* ((post (copy-marker
21752 (org-element-property :post-affiliated element)))
21753 (cbeg
21754 (copy-marker
21755 (cond
21756 ((not (org-element-property :contents-begin element))
21757 ;; Fake contents for source blocks.
21758 (org-with-wide-buffer
21759 (goto-char post)
21760 (line-beginning-position 2)))
21761 ((memq type '(footnote-definition item plain-list))
21762 ;; Contents in these elements could start on
21763 ;; the same line as the beginning of the
21764 ;; element. Make sure we start indenting
21765 ;; from the second line.
21766 (org-with-wide-buffer
21767 (goto-char post)
21768 (end-of-line)
21769 (skip-chars-forward " \r\t\n")
21770 (if (eobp) (point) (line-beginning-position))))
21771 (t (org-element-property :contents-begin element)))))
21772 (cend (copy-marker
21773 (or (org-element-property :contents-end element)
21774 ;; Fake contents for source blocks.
21775 (org-with-wide-buffer
21776 (goto-char element-end)
21777 (skip-chars-backward " \r\t\n")
21778 (line-beginning-position)))
21779 t)))
21780 ;; Do not change items indentation individually as it
21781 ;; might break the list as a whole. On the other
21782 ;; hand, when at a plain list, indent it as a whole.
21783 (cond ((eq type 'plain-list)
21784 (let ((offset (- ind (org-get-indentation))))
21785 (unless (zerop offset)
21786 (indent-rigidly (org-element-property :begin element)
21787 (org-element-property :end element)
21788 offset))
21789 (goto-char cbeg)))
21790 ((eq type 'item) (goto-char cbeg))
21791 (t (funcall indent-to ind (min cbeg end))))
21792 (when (< (point) end)
21793 (cl-case type
21794 ((example-block verse-block))
21795 (src-block
21796 ;; In a source block, indent source code
21797 ;; according to language major mode, but only if
21798 ;; `org-src-tab-acts-natively' is non-nil.
21799 (when (and (< (point) end) org-src-tab-acts-natively)
21800 (ignore-errors
21801 (org-babel-do-in-edit-buffer
21802 (indent-region (point-min) (point-max))))))
21803 (t (org-indent-region (point) (min cend end))))
21804 (goto-char (min cend end))
21805 (when (< (point) end)
21806 (funcall indent-to ind (min element-end end))))
21807 (set-marker post nil)
21808 (set-marker cbeg nil)
21809 (set-marker cend nil))))
21810 (set-marker element-end nil))))
21811 (set-marker end nil))))
21813 (defun org-indent-drawer ()
21814 "Indent the drawer at point."
21815 (interactive)
21816 (unless (save-excursion
21817 (beginning-of-line)
21818 (looking-at-p org-drawer-regexp))
21819 (user-error "Not at a drawer"))
21820 (let ((element (org-element-at-point)))
21821 (unless (memq (org-element-type element) '(drawer property-drawer))
21822 (user-error "Not at a drawer"))
21823 (org-with-wide-buffer
21824 (org-indent-region (org-element-property :begin element)
21825 (org-element-property :end element))))
21826 (message "Drawer at point indented"))
21828 (defun org-indent-block ()
21829 "Indent the block at point."
21830 (interactive)
21831 (unless (save-excursion
21832 (beginning-of-line)
21833 (let ((case-fold-search t))
21834 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21835 (user-error "Not at a block"))
21836 (let ((element (org-element-at-point)))
21837 (unless (memq (org-element-type element)
21838 '(comment-block center-block dynamic-block example-block
21839 export-block quote-block special-block
21840 src-block verse-block))
21841 (user-error "Not at a block"))
21842 (org-with-wide-buffer
21843 (org-indent-region (org-element-property :begin element)
21844 (org-element-property :end element))))
21845 (message "Block at point indented"))
21848 ;;; Filling
21850 ;; We use our own fill-paragraph and auto-fill functions.
21852 ;; `org-fill-paragraph' relies on adaptive filling and context
21853 ;; checking. Appropriate `fill-prefix' is computed with
21854 ;; `org-adaptive-fill-function'.
21856 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21857 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21858 ;; `org-adaptive-fill-function' value. Internally,
21859 ;; `org-comment-line-break-function' breaks the line.
21861 ;; `org-setup-filling' installs filling and auto-filling related
21862 ;; variables during `org-mode' initialization.
21864 (defun org-setup-filling ()
21865 (require 'org-element)
21866 ;; Prevent auto-fill from inserting unwanted new items.
21867 (when (boundp 'fill-nobreak-predicate)
21868 (setq-local
21869 fill-nobreak-predicate
21870 (org-uniquify
21871 (append fill-nobreak-predicate
21872 '(org-fill-line-break-nobreak-p
21873 org-fill-n-macro-as-item-nobreak-p
21874 org-fill-paragraph-with-timestamp-nobreak-p)))))
21875 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21876 (setq-local paragraph-start paragraph-ending)
21877 (setq-local paragraph-separate paragraph-ending))
21878 (setq-local fill-paragraph-function 'org-fill-paragraph)
21879 (setq-local auto-fill-inhibit-regexp nil)
21880 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21881 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21882 (setq-local comment-line-break-function 'org-comment-line-break-function))
21884 (defun org-fill-line-break-nobreak-p ()
21885 "Non-nil when a new line at point would create an Org line break."
21886 (save-excursion
21887 (skip-chars-backward "[ \t]")
21888 (skip-chars-backward "\\\\")
21889 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21891 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21892 "Non-nil when a new line at point would split a timestamp."
21893 (and (org-at-timestamp-p 'lax)
21894 (not (looking-at org-ts-regexp-both))))
21896 (defun org-fill-n-macro-as-item-nobreak-p ()
21897 "Non-nil when a new line at point would create a new list."
21898 ;; During export, a "n" macro followed by a dot or a closing
21899 ;; parenthesis can end up being parsed as a new list item.
21900 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21902 (defvar orgtbl-line-start-regexp) ; From org-table.el
21903 (defun org-adaptive-fill-function ()
21904 "Compute a fill prefix for the current line.
21905 Return fill prefix, as a string, or nil if current line isn't
21906 meant to be filled. For convenience, if `adaptive-fill-regexp'
21907 matches in paragraphs or comments, use it."
21908 (org-with-wide-buffer
21909 (unless (org-at-heading-p)
21910 (let* ((p (line-beginning-position))
21911 (element (save-excursion
21912 (beginning-of-line)
21913 (org-element-at-point)))
21914 (type (org-element-type element))
21915 (post-affiliated (org-element-property :post-affiliated element)))
21916 (unless (< p post-affiliated)
21917 (cl-case type
21918 (comment
21919 (save-excursion
21920 (beginning-of-line)
21921 (looking-at "[ \t]*")
21922 (concat (match-string 0) "# ")))
21923 (footnote-definition "")
21924 ((item plain-list)
21925 (make-string (org-list-item-body-column post-affiliated) ?\s))
21926 (paragraph
21927 ;; Fill prefix is usually the same as the current line,
21928 ;; unless the paragraph is at the beginning of an item.
21929 (let ((parent (org-element-property :parent element)))
21930 (save-excursion
21931 (beginning-of-line)
21932 (cond ((eq (org-element-type parent) 'item)
21933 (make-string (org-list-item-body-column
21934 (org-element-property :begin parent))
21935 ?\s))
21936 ((and adaptive-fill-regexp
21937 ;; Locally disable
21938 ;; `adaptive-fill-function' to let
21939 ;; `fill-context-prefix' handle
21940 ;; `adaptive-fill-regexp' variable.
21941 (let (adaptive-fill-function)
21942 (fill-context-prefix
21943 post-affiliated
21944 (org-element-property :end element)))))
21945 ((looking-at "[ \t]+") (match-string 0))
21946 (t "")))))
21947 (comment-block
21948 ;; Only fill contents if P is within block boundaries.
21949 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21950 (forward-line)
21951 (point)))
21952 (cend (save-excursion
21953 (goto-char (org-element-property :end element))
21954 (skip-chars-backward " \r\t\n")
21955 (line-beginning-position))))
21956 (when (and (>= p cbeg) (< p cend))
21957 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21958 (match-string 0)
21959 ""))))))))))
21961 (defun org-fill-element (&optional justify)
21962 "Fill element at point, when applicable.
21964 This function only applies to comment blocks, comments, example
21965 blocks and paragraphs. Also, as a special case, re-align table
21966 when point is at one.
21968 If JUSTIFY is non-nil (interactively, with prefix argument),
21969 justify as well. If `sentence-end-double-space' is non-nil, then
21970 period followed by one space does not end a sentence, so don't
21971 break a line there. The variable `fill-column' controls the
21972 width for filling.
21974 For convenience, when point is at a plain list, an item or
21975 a footnote definition, try to fill the first paragraph within."
21976 (with-syntax-table org-mode-transpose-word-syntax-table
21977 ;; Move to end of line in order to get the first paragraph within
21978 ;; a plain list or a footnote definition.
21979 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21980 ;; First check if point is in a blank line at the beginning of
21981 ;; the buffer. In that case, ignore filling.
21982 (cl-case (org-element-type element)
21983 ;; Use major mode filling function is src blocks.
21984 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21985 ;; Align Org tables, leave table.el tables as-is.
21986 (table-row (org-table-align) t)
21987 (table
21988 (when (eq (org-element-property :type element) 'org)
21989 (save-excursion
21990 (goto-char (org-element-property :post-affiliated element))
21991 (org-table-align)))
21993 (paragraph
21994 ;; Paragraphs may contain `line-break' type objects.
21995 (let ((beg (max (point-min)
21996 (org-element-property :contents-begin element)))
21997 (end (min (point-max)
21998 (org-element-property :contents-end element))))
21999 ;; Do nothing if point is at an affiliated keyword.
22000 (if (< (line-end-position) beg) t
22001 ;; Fill paragraph, taking line breaks into account.
22002 (save-excursion
22003 (goto-char beg)
22004 (let ((cuts (list beg)))
22005 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22006 (when (eq 'line-break
22007 (org-element-type
22008 (save-excursion (backward-char)
22009 (org-element-context))))
22010 (push (point) cuts)))
22011 (dolist (c (delq end cuts))
22012 (fill-region-as-paragraph c end justify)
22013 (setq end c))))
22014 t)))
22015 ;; Contents of `comment-block' type elements should be
22016 ;; filled as plain text, but only if point is within block
22017 ;; markers.
22018 (comment-block
22019 (let* ((case-fold-search t)
22020 (beg (save-excursion
22021 (goto-char (org-element-property :begin element))
22022 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22023 (forward-line)
22024 (point)))
22025 (end (save-excursion
22026 (goto-char (org-element-property :end element))
22027 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22028 (line-beginning-position))))
22029 (if (or (< (point) beg) (> (point) end)) t
22030 (fill-region-as-paragraph
22031 (save-excursion (end-of-line)
22032 (re-search-backward "^[ \t]*$" beg 'move)
22033 (line-beginning-position))
22034 (save-excursion (beginning-of-line)
22035 (re-search-forward "^[ \t]*$" end 'move)
22036 (line-beginning-position))
22037 justify))))
22038 ;; Fill comments.
22039 (comment
22040 (let ((begin (org-element-property :post-affiliated element))
22041 (end (org-element-property :end element)))
22042 (when (and (>= (point) begin) (<= (point) end))
22043 (let ((begin (save-excursion
22044 (end-of-line)
22045 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22046 (progn (forward-line) (point))
22047 begin)))
22048 (end (save-excursion
22049 (end-of-line)
22050 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22051 (1- (line-beginning-position))
22052 (skip-chars-backward " \r\t\n")
22053 (line-end-position)))))
22054 ;; Do not fill comments when at a blank line.
22055 (when (> end begin)
22056 (let ((fill-prefix
22057 (save-excursion
22058 (beginning-of-line)
22059 (looking-at "[ \t]*#")
22060 (let ((comment-prefix (match-string 0)))
22061 (goto-char (match-end 0))
22062 (if (looking-at adaptive-fill-regexp)
22063 (concat comment-prefix (match-string 0))
22064 (concat comment-prefix " "))))))
22065 (save-excursion
22066 (fill-region-as-paragraph begin end justify))))))
22068 ;; Ignore every other element.
22069 (otherwise t)))))
22071 (defun org-fill-paragraph (&optional justify region)
22072 "Fill element at point, when applicable.
22074 This function only applies to comment blocks, comments, example
22075 blocks and paragraphs. Also, as a special case, re-align table
22076 when point is at one.
22078 For convenience, when point is at a plain list, an item or
22079 a footnote definition, try to fill the first paragraph within.
22081 If JUSTIFY is non-nil (interactively, with prefix argument),
22082 justify as well. If `sentence-end-double-space' is non-nil, then
22083 period followed by one space does not end a sentence, so don't
22084 break a line there. The variable `fill-column' controls the
22085 width for filling.
22087 The REGION argument is non-nil if called interactively; in that
22088 case, if Transient Mark mode is enabled and the mark is active,
22089 fill each of the elements in the active region, instead of just
22090 filling the current element."
22091 (interactive (progn
22092 (barf-if-buffer-read-only)
22093 (list (if current-prefix-arg 'full) t)))
22094 (cond
22095 ((and region transient-mark-mode mark-active
22096 (not (eq (region-beginning) (region-end))))
22097 (let ((origin (point-marker))
22098 (start (region-beginning)))
22099 (unwind-protect
22100 (progn
22101 (goto-char (region-end))
22102 (while (> (point) start)
22103 (org-backward-paragraph)
22104 (org-fill-element justify)))
22105 (goto-char origin)
22106 (set-marker origin nil))))
22107 (t (org-fill-element justify))))
22109 (defun org-auto-fill-function ()
22110 "Auto-fill function."
22111 ;; Check if auto-filling is meaningful.
22112 (let ((fc (current-fill-column)))
22113 (when (and fc (> (current-column) fc))
22114 (let* ((fill-prefix (org-adaptive-fill-function))
22115 ;; Enforce empty fill prefix, if required. Otherwise, it
22116 ;; will be computed again.
22117 (adaptive-fill-mode (not (equal fill-prefix ""))))
22118 (when fill-prefix (do-auto-fill))))))
22120 (defun org-comment-line-break-function (&optional soft)
22121 "Break line at point and indent, continuing comment if within one.
22122 The inserted newline is marked hard if variable
22123 `use-hard-newlines' is true, unless optional argument SOFT is
22124 non-nil."
22125 (if soft (insert-and-inherit ?\n) (newline 1))
22126 (save-excursion (forward-char -1) (delete-horizontal-space))
22127 (delete-horizontal-space)
22128 (indent-to-left-margin)
22129 (insert-before-markers-and-inherit fill-prefix))
22132 ;;; Fixed Width Areas
22134 (defun org-toggle-fixed-width ()
22135 "Toggle fixed-width markup.
22137 Add or remove fixed-width markup on current line, whenever it
22138 makes sense. Return an error otherwise.
22140 If a region is active and if it contains only fixed-width areas
22141 or blank lines, remove all fixed-width markup in it. If the
22142 region contains anything else, convert all non-fixed-width lines
22143 to fixed-width ones.
22145 Blank lines at the end of the region are ignored unless the
22146 region only contains such lines."
22147 (interactive)
22148 (if (not (org-region-active-p))
22149 ;; No region:
22151 ;; Remove fixed width marker only in a fixed-with element.
22153 ;; Add fixed width maker in paragraphs, in blank lines after
22154 ;; elements or at the beginning of a headline or an inlinetask,
22155 ;; and before any one-line elements (e.g., a clock).
22156 (progn
22157 (beginning-of-line)
22158 (let* ((element (org-element-at-point))
22159 (type (org-element-type element)))
22160 (cond
22161 ((and (eq type 'fixed-width)
22162 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22163 (replace-match
22164 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22165 ((and (memq type '(babel-call clock comment diary-sexp headline
22166 horizontal-rule keyword paragraph
22167 planning))
22168 (<= (org-element-property :post-affiliated element) (point)))
22169 (skip-chars-forward " \t")
22170 (insert ": "))
22171 ((and (looking-at-p "[ \t]*$")
22172 (or (eq type 'inlinetask)
22173 (save-excursion
22174 (skip-chars-forward " \r\t\n")
22175 (<= (org-element-property :end element) (point)))))
22176 (delete-region (point) (line-end-position))
22177 (org-indent-line)
22178 (insert ": "))
22179 (t (user-error "Cannot insert a fixed-width line here")))))
22180 ;; Region active.
22181 (let* ((begin (save-excursion
22182 (goto-char (region-beginning))
22183 (line-beginning-position)))
22184 (end (copy-marker
22185 (save-excursion
22186 (goto-char (region-end))
22187 (unless (eolp) (beginning-of-line))
22188 (if (save-excursion (re-search-backward "\\S-" begin t))
22189 (progn (skip-chars-backward " \r\t\n") (point))
22190 (point)))))
22191 (all-fixed-width-p
22192 (catch 'not-all-p
22193 (save-excursion
22194 (goto-char begin)
22195 (skip-chars-forward " \r\t\n")
22196 (when (eobp) (throw 'not-all-p nil))
22197 (while (< (point) end)
22198 (let ((element (org-element-at-point)))
22199 (if (eq (org-element-type element) 'fixed-width)
22200 (goto-char (org-element-property :end element))
22201 (throw 'not-all-p nil))))
22202 t))))
22203 (if all-fixed-width-p
22204 (save-excursion
22205 (goto-char begin)
22206 (while (< (point) end)
22207 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22208 (replace-match
22209 "" nil nil nil
22210 (if (= (line-end-position) (match-end 0)) 0 1)))
22211 (forward-line)))
22212 (let ((min-ind (point-max)))
22213 ;; Find minimum indentation across all lines.
22214 (save-excursion
22215 (goto-char begin)
22216 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22217 (setq min-ind 0)
22218 (catch 'zerop
22219 (while (< (point) end)
22220 (unless (looking-at-p "[ \t]*$")
22221 (let ((ind (org-get-indentation)))
22222 (setq min-ind (min min-ind ind))
22223 (when (zerop ind) (throw 'zerop t))))
22224 (forward-line)))))
22225 ;; Loop over all lines and add fixed-width markup everywhere
22226 ;; but in fixed-width lines.
22227 (save-excursion
22228 (goto-char begin)
22229 (while (< (point) end)
22230 (cond
22231 ((org-at-heading-p)
22232 (insert ": ")
22233 (forward-line)
22234 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22235 (insert ":")
22236 (forward-line)))
22237 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22238 (let* ((element (org-element-at-point))
22239 (element-end (org-element-property :end element)))
22240 (if (eq (org-element-type element) 'fixed-width)
22241 (progn (goto-char element-end)
22242 (skip-chars-backward " \r\t\n")
22243 (forward-line))
22244 (let ((limit (min end element-end)))
22245 (while (< (point) limit)
22246 (org-move-to-column min-ind t)
22247 (insert ": ")
22248 (forward-line))))))
22250 (org-move-to-column min-ind t)
22251 (insert ": ")
22252 (forward-line)))))))
22253 (set-marker end nil))))
22256 ;;; Blocks
22258 (defun org-block-map (function &optional start end)
22259 "Call FUNCTION at the head of all source blocks in the current buffer.
22260 Optional arguments START and END can be used to limit the range."
22261 (let ((start (or start (point-min)))
22262 (end (or end (point-max))))
22263 (save-excursion
22264 (goto-char start)
22265 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22266 (save-excursion
22267 (save-match-data
22268 (goto-char (match-beginning 0))
22269 (funcall function)))))))
22271 (defun org-next-block (arg &optional backward block-regexp)
22272 "Jump to the next block.
22274 With a prefix argument ARG, jump forward ARG many blocks.
22276 When BACKWARD is non-nil, jump to the previous block.
22278 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22279 Match data is set according to this regexp when the function
22280 returns.
22282 Return point at beginning of the opening line of found block.
22283 Throw an error if no block is found."
22284 (interactive "p")
22285 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22286 (case-fold-search t)
22287 (search-fn (if backward #'re-search-backward #'re-search-forward))
22288 (count (or arg 1))
22289 (origin (point))
22290 last-element)
22291 (if backward (beginning-of-line) (end-of-line))
22292 (while (and (> count 0) (funcall search-fn re nil t))
22293 (let ((element (save-excursion
22294 (goto-char (match-beginning 0))
22295 (save-match-data (org-element-at-point)))))
22296 (when (and (memq (org-element-type element)
22297 '(center-block comment-block dynamic-block
22298 example-block export-block quote-block
22299 special-block src-block verse-block))
22300 (<= (match-beginning 0)
22301 (org-element-property :post-affiliated element)))
22302 (setq last-element element)
22303 (cl-decf count))))
22304 (if (= count 0)
22305 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22306 (save-match-data (org-show-context)))
22307 (goto-char origin)
22308 (user-error "No %s code blocks" (if backward "previous" "further")))))
22310 (defun org-previous-block (arg &optional block-regexp)
22311 "Jump to the previous block.
22312 With a prefix argument ARG, jump backward ARG many source blocks.
22313 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22314 (interactive "p")
22315 (org-next-block arg t block-regexp))
22318 ;;; Comments
22320 ;; Org comments syntax is quite complex. It requires the entire line
22321 ;; to be just a comment. Also, even with the right syntax at the
22322 ;; beginning of line, some elements (e.g., verse-block or
22323 ;; example-block) don't accept comments. Usual Emacs comment commands
22324 ;; cannot cope with those requirements. Therefore, Org replaces them.
22326 ;; Org still relies on `comment-dwim', but cannot trust
22327 ;; `comment-only-p'. So, `comment-region-function' and
22328 ;; `uncomment-region-function' both point
22329 ;; to`org-comment-or-uncomment-region'. Eventually,
22330 ;; `org-insert-comment' takes care of insertion of comments at the
22331 ;; beginning of line.
22333 ;; `org-setup-comments-handling' install comments related variables
22334 ;; during `org-mode' initialization.
22336 (defun org-setup-comments-handling ()
22337 (interactive)
22338 (setq-local comment-use-syntax nil)
22339 (setq-local comment-start "# ")
22340 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22341 (setq-local comment-insert-comment-function 'org-insert-comment)
22342 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22343 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22345 (defun org-insert-comment ()
22346 "Insert an empty comment above current line.
22347 If the line is empty, insert comment at its beginning. When
22348 point is within a source block, comment according to the related
22349 major mode."
22350 (if (let ((element (org-element-at-point)))
22351 (and (eq (org-element-type element) 'src-block)
22352 (< (save-excursion
22353 (goto-char (org-element-property :post-affiliated element))
22354 (line-end-position))
22355 (point))
22356 (> (save-excursion
22357 (goto-char (org-element-property :end element))
22358 (skip-chars-backward " \r\t\n")
22359 (line-beginning-position))
22360 (point))))
22361 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22362 (beginning-of-line)
22363 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22364 (open-line 1))
22365 (org-indent-line)
22366 (insert "# ")))
22368 (defvar comment-empty-lines) ; From newcomment.el.
22369 (defun org-comment-or-uncomment-region (beg end &rest _)
22370 "Comment or uncomment each non-blank line in the region.
22371 Uncomment each non-blank line between BEG and END if it only
22372 contains commented lines. Otherwise, comment them. If region is
22373 strictly within a source block, use appropriate comment syntax."
22374 (if (let ((element (org-element-at-point)))
22375 (and (eq (org-element-type element) 'src-block)
22376 (< (save-excursion
22377 (goto-char (org-element-property :post-affiliated element))
22378 (line-end-position))
22379 beg)
22380 (>= (save-excursion
22381 (goto-char (org-element-property :end element))
22382 (skip-chars-backward " \r\t\n")
22383 (line-beginning-position))
22384 end)))
22385 ;; Translate region boundaries for the Org buffer to the source
22386 ;; buffer.
22387 (let ((offset (- end beg)))
22388 (save-excursion
22389 (goto-char beg)
22390 (org-babel-do-in-edit-buffer
22391 (comment-or-uncomment-region (point) (+ offset (point))))))
22392 (save-restriction
22393 ;; Restrict region
22394 (narrow-to-region (save-excursion (goto-char beg)
22395 (skip-chars-forward " \r\t\n" end)
22396 (line-beginning-position))
22397 (save-excursion (goto-char end)
22398 (skip-chars-backward " \r\t\n" beg)
22399 (line-end-position)))
22400 (let ((uncommentp
22401 ;; UNCOMMENTP is non-nil when every non blank line between
22402 ;; BEG and END is a comment.
22403 (save-excursion
22404 (goto-char (point-min))
22405 (while (and (not (eobp))
22406 (let ((element (org-element-at-point)))
22407 (and (eq (org-element-type element) 'comment)
22408 (goto-char (min (point-max)
22409 (org-element-property
22410 :end element)))))))
22411 (eobp))))
22412 (if uncommentp
22413 ;; Only blank lines and comments in region: uncomment it.
22414 (save-excursion
22415 (goto-char (point-min))
22416 (while (not (eobp))
22417 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22418 (replace-match "" nil nil nil 1))
22419 (forward-line)))
22420 ;; Comment each line in region.
22421 (let ((min-indent (point-max)))
22422 ;; First find the minimum indentation across all lines.
22423 (save-excursion
22424 (goto-char (point-min))
22425 (while (and (not (eobp)) (not (zerop min-indent)))
22426 (unless (looking-at "[ \t]*$")
22427 (setq min-indent (min min-indent (current-indentation))))
22428 (forward-line)))
22429 ;; Then loop over all lines.
22430 (save-excursion
22431 (goto-char (point-min))
22432 (while (not (eobp))
22433 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22434 ;; Don't get fooled by invisible text (e.g. link path)
22435 ;; when moving to column MIN-INDENT.
22436 (let ((buffer-invisibility-spec nil))
22437 (org-move-to-column min-indent t))
22438 (insert comment-start))
22439 (forward-line)))))))))
22441 (defun org-comment-dwim (_arg)
22442 "Call the comment command you mean.
22443 Call `org-toggle-comment' if on a heading, otherwise call
22444 `comment-dwim', within a source edit buffer if needed."
22445 (interactive "*P")
22446 (cond ((org-at-heading-p)
22447 (call-interactively #'org-toggle-comment))
22448 ((org-in-src-block-p)
22449 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22450 (t (call-interactively #'comment-dwim))))
22453 ;;; Timestamps API
22455 ;; This section contains tools to operate on, or create, timestamp
22456 ;; objects, as returned by, e.g. `org-element-context'.
22458 (defun org-timestamp-from-string (s)
22459 "Convert Org timestamp S, as a string, into a timestamp object.
22460 Return nil if S is not a valid timestamp string."
22461 (when (org-string-nw-p s)
22462 (with-temp-buffer
22463 (save-excursion (insert s))
22464 (org-element-timestamp-parser))))
22466 (defun org-timestamp-from-time (time &optional with-time inactive)
22467 "Convert a time value into a timestamp object.
22469 TIME is an Emacs internal time representation, as returned, e.g.,
22470 by `current-time'.
22472 When optional argument WITH-TIME is non-nil, return a timestamp
22473 object with a time part, i.e., with hours and minutes.
22475 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22476 return an active timestamp."
22477 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22478 (org-element-create 'timestamp
22479 (list :type (if inactive 'inactive 'active)
22480 :year-start year
22481 :month-start month
22482 :day-start day
22483 :hour-start (and with-time hour)
22484 :minute-start (and with-time minute)))))
22486 (defun org-timestamp-to-time (timestamp &optional end)
22487 "Convert TIMESTAMP object into an Emacs internal time value.
22488 Use end of date range or time range when END is non-nil.
22489 Otherwise, use its start."
22490 (apply #'encode-time
22491 (cons 0
22492 (mapcar
22493 (lambda (prop) (or (org-element-property prop timestamp) 0))
22494 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22495 '(:minute-start :hour-start :day-start :month-start
22496 :year-start))))))
22498 (defun org-timestamp-has-time-p (timestamp)
22499 "Non-nil when TIMESTAMP has a time specified."
22500 (org-element-property :hour-start timestamp))
22502 (defun org-timestamp-format (timestamp format &optional end utc)
22503 "Format a TIMESTAMP object into a string.
22505 FORMAT is a format specifier to be passed to
22506 `format-time-string'.
22508 When optional argument END is non-nil, use end of date-range or
22509 time-range, if possible.
22511 When optional argument UTC is non-nil, time is be expressed as
22512 Universal Time."
22513 (format-time-string format (org-timestamp-to-time timestamp end)
22514 (and utc t)))
22516 (defun org-timestamp-split-range (timestamp &optional end)
22517 "Extract a TIMESTAMP object from a date or time range.
22519 END, when non-nil, means extract the end of the range.
22520 Otherwise, extract its start.
22522 Return a new timestamp object."
22523 (let ((type (org-element-property :type timestamp)))
22524 (if (memq type '(active inactive diary)) timestamp
22525 (let ((split-ts (org-element-copy timestamp)))
22526 ;; Set new type.
22527 (org-element-put-property
22528 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22529 ;; Copy start properties over end properties if END is
22530 ;; non-nil. Otherwise, copy end properties over `start' ones.
22531 (let ((p-alist '((:minute-start . :minute-end)
22532 (:hour-start . :hour-end)
22533 (:day-start . :day-end)
22534 (:month-start . :month-end)
22535 (:year-start . :year-end))))
22536 (dolist (p-cell p-alist)
22537 (org-element-put-property
22538 split-ts
22539 (funcall (if end #'car #'cdr) p-cell)
22540 (org-element-property
22541 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22542 ;; Eventually refresh `:raw-value'.
22543 (org-element-put-property split-ts :raw-value nil)
22544 (org-element-put-property
22545 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22547 (defun org-timestamp-translate (timestamp &optional boundary)
22548 "Translate TIMESTAMP object to custom format.
22550 Format string is defined in `org-time-stamp-custom-formats',
22551 which see.
22553 When optional argument BOUNDARY is non-nil, it is either the
22554 symbol `start' or `end'. In this case, only translate the
22555 starting or ending part of TIMESTAMP if it is a date or time
22556 range. Otherwise, translate both parts.
22558 Return timestamp as-is if `org-display-custom-times' is nil or if
22559 it has a `diary' type."
22560 (let ((type (org-element-property :type timestamp)))
22561 (if (or (not org-display-custom-times) (eq type 'diary))
22562 (org-element-interpret-data timestamp)
22563 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22564 org-time-stamp-custom-formats)))
22565 (if (and (not boundary) (memq type '(active-range inactive-range)))
22566 (concat (org-timestamp-format timestamp fmt)
22567 "--"
22568 (org-timestamp-format timestamp fmt t))
22569 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22571 ;;; Other stuff
22573 (defvar reftex-docstruct-symbol)
22574 (defvar org--rds)
22576 (defun org-reftex-citation ()
22577 "Use reftex-citation to insert a citation into the buffer.
22578 This looks for a line like
22580 #+BIBLIOGRAPHY: foo plain option:-d
22582 and derives from it that foo.bib is the bibliography file relevant
22583 for this document. It then installs the necessary environment for RefTeX
22584 to work in this buffer and calls `reftex-citation' to insert a citation
22585 into the buffer.
22587 Export of such citations to both LaTeX and HTML is handled by the contributed
22588 package ox-bibtex by Taru Karttunen."
22589 (interactive)
22590 (let ((reftex-docstruct-symbol 'org--rds)
22591 org--rds bib)
22592 (org-with-wide-buffer
22593 (let ((case-fold-search t)
22594 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22595 (if (not (save-excursion
22596 (or (re-search-forward re nil t)
22597 (re-search-backward re nil t))))
22598 (user-error "No bibliography defined in file")
22599 (setq bib (concat (match-string 1) ".bib")
22600 org--rds (list (list 'bib bib))))))
22601 (call-interactively 'reftex-citation)))
22603 ;;;; Functions extending outline functionality
22605 (defun org-beginning-of-line (&optional n)
22606 "Go to the beginning of the current visible line.
22608 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22609 symbol `reversed', on the first attempt move to where the
22610 headline text starts, and only move to beginning of line when the
22611 cursor is already before the start of the text of the headline.
22613 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22614 start of the text on the second attempt.
22616 With argument N not nil or 1, move forward N - 1 lines first."
22617 (interactive "^p")
22618 (let ((origin (point))
22619 (special (pcase org-special-ctrl-a/e
22620 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22621 deactivate-mark)
22622 ;; First move to a visible line.
22623 (if (bound-and-true-p visual-line-mode)
22624 (beginning-of-visual-line n)
22625 (move-beginning-of-line n)
22626 ;; `move-beginning-of-line' may leave point after invisible
22627 ;; characters if line starts with such of these (e.g., with
22628 ;; a link at column 0). Really move to the beginning of the
22629 ;; current visible line.
22630 (beginning-of-line))
22631 (cond
22632 ;; No special behavior. Point is already at the beginning of
22633 ;; a line, logical or visual.
22634 ((not special))
22635 ;; `beginning-of-visual-line' left point before logical beginning
22636 ;; of line: point is at the beginning of a visual line. Bail
22637 ;; out.
22638 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22639 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22640 ;; At a headline, special position is before the title, but
22641 ;; after any TODO keyword or priority cookie.
22642 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22643 (line-end-position)))
22644 (bol (point)))
22645 (if (eq special 'reversed)
22646 (when (and (= origin bol) (eq last-command this-command))
22647 (goto-char refpos))
22648 (when (or (> origin refpos) (= origin bol))
22649 (goto-char refpos)))))
22650 ((and (looking-at org-list-full-item-re)
22651 (memq (org-element-type (save-match-data (org-element-at-point)))
22652 '(item plain-list)))
22653 ;; Set special position at first white space character after
22654 ;; bullet, and check-box, if any.
22655 (let ((after-bullet
22656 (let ((box (match-end 3)))
22657 (cond ((not box) (match-end 1))
22658 ((eq (char-after box) ?\s) (1+ box))
22659 (t box)))))
22660 (if (eq special 'reversed)
22661 (when (and (= (point) origin) (eq last-command this-command))
22662 (goto-char after-bullet))
22663 (when (or (> origin after-bullet) (= (point) origin))
22664 (goto-char after-bullet)))))
22665 ;; No special context. Point is already at beginning of line.
22666 (t nil))))
22668 (defun org-end-of-line (&optional n)
22669 "Go to the end of the line, but before ellipsis, if any.
22671 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22672 symbol `reversed', ignore tags on the first attempt, and only
22673 move to after the tags when the cursor is already beyond the end
22674 of the headline.
22676 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22677 on the second attempt.
22679 With argument N not nil or 1, move forward N - 1 lines first."
22680 (interactive "^p")
22681 (let ((origin (point))
22682 (special (pcase org-special-ctrl-a/e
22683 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22684 deactivate-mark)
22685 ;; First move to a visible line.
22686 (if (bound-and-true-p visual-line-mode)
22687 (beginning-of-visual-line n)
22688 (move-beginning-of-line n))
22689 (cond
22690 ;; At a headline, with tags.
22691 ((and special
22692 (save-excursion
22693 (beginning-of-line)
22694 (let ((case-fold-search nil))
22695 (looking-at org-complex-heading-regexp)))
22696 (match-end 5))
22697 (let ((tags (save-excursion
22698 (goto-char (match-beginning 5))
22699 (skip-chars-backward " \t")
22700 (point)))
22701 (visual-end (and (bound-and-true-p visual-line-mode)
22702 (save-excursion
22703 (end-of-visual-line)
22704 (point)))))
22705 ;; If `end-of-visual-line' brings us before end of line or
22706 ;; even tags, i.e., the headline spans over multiple visual
22707 ;; lines, move there.
22708 (cond ((and visual-end
22709 (< visual-end tags)
22710 (<= origin visual-end))
22711 (goto-char visual-end))
22712 ((eq special 'reversed)
22713 (if (and (= origin (line-end-position))
22714 (eq this-command last-command))
22715 (goto-char tags)
22716 (end-of-line)))
22718 (if (or (< origin tags) (= origin (line-end-position)))
22719 (goto-char tags)
22720 (end-of-line))))))
22721 ((bound-and-true-p visual-line-mode)
22722 (let ((bol (line-beginning-position)))
22723 (end-of-visual-line)
22724 ;; If `end-of-visual-line' gets us past the ellipsis at the
22725 ;; end of a line, backtrack and use `end-of-line' instead.
22726 (when (/= bol (line-beginning-position))
22727 (goto-char bol)
22728 (end-of-line))))
22729 (t (end-of-line)))))
22731 (defun org-backward-sentence (&optional _arg)
22732 "Go to beginning of sentence, or beginning of table field.
22733 This will call `backward-sentence' or `org-table-beginning-of-field',
22734 depending on context."
22735 (interactive)
22736 (let* ((element (org-element-at-point))
22737 (contents-begin (org-element-property :contents-begin element))
22738 (table (org-element-lineage element '(table) t)))
22739 (if (and table
22740 (> (point) contents-begin)
22741 (<= (point) (org-element-property :contents-end table)))
22742 (call-interactively #'org-table-beginning-of-field)
22743 (save-restriction
22744 (when (and contents-begin
22745 (< (point-min) contents-begin)
22746 (> (point) contents-begin))
22747 (narrow-to-region contents-begin
22748 (org-element-property :contents-end element)))
22749 (call-interactively #'backward-sentence)))))
22751 (defun org-forward-sentence (&optional _arg)
22752 "Go to end of sentence, or end of table field.
22753 This will call `forward-sentence' or `org-table-end-of-field',
22754 depending on context."
22755 (interactive)
22756 (if (and (org-at-heading-p)
22757 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22758 (save-restriction
22759 (narrow-to-region (line-beginning-position) (line-end-position))
22760 (call-interactively #'forward-sentence))
22761 (let* ((element (org-element-at-point))
22762 (contents-end (org-element-property :contents-end element))
22763 (table (org-element-lineage element '(table) t)))
22764 (if (and table
22765 (>= (point) (org-element-property :contents-begin table))
22766 (< (point) contents-end))
22767 (call-interactively #'org-table-end-of-field)
22768 (save-restriction
22769 (when (and contents-end
22770 (> (point-max) contents-end)
22771 ;; Skip blank lines between elements.
22772 (< (org-element-property :end element)
22773 (save-excursion (goto-char contents-end)
22774 (skip-chars-forward " \r\t\n"))))
22775 (narrow-to-region (org-element-property :contents-begin element)
22776 contents-end))
22777 ;; End of heading is considered as the end of a sentence.
22778 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22779 (call-interactively #'forward-sentence)))))))
22781 (defun org-kill-line (&optional _arg)
22782 "Kill line, to tags or end of line."
22783 (interactive)
22784 (cond
22785 ((or (not org-special-ctrl-k)
22786 (bolp)
22787 (not (org-at-heading-p)))
22788 (when (and (get-char-property (line-end-position) 'invisible)
22789 org-ctrl-k-protect-subtree
22790 (or (eq org-ctrl-k-protect-subtree 'error)
22791 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22792 (user-error
22793 (substitute-command-keys
22794 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22795 (call-interactively
22796 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22797 ((looking-at org-tag-line-re)
22798 (let ((end (save-excursion
22799 (goto-char (match-beginning 1))
22800 (skip-chars-backward " \t"))))
22801 (if (<= end (point)) ;on tags part
22802 (kill-region (point) (line-end-position))
22803 (kill-region (point) end)))
22804 (org-align-tags))
22805 (t (kill-region (point) (line-end-position)))))
22807 (defun org-yank (&optional arg)
22808 "Yank. If the kill is a subtree, treat it specially.
22809 This command will look at the current kill and check if is a single
22810 subtree, or a series of subtrees[1]. If it passes the test, and if the
22811 cursor is at the beginning of a line or after the stars of a currently
22812 empty headline, then the yank is handled specially. How exactly depends
22813 on the value of the following variables.
22815 `org-yank-folded-subtrees'
22816 By default, this variable is non-nil, which results in
22817 subtree(s) being folded after insertion, except if doing so
22818 would swallow text after the yanked text.
22820 `org-yank-adjusted-subtrees'
22821 When non-nil (the default value is nil), the subtree will be
22822 promoted or demoted in order to fit into the local outline tree
22823 structure, which means that the level will be adjusted so that it
22824 becomes the smaller one of the two *visible* surrounding headings.
22826 Any prefix to this command will cause `yank' to be called directly with
22827 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22828 will just
22829 plainly yank the text as it is.
22831 \[1] The test checks if the first non-white line is a heading
22832 and if there are no other headings with fewer stars."
22833 (interactive "P")
22834 (org-yank-generic 'yank arg))
22836 (defun org-yank-generic (command arg)
22837 "Perform some yank-like command.
22839 This function implements the behavior described in the `org-yank'
22840 documentation. However, it has been generalized to work for any
22841 interactive command with similar behavior."
22843 ;; pretend to be command COMMAND
22844 (setq this-command command)
22846 (if arg
22847 (call-interactively command)
22849 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22850 (and (org-kill-is-subtree-p)
22851 (or (bolp)
22852 (and (looking-at "[ \t]*$")
22853 (string-match
22854 "\\`\\*+\\'"
22855 (buffer-substring (point-at-bol) (point)))))))
22856 swallowp)
22857 (cond
22858 ((and subtreep org-yank-folded-subtrees)
22859 (let ((beg (point))
22860 end)
22861 (if (and subtreep org-yank-adjusted-subtrees)
22862 (org-paste-subtree nil nil 'for-yank)
22863 (call-interactively command))
22865 (setq end (point))
22866 (goto-char beg)
22867 (when (and (bolp) subtreep
22868 (not (setq swallowp
22869 (org-yank-folding-would-swallow-text beg end))))
22870 (org-with-limited-levels
22871 (or (looking-at org-outline-regexp)
22872 (re-search-forward org-outline-regexp-bol end t))
22873 (while (and (< (point) end) (looking-at org-outline-regexp))
22874 (outline-hide-subtree)
22875 (org-cycle-show-empty-lines 'folded)
22876 (condition-case nil
22877 (outline-forward-same-level 1)
22878 (error (goto-char end))))))
22879 (when swallowp
22880 (message
22881 "Inserted text not folded because that would swallow text"))
22883 (goto-char end)
22884 (skip-chars-forward " \t\n\r")
22885 (beginning-of-line 1)
22886 (push-mark beg 'nomsg)))
22887 ((and subtreep org-yank-adjusted-subtrees)
22888 (let ((beg (point-at-bol)))
22889 (org-paste-subtree nil nil 'for-yank)
22890 (push-mark beg 'nomsg)))
22892 (call-interactively command))))))
22894 (defun org-yank-folding-would-swallow-text (beg end)
22895 "Would hide-subtree at BEG swallow any text after END?"
22896 (let (level)
22897 (org-with-limited-levels
22898 (save-excursion
22899 (goto-char beg)
22900 (when (or (looking-at org-outline-regexp)
22901 (re-search-forward org-outline-regexp-bol end t))
22902 (setq level (org-outline-level)))
22903 (goto-char end)
22904 (skip-chars-forward " \t\r\n\v\f")
22905 (not (or (eobp)
22906 (and (bolp) (looking-at-p org-outline-regexp)
22907 (<= (org-outline-level) level))))))))
22909 (defun org-back-to-heading (&optional invisible-ok)
22910 "Call `outline-back-to-heading', but provide a better error message."
22911 (condition-case nil
22912 (outline-back-to-heading invisible-ok)
22913 (error (error "Before first headline at position %d in buffer %s"
22914 (point) (current-buffer)))))
22916 (defun org-before-first-heading-p ()
22917 "Before first heading?"
22918 (save-excursion
22919 (end-of-line)
22920 (null (re-search-backward org-outline-regexp-bol nil t))))
22922 (defun org-at-heading-p (&optional ignored)
22923 (outline-on-heading-p t))
22925 (defun org-in-commented-heading-p (&optional no-inheritance)
22926 "Non-nil if point is under a commented heading.
22927 This function also checks ancestors of the current headline,
22928 unless optional argument NO-INHERITANCE is non-nil."
22929 (cond
22930 ((org-before-first-heading-p) nil)
22931 ((let ((headline (nth 4 (org-heading-components))))
22932 (and headline
22933 (let ((case-fold-search nil))
22934 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22935 headline)))))
22936 (no-inheritance nil)
22938 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22940 (defun org-at-comment-p nil
22941 "Is cursor in a commented line?"
22942 (save-excursion
22943 (save-match-data
22944 (beginning-of-line)
22945 (looking-at "^[ \t]*# "))))
22947 (defun org-at-drawer-p nil
22948 "Is cursor at a drawer keyword?"
22949 (save-excursion
22950 (move-beginning-of-line 1)
22951 (looking-at org-drawer-regexp)))
22953 (defun org-at-block-p nil
22954 "Is cursor at a block keyword?"
22955 (save-excursion
22956 (move-beginning-of-line 1)
22957 (looking-at org-block-regexp)))
22959 (defun org-point-at-end-of-empty-headline ()
22960 "If point is at the end of an empty headline, return t, else nil.
22961 If the heading only contains a TODO keyword, it is still still considered
22962 empty."
22963 (let ((case-fold-search nil))
22964 (and (looking-at "[ \t]*$")
22965 org-todo-line-regexp
22966 (save-excursion
22967 (beginning-of-line)
22968 (looking-at org-todo-line-regexp)
22969 (string= (match-string 3) "")))))
22971 (defun org-at-heading-or-item-p ()
22972 (or (org-at-heading-p) (org-at-item-p)))
22974 (defun org-at-target-p ()
22975 (or (org-in-regexp org-radio-target-regexp)
22976 (org-in-regexp org-target-regexp)))
22977 ;; Compatibility alias with Org versions < 7.8.03
22978 (defalias 'org-on-target-p 'org-at-target-p)
22980 (defun org-up-heading-all (arg)
22981 "Move to the heading line of which the present line is a subheading.
22982 This function considers both visible and invisible heading lines.
22983 With argument, move up ARG levels."
22984 (outline-up-heading arg t))
22986 (defun org-up-heading-safe ()
22987 "Move to the heading line of which the present line is a subheading.
22988 This version will not throw an error. It will return the level of the
22989 headline found, or nil if no higher level is found.
22991 Also, this function will be a lot faster than `outline-up-heading',
22992 because it relies on stars being the outline starters. This can really
22993 make a significant difference in outlines with very many siblings."
22994 (when (ignore-errors (org-back-to-heading t))
22995 (let ((level-up (1- (funcall outline-level))))
22996 (and (> level-up 0)
22997 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
22998 (funcall outline-level)))))
23000 (defun org-first-sibling-p ()
23001 "Is this heading the first child of its parents?"
23002 (interactive)
23003 (let ((re org-outline-regexp-bol)
23004 level l)
23005 (unless (org-at-heading-p t)
23006 (user-error "Not at a heading"))
23007 (setq level (funcall outline-level))
23008 (save-excursion
23009 (if (not (re-search-backward re nil t))
23011 (setq l (funcall outline-level))
23012 (< l level)))))
23014 (defun org-goto-sibling (&optional previous)
23015 "Goto the next sibling, even if it is invisible.
23016 When PREVIOUS is set, go to the previous sibling instead. Returns t
23017 when a sibling was found. When none is found, return nil and don't
23018 move point."
23019 (let ((fun (if previous 're-search-backward 're-search-forward))
23020 (pos (point))
23021 (re org-outline-regexp-bol)
23022 level l)
23023 (when (ignore-errors (org-back-to-heading t))
23024 (setq level (funcall outline-level))
23025 (catch 'exit
23026 (or previous (forward-char 1))
23027 (while (funcall fun re nil t)
23028 (setq l (funcall outline-level))
23029 (when (< l level) (goto-char pos) (throw 'exit nil))
23030 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23031 (goto-char pos)
23032 nil))))
23034 (defun org-show-siblings ()
23035 "Show all siblings of the current headline."
23036 (save-excursion
23037 (while (org-goto-sibling) (org-flag-heading nil)))
23038 (save-excursion
23039 (while (org-goto-sibling 'previous)
23040 (org-flag-heading nil))))
23042 (defun org-goto-first-child ()
23043 "Goto the first child, even if it is invisible.
23044 Return t when a child was found. Otherwise don't move point and
23045 return nil."
23046 (let (level (pos (point)) (re org-outline-regexp-bol))
23047 (when (ignore-errors (org-back-to-heading t))
23048 (setq level (outline-level))
23049 (forward-char 1)
23050 (if (and (re-search-forward re nil t) (> (outline-level) level))
23051 (progn (goto-char (match-beginning 0)) t)
23052 (goto-char pos) nil))))
23054 (defun org-show-hidden-entry ()
23055 "Show an entry where even the heading is hidden."
23056 (save-excursion
23057 (org-show-entry)))
23059 (defun org-flag-heading (flag &optional entry)
23060 "Flag the current heading. FLAG non-nil means make invisible.
23061 When ENTRY is non-nil, show the entire entry."
23062 (save-excursion
23063 (org-back-to-heading t)
23064 ;; Check if we should show the entire entry
23065 (if (not entry)
23066 (org-flag-region
23067 (line-end-position 0) (line-end-position) flag 'outline)
23068 (org-show-entry)
23069 (save-excursion
23070 (and (outline-next-heading)
23071 (org-flag-heading nil))))))
23073 (defun org-get-next-sibling ()
23074 "Move to next heading of the same level, and return point.
23075 If there is no such heading, return nil.
23076 This is like outline-next-sibling, but invisible headings are ok."
23077 (let ((level (funcall outline-level)))
23078 (outline-next-heading)
23079 (while (and (not (eobp)) (> (funcall outline-level) level))
23080 (outline-next-heading))
23081 (unless (or (eobp) (< (funcall outline-level) level))
23082 (point))))
23084 (defun org-get-last-sibling ()
23085 "Move to previous heading of the same level, and return point.
23086 If there is no such heading, return nil."
23087 (let ((opoint (point))
23088 (level (funcall outline-level)))
23089 (outline-previous-heading)
23090 (when (and (/= (point) opoint) (outline-on-heading-p t))
23091 (while (and (> (funcall outline-level) level)
23092 (not (bobp)))
23093 (outline-previous-heading))
23094 (unless (< (funcall outline-level) level)
23095 (point)))))
23097 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23098 "Goto to the end of a subtree."
23099 ;; This contains an exact copy of the original function, but it uses
23100 ;; `org-back-to-heading', to make it work also in invisible
23101 ;; trees. And is uses an invisible-ok argument.
23102 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23103 ;; Furthermore, when used inside Org, finding the end of a large subtree
23104 ;; with many children and grandchildren etc, this can be much faster
23105 ;; than the outline version.
23106 (org-back-to-heading invisible-ok)
23107 (let ((first t)
23108 (level (funcall outline-level)))
23109 (if (and (derived-mode-p 'org-mode) (< level 1000))
23110 ;; A true heading (not a plain list item), in Org
23111 ;; This means we can easily find the end by looking
23112 ;; only for the right number of stars. Using a regexp to do
23113 ;; this is so much faster than using a Lisp loop.
23114 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23115 (forward-char 1)
23116 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23117 ;; something else, do it the slow way
23118 (while (and (not (eobp))
23119 (or first (> (funcall outline-level) level)))
23120 (setq first nil)
23121 (outline-next-heading)))
23122 (unless to-heading
23123 (when (memq (preceding-char) '(?\n ?\^M))
23124 ;; Go to end of line before heading
23125 (forward-char -1)
23126 (when (memq (preceding-char) '(?\n ?\^M))
23127 ;; leave blank line before heading
23128 (forward-char -1)))))
23129 (point))
23131 (defun org-end-of-meta-data (&optional full)
23132 "Skip planning line and properties drawer in current entry.
23133 When optional argument FULL is non-nil, also skip empty lines,
23134 clocking lines and regular drawers at the beginning of the
23135 entry."
23136 (org-back-to-heading t)
23137 (forward-line)
23138 (when (looking-at-p org-planning-line-re) (forward-line))
23139 (when (looking-at org-property-drawer-re)
23140 (goto-char (match-end 0))
23141 (forward-line))
23142 (when (and full (not (org-at-heading-p)))
23143 (catch 'exit
23144 (let ((end (save-excursion (outline-next-heading) (point)))
23145 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23146 (while (not (eobp))
23147 (cond ((looking-at-p org-drawer-regexp)
23148 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23149 (forward-line)
23150 (throw 'exit t)))
23151 ((looking-at-p re) (forward-line))
23152 (t (throw 'exit t))))))))
23154 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23155 "Move forward to the ARG'th subheading at same level as this one.
23156 Stop at the first and last subheadings of a superior heading.
23157 Normally this only looks at visible headings, but when INVISIBLE-OK is
23158 non-nil it will also look at invisible ones."
23159 (interactive "p")
23160 (let ((backward? (and arg (< arg 0))))
23161 (if (org-before-first-heading-p)
23162 (if backward? (goto-char (point-min)) (outline-next-heading))
23163 (org-back-to-heading invisible-ok)
23164 (unless backward? (end-of-line)) ;do not match current headline
23165 (let ((level (- (match-end 0) (match-beginning 0) 1))
23166 (f (if backward? #'re-search-backward #'re-search-forward))
23167 (count (if arg (abs arg) 1))
23168 (result (point)))
23169 (while (and (> count 0)
23170 (funcall f org-outline-regexp-bol nil 'move))
23171 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23172 (cond ((< l level) (setq count 0))
23173 ((and (= l level)
23174 (or invisible-ok
23175 (not (org-invisible-p
23176 (line-beginning-position)))))
23177 (cl-decf count)
23178 (when (= l level) (setq result (point)))))))
23179 (goto-char result))
23180 (beginning-of-line))))
23182 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23183 "Move backward to the ARG'th subheading at same level as this one.
23184 Stop at the first and last subheadings of a superior heading."
23185 (interactive "p")
23186 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23188 (defun org-next-visible-heading (arg)
23189 "Move to the next visible heading.
23191 This function wraps `outline-next-visible-heading' with
23192 `org-with-limited-levels' in order to skip over inline tasks and
23193 respect customization of `org-odd-levels-only'."
23194 (interactive "p")
23195 (org-with-limited-levels
23196 (outline-next-visible-heading arg)))
23198 (defun org-previous-visible-heading (arg)
23199 "Move to the previous visible heading.
23201 This function wraps `outline-previous-visible-heading' with
23202 `org-with-limited-levels' in order to skip over inline tasks and
23203 respect customization of `org-odd-levels-only'."
23204 (interactive "p")
23205 (org-with-limited-levels
23206 (outline-previous-visible-heading arg)))
23208 (defun org-forward-paragraph ()
23209 "Move forward to beginning of next paragraph or equivalent.
23211 The function moves point to the beginning of the next visible
23212 structural element, which can be a paragraph, a table, a list
23213 item, etc. It also provides some special moves for convenience:
23215 - On an affiliated keyword, jump to the beginning of the
23216 relative element.
23217 - On an item or a footnote definition, move to the second
23218 element inside, if any.
23219 - On a table or a property drawer, jump after it.
23220 - On a verse or source block, stop after blank lines."
23221 (interactive)
23222 (unless (eobp)
23223 (let* ((deactivate-mark nil)
23224 (element (org-element-at-point))
23225 (type (org-element-type element))
23226 (post-affiliated (org-element-property :post-affiliated element))
23227 (contents-begin (org-element-property :contents-begin element))
23228 (contents-end (org-element-property :contents-end element))
23229 (end (let ((end (org-element-property :end element)) (parent element))
23230 (while (and (setq parent (org-element-property :parent parent))
23231 (= (org-element-property :contents-end parent) end))
23232 (setq end (org-element-property :end parent)))
23233 end)))
23234 (cond ((not element)
23235 (skip-chars-forward " \r\t\n")
23236 (or (eobp) (beginning-of-line)))
23237 ;; On affiliated keywords, move to element's beginning.
23238 ((< (point) post-affiliated)
23239 (goto-char post-affiliated))
23240 ;; At a table row, move to the end of the table. Similarly,
23241 ;; at a node property, move to the end of the property
23242 ;; drawer.
23243 ((memq type '(node-property table-row))
23244 (goto-char (org-element-property
23245 :end (org-element-property :parent element))))
23246 ((memq type '(property-drawer table)) (goto-char end))
23247 ;; Consider blank lines as separators in verse and source
23248 ;; blocks to ease editing.
23249 ((memq type '(src-block verse-block))
23250 (when (eq type 'src-block)
23251 (setq contents-end
23252 (save-excursion (goto-char end)
23253 (skip-chars-backward " \r\t\n")
23254 (line-beginning-position))))
23255 (beginning-of-line)
23256 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23257 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23258 (goto-char end)
23259 (skip-chars-forward " \r\t\n")
23260 (if (= (point) contents-end) (goto-char end)
23261 (beginning-of-line))))
23262 ;; With no contents, just skip element.
23263 ((not contents-begin) (goto-char end))
23264 ;; If contents are invisible, skip the element altogether.
23265 ((org-invisible-p (line-end-position))
23266 (cl-case type
23267 (headline
23268 (org-with-limited-levels (outline-next-visible-heading 1)))
23269 ;; At a plain list, make sure we move to the next item
23270 ;; instead of skipping the whole list.
23271 (plain-list (forward-char)
23272 (org-forward-paragraph))
23273 (otherwise (goto-char end))))
23274 ((>= (point) contents-end) (goto-char end))
23275 ((>= (point) contents-begin)
23276 ;; This can only happen on paragraphs and plain lists.
23277 (cl-case type
23278 (paragraph (goto-char end))
23279 ;; At a plain list, try to move to second element in
23280 ;; first item, if possible.
23281 (plain-list (end-of-line)
23282 (org-forward-paragraph))))
23283 ;; When contents start on the middle of a line (e.g. in
23284 ;; items and footnote definitions), try to reach first
23285 ;; element starting after current line.
23286 ((> (line-end-position) contents-begin)
23287 (end-of-line)
23288 (org-forward-paragraph))
23289 (t (goto-char contents-begin))))))
23291 (defun org-backward-paragraph ()
23292 "Move backward to start of previous paragraph or equivalent.
23294 The function moves point to the beginning of the current
23295 structural element, which can be a paragraph, a table, a list
23296 item, etc., or to the beginning of the previous visible one if
23297 point is already there. It also provides some special moves for
23298 convenience:
23300 - On an affiliated keyword, jump to the first one.
23301 - On a table or a property drawer, move to its beginning.
23302 - On comment, example, export, src and verse blocks, stop
23303 before blank lines."
23304 (interactive)
23305 (unless (bobp)
23306 (let* ((deactivate-mark nil)
23307 (element (org-element-at-point))
23308 (type (org-element-type element))
23309 (contents-end (org-element-property :contents-end element))
23310 (post-affiliated (org-element-property :post-affiliated element))
23311 (begin (org-element-property :begin element))
23312 (special? ;blocks handled specially
23313 (memq type '(comment-block example-block export-block src-block
23314 verse-block)))
23315 (contents-begin
23316 (if special?
23317 ;; These types have no proper contents. Fake line
23318 ;; below the block opening line as contents beginning.
23319 (save-excursion (goto-char begin) (line-beginning-position 2))
23320 (org-element-property :contents-begin element))))
23321 (cond
23322 ((not element) (goto-char (point-min)))
23323 ((= (point) begin)
23324 (backward-char)
23325 (org-backward-paragraph))
23326 ((<= (point) post-affiliated) (goto-char begin))
23327 ;; Special behavior: on a table or a property drawer, move to
23328 ;; its beginning.
23329 ((memq type '(node-property table-row))
23330 (goto-char (org-element-property
23331 :post-affiliated (org-element-property :parent element))))
23332 (special?
23333 (if (<= (point) contents-begin) (goto-char post-affiliated)
23334 ;; Inside a verse block, see blank lines as paragraph
23335 ;; separators.
23336 (let ((origin (point)))
23337 (skip-chars-backward " \r\t\n" contents-begin)
23338 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23339 (skip-chars-forward " \r\t\n" origin)
23340 (if (= (point) origin) (goto-char contents-begin)
23341 (beginning-of-line))))))
23342 ((eq type 'paragraph) (goto-char contents-begin)
23343 ;; When at first paragraph in an item or a footnote definition,
23344 ;; move directly to beginning of line.
23345 (let ((parent-contents
23346 (org-element-property
23347 :contents-begin (org-element-property :parent element))))
23348 (when (and parent-contents (= parent-contents contents-begin))
23349 (beginning-of-line))))
23350 ;; At the end of a greater element, move to the beginning of
23351 ;; the last element within.
23352 ((and contents-end (>= (point) contents-end))
23353 (goto-char (1- contents-end))
23354 (org-backward-paragraph))
23355 (t (goto-char (or post-affiliated begin))))
23356 ;; Ensure we never leave point invisible.
23357 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23359 (defun org-forward-element ()
23360 "Move forward by one element.
23361 Move to the next element at the same level, when possible."
23362 (interactive)
23363 (cond ((eobp) (user-error "Cannot move further down"))
23364 ((org-with-limited-levels (org-at-heading-p))
23365 (let ((origin (point)))
23366 (goto-char (org-end-of-subtree nil t))
23367 (unless (org-with-limited-levels (org-at-heading-p))
23368 (goto-char origin)
23369 (user-error "Cannot move further down"))))
23371 (let* ((elem (org-element-at-point))
23372 (end (org-element-property :end elem))
23373 (parent (org-element-property :parent elem)))
23374 (cond ((and parent (= (org-element-property :contents-end parent) end))
23375 (goto-char (org-element-property :end parent)))
23376 ((integer-or-marker-p end) (goto-char end))
23377 (t (message "No element at point")))))))
23379 (defun org-backward-element ()
23380 "Move backward by one element.
23381 Move to the previous element at the same level, when possible."
23382 (interactive)
23383 (cond ((bobp) (user-error "Cannot move further up"))
23384 ((org-with-limited-levels (org-at-heading-p))
23385 ;; At a headline, move to the previous one, if any, or stay
23386 ;; here.
23387 (let ((origin (point)))
23388 (org-with-limited-levels (org-backward-heading-same-level 1))
23389 ;; When current headline has no sibling above, move to its
23390 ;; parent.
23391 (when (= (point) origin)
23392 (or (org-with-limited-levels (org-up-heading-safe))
23393 (progn (goto-char origin)
23394 (user-error "Cannot move further up"))))))
23396 (let* ((elem (org-element-at-point))
23397 (beg (org-element-property :begin elem)))
23398 (cond
23399 ;; Move to beginning of current element if point isn't
23400 ;; there already.
23401 ((null beg) (message "No element at point"))
23402 ((/= (point) beg) (goto-char beg))
23403 (t (goto-char beg)
23404 (skip-chars-backward " \r\t\n")
23405 (unless (bobp)
23406 (let ((prev (org-element-at-point)))
23407 (goto-char (org-element-property :begin prev))
23408 (while (and (setq prev (org-element-property :parent prev))
23409 (<= (org-element-property :end prev) beg))
23410 (goto-char (org-element-property :begin prev)))))))))))
23412 (defun org-up-element ()
23413 "Move to upper element."
23414 (interactive)
23415 (if (org-with-limited-levels (org-at-heading-p))
23416 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23417 (let* ((elem (org-element-at-point))
23418 (parent (org-element-property :parent elem)))
23419 (if parent (goto-char (org-element-property :begin parent))
23420 (if (org-with-limited-levels (org-before-first-heading-p))
23421 (user-error "No surrounding element")
23422 (org-with-limited-levels (org-back-to-heading)))))))
23424 (defun org-down-element ()
23425 "Move to inner element."
23426 (interactive)
23427 (let ((element (org-element-at-point)))
23428 (cond
23429 ((memq (org-element-type element) '(plain-list table))
23430 (goto-char (org-element-property :contents-begin element))
23431 (forward-char))
23432 ((memq (org-element-type element) org-element-greater-elements)
23433 ;; If contents are hidden, first disclose them.
23434 (when (org-invisible-p (line-end-position)) (org-cycle))
23435 (goto-char (or (org-element-property :contents-begin element)
23436 (user-error "No content for this element"))))
23437 (t (user-error "No inner element")))))
23439 (defun org-drag-element-backward ()
23440 "Move backward element at point."
23441 (interactive)
23442 (let ((elem (or (org-element-at-point)
23443 (user-error "No element at point"))))
23444 (if (eq (org-element-type elem) 'headline)
23445 ;; Preserve point when moving a whole tree, even if point was
23446 ;; on blank lines below the headline.
23447 (let ((offset (skip-chars-backward " \t\n")))
23448 (unwind-protect (org-move-subtree-up)
23449 (forward-char (- offset))))
23450 (let ((prev-elem
23451 (save-excursion
23452 (goto-char (org-element-property :begin elem))
23453 (skip-chars-backward " \r\t\n")
23454 (unless (bobp)
23455 (let* ((beg (org-element-property :begin elem))
23456 (prev (org-element-at-point))
23457 (up prev))
23458 (while (and (setq up (org-element-property :parent up))
23459 (<= (org-element-property :end up) beg))
23460 (setq prev up))
23461 prev)))))
23462 ;; Error out if no previous element or previous element is
23463 ;; a parent of the current one.
23464 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23465 (user-error "Cannot drag element backward")
23466 (let ((pos (point)))
23467 (org-element-swap-A-B prev-elem elem)
23468 (goto-char (+ (org-element-property :begin prev-elem)
23469 (- pos (org-element-property :begin elem))))))))))
23471 (defun org-drag-element-forward ()
23472 "Move forward element at point."
23473 (interactive)
23474 (let* ((pos (point))
23475 (elem (or (org-element-at-point)
23476 (user-error "No element at point"))))
23477 (when (= (point-max) (org-element-property :end elem))
23478 (user-error "Cannot drag element forward"))
23479 (goto-char (org-element-property :end elem))
23480 (let ((next-elem (org-element-at-point)))
23481 (when (or (org-element-nested-p elem next-elem)
23482 (and (eq (org-element-type next-elem) 'headline)
23483 (not (eq (org-element-type elem) 'headline))))
23484 (goto-char pos)
23485 (user-error "Cannot drag element forward"))
23486 ;; Compute new position of point: it's shifted by NEXT-ELEM
23487 ;; body's length (without final blanks) and by the length of
23488 ;; blanks between ELEM and NEXT-ELEM.
23489 (let ((size-next (- (save-excursion
23490 (goto-char (org-element-property :end next-elem))
23491 (skip-chars-backward " \r\t\n")
23492 (forward-line)
23493 ;; Small correction if buffer doesn't end
23494 ;; with a newline character.
23495 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23496 (org-element-property :begin next-elem)))
23497 (size-blank (- (org-element-property :end elem)
23498 (save-excursion
23499 (goto-char (org-element-property :end elem))
23500 (skip-chars-backward " \r\t\n")
23501 (forward-line)
23502 (point)))))
23503 (org-element-swap-A-B elem next-elem)
23504 (goto-char (+ pos size-next size-blank))))))
23506 (defun org-drag-line-forward (arg)
23507 "Drag the line at point ARG lines forward."
23508 (interactive "p")
23509 (dotimes (_ (abs arg))
23510 (let ((c (current-column)))
23511 (if (< 0 arg)
23512 (progn
23513 (beginning-of-line 2)
23514 (transpose-lines 1)
23515 (beginning-of-line 0))
23516 (transpose-lines 1)
23517 (beginning-of-line -1))
23518 (org-move-to-column c))))
23520 (defun org-drag-line-backward (arg)
23521 "Drag the line at point ARG lines backward."
23522 (interactive "p")
23523 (org-drag-line-forward (- arg)))
23525 (defun org-mark-element ()
23526 "Put point at beginning of this element, mark at end.
23528 Interactively, if this command is repeated or (in Transient Mark
23529 mode) if the mark is active, it marks the next element after the
23530 ones already marked."
23531 (interactive)
23532 (let (deactivate-mark)
23533 (if (and (called-interactively-p 'any)
23534 (or (and (eq last-command this-command) (mark t))
23535 (and transient-mark-mode mark-active)))
23536 (set-mark
23537 (save-excursion
23538 (goto-char (mark))
23539 (goto-char (org-element-property :end (org-element-at-point)))))
23540 (let ((element (org-element-at-point)))
23541 (end-of-line)
23542 (push-mark (org-element-property :end element) t t)
23543 (goto-char (org-element-property :begin element))))))
23545 (defun org-narrow-to-element ()
23546 "Narrow buffer to current element."
23547 (interactive)
23548 (let ((elem (org-element-at-point)))
23549 (cond
23550 ((eq (car elem) 'headline)
23551 (narrow-to-region
23552 (org-element-property :begin elem)
23553 (org-element-property :end elem)))
23554 ((memq (car elem) org-element-greater-elements)
23555 (narrow-to-region
23556 (org-element-property :contents-begin elem)
23557 (org-element-property :contents-end elem)))
23559 (narrow-to-region
23560 (org-element-property :begin elem)
23561 (org-element-property :end elem))))))
23563 (defun org-transpose-element ()
23564 "Transpose current and previous elements, keeping blank lines between.
23565 Point is moved after both elements."
23566 (interactive)
23567 (org-skip-whitespace)
23568 (let ((end (org-element-property :end (org-element-at-point))))
23569 (org-drag-element-backward)
23570 (goto-char end)))
23572 (defun org-unindent-buffer ()
23573 "Un-indent the visible part of the buffer.
23574 Relative indentation (between items, inside blocks, etc.) isn't
23575 modified."
23576 (interactive)
23577 (unless (eq major-mode 'org-mode)
23578 (user-error "Cannot un-indent a buffer not in Org mode"))
23579 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23580 (unindent-tree
23581 (lambda (contents)
23582 (dolist (element (reverse contents))
23583 (if (memq (org-element-type element) '(headline section))
23584 (funcall unindent-tree (org-element-contents element))
23585 (save-excursion
23586 (save-restriction
23587 (narrow-to-region
23588 (org-element-property :begin element)
23589 (org-element-property :end element))
23590 (org-do-remove-indentation))))))))
23591 (funcall unindent-tree (org-element-contents parse-tree))))
23593 (defun org-make-options-regexp (kwds &optional extra)
23594 "Make a regular expression for keyword lines.
23595 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23596 when non-nil, is a regexp matching keywords names."
23597 (concat "^[ \t]*#\\+\\("
23598 (regexp-opt kwds)
23599 (and extra (concat (and kwds "\\|") extra))
23600 "\\):[ \t]*\\(.*\\)"))
23603 ;;; Finish up
23605 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23606 (lambda () (add-hook 'change-major-mode-hook
23607 'org-show-all 'append 'local)))
23609 (provide 'org)
23611 (run-hooks 'org-load-hook)
23613 ;;; org.el ends here