Improve `org-fix-tags-on-the-fly'
[org-mode/org-tableheadings.git] / lisp / org.el
blobe7dc3dd278e11f94dbe325f3ebfbfab3a3e6dc01
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: https://orgmode.org
10 ;; Version: 9.1.12
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
46 ;; webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; https://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; https://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (defvar org-inlinetask-min-level)
72 ;;;; Require other packages
74 (require 'cl-lib)
76 (eval-when-compile (require 'gnus-sum))
78 (require 'calendar)
79 (require 'find-func)
80 (require 'format-spec)
82 (or (eq this-command 'eval-buffer)
83 (condition-case nil
84 (load (concat (file-name-directory load-file-name)
85 "org-loaddefs.el")
86 nil t t t)
87 (error
88 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
89 (sit-for 3)
90 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
91 (sit-for 3))))
93 (require 'org-macs)
94 (require 'org-compat)
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 (defvar org-outline-regexp "\\*+ "
99 "Regexp to match Org headlines.")
101 (defvar org-outline-regexp-bol "^\\*+ "
102 "Regexp to match Org headlines.
103 This is similar to `org-outline-regexp' but additionally makes
104 sure that we are at the beginning of the line.")
106 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
107 "Matches a headline, putting stars and text into groups.
108 Stars are put in group 1 and the trimmed body in group 2.")
110 (declare-function calendar-check-holidays "holidays" (date))
111 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
112 (declare-function cdlatex-math-symbol "ext:cdlatex")
113 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocking-buffer "org-clock" ())
130 (declare-function org-clocktable-shift "org-clock" (dir n))
131 (declare-function
132 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-link-parser "org-element" ())
142 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
143 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
144 (declare-function org-element-property "org-element" (property element))
145 (declare-function org-element-put-property "org-element" (element property value))
146 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
147 (declare-function org-element-type "org-element" (element))
148 (declare-function org-element-update-syntax "org-element" ())
149 (declare-function org-id-find-id-file "org-id" (id))
150 (declare-function org-id-get-create "org-id" (&optional force))
151 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
152 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
153 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
154 (declare-function org-plot/gnuplot "org-plot" (&optional params))
155 (declare-function org-table-align "org-table" ())
156 (declare-function org-table-begin "org-table" (&optional table-type))
157 (declare-function org-table-beginning-of-field "org-table" (&optional n))
158 (declare-function org-table-blank-field "org-table" ())
159 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
160 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
161 (declare-function org-table-cut-region "org-table" (beg end))
162 (declare-function org-table-edit-field "org-table" (arg))
163 (declare-function org-table-end "org-table" (&optional table-type))
164 (declare-function org-table-end-of-field "org-table" (&optional n))
165 (declare-function org-table-insert-row "org-table" (&optional arg))
166 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
167 (declare-function org-table-maybe-eval-formula "org-table" ())
168 (declare-function org-table-maybe-recalculate-line "org-table" ())
169 (declare-function org-table-next-row "org-table" ())
170 (declare-function org-table-paste-rectangle "org-table" ())
171 (declare-function org-table-recalculate "org-table" (&optional all noalign))
172 (declare-function
173 org-table-sort-lines "org-table"
174 (&optional with-case sorting-type getkey-func compare-func interactive?))
175 (declare-function org-table-shrink "org-table" (&optional begin end))
176 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp)
186 (defvar org-element-paragraph-separate)
187 (defvar org-indent-indentation-per-level)
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Ebnf2ps" ebnf2ps)
262 (const :tag "Emacs Lisp" emacs-lisp)
263 (const :tag "Forth" forth)
264 (const :tag "Fortran" fortran)
265 (const :tag "Gnuplot" gnuplot)
266 (const :tag "Haskell" haskell)
267 (const :tag "hledger" hledger)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "Vala" vala))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 \\<org-mode-map>
376 A deadline is this string, followed by a time stamp. It must be
377 a word, terminated by a colon. You can insert a schedule keyword
378 and a timestamp with `\\[org-deadline]'.")
380 (defvar org-scheduled-string "SCHEDULED:"
381 "String to mark scheduled TODO entries.
382 \\<org-mode-map>
383 A schedule is this string, followed by a time stamp. It must be
384 a word, terminated by a colon. You can insert a schedule keyword
385 and a timestamp with `\\[org-schedule]'.")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (defconst org-tag-re "[[:alnum:]_@#%]+"
525 "Regexp matching a single tag.")
527 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
528 "Regexp matching the tag group at the end of a line, with leading spaces.
529 Tags are stored in match group 1. Match group 2 stores the tags
530 without the enclosing colons.")
532 (defconst org-tag-line-re
533 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
534 "Regexp matching tags in a headline.
535 Tags are stored in match group 1. Match group 2 stores the tags
536 without the enclosing colons.")
538 (eval-and-compile
539 (defconst org-comment-string "COMMENT"
540 "Entries starting with this keyword will never be exported.
541 \\<org-mode-map>
542 An entry can be toggled between COMMENT and normal with
543 `\\[org-toggle-comment]'."))
546 ;;;; LaTeX Environments and Fragments
548 (defconst org-latex-regexps
549 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
550 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
551 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
552 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
554 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
555 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
556 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
557 "Regular expressions for matching embedded LaTeX.")
559 ;;;; Node Property
561 (defconst org-effort-property "Effort"
562 "The property that is being used to keep track of effort estimates.
563 Effort estimates given in this property need to have the format H:MM.")
565 ;;;; Table
567 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
568 "Detect an org-type or table-type table.")
570 (defconst org-table-line-regexp "^[ \t]*|"
571 "Detect an org-type table line.")
573 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
574 "Detect an org-type table line.")
576 (defconst org-table-hline-regexp "^[ \t]*|-"
577 "Detect an org-type table hline.")
579 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
580 "Detect a table-type table hline.")
582 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
583 "Detect the first line outside a table when searching from within it.
584 This works for both table types.")
586 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
587 "Detect a #+TBLFM line.")
589 ;;;; Timestamp
591 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
592 "Regular expression for fast time stamp matching.")
594 (defconst org-ts-regexp-inactive
595 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
596 "Regular expression for fast inactive time stamp matching.")
598 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
599 "Regular expression for fast time stamp matching.")
601 (defconst org-ts-regexp0
602 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
603 "Regular expression matching time strings for analysis.
604 This one does not require the space after the date, so it can be used
605 on a string that terminates immediately after the date.")
607 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
608 "Regular expression matching time strings for analysis.")
610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
611 "Regular expression matching time stamps, with groups.")
613 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
614 "Regular expression matching time stamps (also [..]), with groups.")
616 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
617 "Regular expression matching a time stamp range.")
619 (defconst org-tr-regexp-both
620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
621 "Regular expression matching a time stamp range.")
623 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
624 org-ts-regexp "\\)?")
625 "Regular expression matching a time stamp or time stamp range.")
627 (defconst org-tsr-regexp-both
628 (concat org-ts-regexp-both "\\(--?-?"
629 org-ts-regexp-both "\\)?")
630 "Regular expression matching a time stamp or time stamp range.
631 The time stamps may be either active or inactive.")
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
639 "Formats for `format-time-string' which are used for time stamps.")
642 ;;; The custom variables
644 (defgroup org nil
645 "Outline-based notes management and organizer."
646 :tag "Org"
647 :group 'outlines
648 :group 'calendar)
650 (defcustom org-mode-hook nil
651 "Mode hook for Org mode, run after the mode was turned on."
652 :group 'org
653 :type 'hook)
655 (defcustom org-load-hook nil
656 "Hook that is run after org.el has been loaded."
657 :group 'org
658 :type 'hook)
660 (defcustom org-log-buffer-setup-hook nil
661 "Hook that is run after an Org log buffer is created."
662 :group 'org
663 :version "24.1"
664 :type 'hook)
666 (defvar org-modules) ; defined below
667 (defvar org-modules-loaded nil
668 "Have the modules been loaded already?")
670 (defun org-load-modules-maybe (&optional force)
671 "Load all extensions listed in `org-modules'."
672 (when (or force (not org-modules-loaded))
673 (dolist (ext org-modules)
674 (condition-case nil (require ext)
675 (error (message "Problems while trying to load feature `%s'" ext))))
676 (setq org-modules-loaded t)))
678 (defun org-set-modules (var value)
679 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
680 (set var value)
681 (when (featurep 'org)
682 (org-load-modules-maybe 'force)
683 (org-element-cache-reset 'all)))
685 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
686 "Modules that should always be loaded together with org.el.
688 If a description starts with <C>, the file is not part of Emacs
689 and loading it will require that you have downloaded and properly
690 installed the Org mode distribution.
692 You can also use this system to load external packages (i.e. neither Org
693 core modules, nor modules from the CONTRIB directory). Just add symbols
694 to the end of the list. If the package is called org-xyz.el, then you need
695 to add the symbol `xyz', and the package must have a call to:
697 (provide \\='org-xyz)
699 For export specific modules, see also `org-export-backends'."
700 :group 'org
701 :set 'org-set-modules
702 :version "26.1"
703 :package-version '(Org . "9.2")
704 :type
705 '(set :greedy t
706 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
707 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
708 (const :tag " crypt: Encryption of subtrees" org-crypt)
709 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
710 (const :tag " docview: Links to doc-view buffers" org-docview)
711 (const :tag " eww: Store link to url of eww" org-eww)
712 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
713 (const :tag " habit: Track your consistency with habits" org-habit)
714 (const :tag " id: Global IDs for identifying entries" org-id)
715 (const :tag " info: Links to Info nodes" org-info)
716 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
717 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
718 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
719 (const :tag " mouse: Additional mouse support" org-mouse)
720 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
721 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
722 (const :tag " tempo: Fast completion for structures" org-tempo)
723 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
725 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
726 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
727 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
728 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
729 (const :tag "C collector: Collect properties into tables" org-collector)
730 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
731 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
732 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
733 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
734 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
735 (const :tag "C eval: Include command output as text" org-eval)
736 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
737 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
738 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
739 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
740 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
741 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
742 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
743 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
744 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
745 (const :tag "C man: Support for links to manpages in Org mode" org-man)
746 (const :tag "C mew: Links to Mew folders/messages" org-mew)
747 (const :tag "C mtags: Support for muse-like tags" org-mtags)
748 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
749 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
750 (const :tag "C registry: A registry for Org links" org-registry)
751 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
752 (const :tag "C secretary: Team management with Org" org-secretary)
753 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
754 (const :tag "C toc: Table of contents for Org buffer" org-toc)
755 (const :tag "C track: Keep up with Org mode development" org-track)
756 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
757 (const :tag "C vm: Links to VM folders/messages" org-vm)
758 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
759 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
760 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
762 (defvar org-export-registered-backends) ; From ox.el.
763 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
764 (declare-function org-export-backend-name "ox" (backend) t)
765 (defcustom org-export-backends '(ascii html icalendar latex odt)
766 "List of export back-ends that should be always available.
768 If a description starts with <C>, the file is not part of Emacs
769 and loading it will require that you have downloaded and properly
770 installed the Org mode distribution.
772 Unlike to `org-modules', libraries in this list will not be
773 loaded along with Org, but only once the export framework is
774 needed.
776 This variable needs to be set before org.el is loaded. If you
777 need to make a change while Emacs is running, use the customize
778 interface or run the following code, where VAL stands for the new
779 value of the variable, after updating it:
781 (progn
782 (setq org-export-registered-backends
783 (cl-remove-if-not
784 (lambda (backend)
785 (let ((name (org-export-backend-name backend)))
786 (or (memq name val)
787 (catch \\='parentp
788 (dolist (b val)
789 (and (org-export-derived-backend-p b name)
790 (throw \\='parentp t)))))))
791 org-export-registered-backends))
792 (let ((new-list (mapcar #\\='org-export-backend-name
793 org-export-registered-backends)))
794 (dolist (backend val)
795 (cond
796 ((not (load (format \"ox-%s\" backend) t t))
797 (message \"Problems while trying to load export back-end \\=`%s\\='\"
798 backend))
799 ((not (memq backend new-list)) (push backend new-list))))
800 (set-default \\='org-export-backends new-list)))
802 Adding a back-end to this list will also pull the back-end it
803 depends on, if any."
804 :group 'org
805 :group 'org-export
806 :version "26.1"
807 :package-version '(Org . "9.0")
808 :initialize 'custom-initialize-set
809 :set (lambda (var val)
810 (if (not (featurep 'ox)) (set-default var val)
811 ;; Any back-end not required anymore (not present in VAL and not
812 ;; a parent of any back-end in the new value) is removed from the
813 ;; list of registered back-ends.
814 (setq org-export-registered-backends
815 (cl-remove-if-not
816 (lambda (backend)
817 (let ((name (org-export-backend-name backend)))
818 (or (memq name val)
819 (catch 'parentp
820 (dolist (b val)
821 (and (org-export-derived-backend-p b name)
822 (throw 'parentp t)))))))
823 org-export-registered-backends))
824 ;; Now build NEW-LIST of both new back-ends and required
825 ;; parents.
826 (let ((new-list (mapcar #'org-export-backend-name
827 org-export-registered-backends)))
828 (dolist (backend val)
829 (cond
830 ((not (load (format "ox-%s" backend) t t))
831 (message "Problems while trying to load export back-end `%s'"
832 backend))
833 ((not (memq backend new-list)) (push backend new-list))))
834 ;; Set VAR to that list with fixed dependencies.
835 (set-default var new-list))))
836 :type '(set :greedy t
837 (const :tag " ascii Export buffer to ASCII format" ascii)
838 (const :tag " beamer Export buffer to Beamer presentation" beamer)
839 (const :tag " html Export buffer to HTML format" html)
840 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
841 (const :tag " latex Export buffer to LaTeX format" latex)
842 (const :tag " man Export buffer to MAN format" man)
843 (const :tag " md Export buffer to Markdown format" md)
844 (const :tag " odt Export buffer to ODT format" odt)
845 (const :tag " org Export buffer to Org format" org)
846 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
847 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
848 (const :tag "C deck Export buffer to deck.js presentations" deck)
849 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
850 (const :tag "C groff Export buffer to Groff format" groff)
851 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
852 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
853 (const :tag "C s5 Export buffer to s5 presentations" s5)
854 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
856 (eval-after-load 'ox
857 '(dolist (backend org-export-backends)
858 (condition-case nil (require (intern (format "ox-%s" backend)))
859 (error (message "Problems while trying to load export back-end `%s'"
860 backend)))))
862 (defcustom org-support-shift-select nil
863 "Non-nil means make shift-cursor commands select text when possible.
864 \\<org-mode-map>\
866 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
867 start selecting a region, or enlarge regions started in this way.
868 In Org mode, in special contexts, these same keys are used for
869 other purposes, important enough to compete with shift selection.
870 Org tries to balance these needs by supporting `shift-select-mode'
871 outside these special contexts, under control of this variable.
873 The default of this variable is nil, to avoid confusing behavior. Shifted
874 cursor keys will then execute Org commands in the following contexts:
875 - on a headline, changing TODO state (left/right) and priority (up/down)
876 - on a time stamp, changing the time
877 - in a plain list item, changing the bullet type
878 - in a property definition line, switching between allowed values
879 - in the BEGIN line of a clock table (changing the time block).
880 Outside these contexts, the commands will throw an error.
882 When this variable is t and the cursor is not in a special
883 context, Org mode will support shift-selection for making and
884 enlarging regions. To make this more effective, the bullet
885 cycling will no longer happen anywhere in an item line, but only
886 if the cursor is exactly on the bullet.
888 If you set this variable to the symbol `always', then the keys
889 will not be special in headlines, property lines, and item lines,
890 to make shift selection work there as well. If this is what you
891 want, you can use the following alternative commands:
892 `\\[org-todo]' and `\\[org-priority]' \
893 to change TODO state and priority,
894 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
895 can be used to switch TODO sets,
896 `\\[org-ctrl-c-minus]' to cycle item bullet types,
897 and properties can be edited by hand or in column view.
899 However, when the cursor is on a timestamp, shift-cursor commands
900 will still edit the time stamp - this is just too good to give up."
901 :group 'org
902 :type '(choice
903 (const :tag "Never" nil)
904 (const :tag "When outside special context" t)
905 (const :tag "Everywhere except timestamps" always)))
907 (defcustom org-loop-over-headlines-in-active-region nil
908 "Shall some commands act upon headlines in the active region?
910 When set to t, some commands will be performed in all headlines
911 within the active region.
913 When set to `start-level', some commands will be performed in all
914 headlines within the active region, provided that these headlines
915 are of the same level than the first one.
917 When set to a string, those commands will be performed on the
918 matching headlines within the active region. Such string must be
919 a tags/property/todo match as it is used in the agenda tags view.
921 The list of commands is: `org-schedule', `org-deadline',
922 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
923 `org-archive-to-archive-sibling'. The archiving commands skip
924 already archived entries."
925 :type '(choice (const :tag "Don't loop" nil)
926 (const :tag "All headlines in active region" t)
927 (const :tag "In active region, headlines at the same level than the first one" start-level)
928 (string :tag "Tags/Property/Todo matcher"))
929 :version "24.1"
930 :group 'org-todo
931 :group 'org-archive)
933 (defcustom org-startup-folded t
934 "Non-nil means entering Org mode will switch to OVERVIEW.
936 This can also be configured on a per-file basis by adding one of
937 the following lines anywhere in the buffer:
939 #+STARTUP: fold (or `overview', this is equivalent)
940 #+STARTUP: nofold (or `showall', this is equivalent)
941 #+STARTUP: content
942 #+STARTUP: showeverything
944 Set `org-agenda-inhibit-startup' to a non-nil value if you want
945 to ignore this option when Org opens agenda files for the first
946 time."
947 :group 'org-startup
948 :type '(choice
949 (const :tag "nofold: show all" nil)
950 (const :tag "fold: overview" t)
951 (const :tag "content: all headlines" content)
952 (const :tag "show everything, even drawers" showeverything)))
954 (defcustom org-startup-truncated t
955 "Non-nil means entering Org mode will set `truncate-lines'.
956 This is useful since some lines containing links can be very long and
957 uninteresting. Also tables look terrible when wrapped.
959 The variable `org-startup-truncated' allows to configure
960 truncation for Org mode different to the other modes that use the
961 variable `truncate-lines' and as a shortcut instead of putting
962 the variable `truncate-lines' into the `org-mode-hook'. If one
963 wants to configure truncation for Org mode not statically but
964 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
965 the variable `truncate-lines' has to be used because in such a
966 case it is too late to set the variable `org-startup-truncated'."
967 :group 'org-startup
968 :type 'boolean)
970 (defcustom org-startup-indented nil
971 "Non-nil means turn on `org-indent-mode' on startup.
972 This can also be configured on a per-file basis by adding one of
973 the following lines anywhere in the buffer:
975 #+STARTUP: indent
976 #+STARTUP: noindent"
977 :group 'org-structure
978 :type '(choice
979 (const :tag "Not" nil)
980 (const :tag "Globally (slow on startup in large files)" t)))
982 (defcustom org-use-sub-superscripts t
983 "Non-nil means interpret \"_\" and \"^\" for display.
985 If you want to control how Org exports those characters, see
986 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
987 used to be an alias for `org-export-with-sub-superscripts' in
988 Org <8.0, it is not anymore.
990 When this option is turned on, you can use TeX-like syntax for
991 sub- and superscripts within the buffer. Several characters after
992 \"_\" or \"^\" will be considered as a single item - so grouping
993 with {} is normally not needed. For example, the following things
994 will be parsed as single sub- or superscripts:
996 10^24 or 10^tau several digits will be considered 1 item.
997 10^-12 or 10^-tau a leading sign with digits or a word
998 x^2-y^3 will be read as x^2 - y^3, because items are
999 terminated by almost any nonword/nondigit char.
1000 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1002 Still, ambiguity is possible. So when in doubt, use {} to enclose
1003 the sub/superscript. If you set this variable to the symbol `{}',
1004 the braces are *required* in order to trigger interpretations as
1005 sub/superscript. This can be helpful in documents that need \"_\"
1006 frequently in plain text."
1007 :group 'org-startup
1008 :version "24.4"
1009 :package-version '(Org . "8.0")
1010 :type '(choice
1011 (const :tag "Always interpret" t)
1012 (const :tag "Only with braces" {})
1013 (const :tag "Never interpret" nil)))
1015 (defcustom org-startup-with-beamer-mode nil
1016 "Non-nil means turn on `org-beamer-mode' on startup.
1017 This can also be configured on a per-file basis by adding one of
1018 the following lines anywhere in the buffer:
1020 #+STARTUP: beamer"
1021 :group 'org-startup
1022 :version "24.1"
1023 :type 'boolean)
1025 (defcustom org-startup-align-all-tables nil
1026 "Non-nil means align all tables when visiting a file.
1027 This can also be configured on a per-file basis by adding one of
1028 the following lines anywhere in the buffer:
1029 #+STARTUP: align
1030 #+STARTUP: noalign"
1031 :group 'org-startup
1032 :type 'boolean)
1034 (defcustom org-startup-shrink-all-tables nil
1035 "Non-nil means shrink all table columns with a width cookie.
1036 This can also be configured on a per-file basis by adding one of
1037 the following lines anywhere in the buffer:
1038 #+STARTUP: shrink"
1039 :group 'org-startup
1040 :type 'boolean
1041 :version "27.1"
1042 :package-version '(Org . "9.2")
1043 :safe #'booleanp)
1045 (defcustom org-startup-with-inline-images nil
1046 "Non-nil means show inline images when loading a new Org file.
1047 This can also be configured on a per-file basis by adding one of
1048 the following lines anywhere in the buffer:
1049 #+STARTUP: inlineimages
1050 #+STARTUP: noinlineimages"
1051 :group 'org-startup
1052 :version "24.1"
1053 :type 'boolean)
1055 (defcustom org-startup-with-latex-preview nil
1056 "Non-nil means preview LaTeX fragments when loading a new Org file.
1058 This can also be configured on a per-file basis by adding one of
1059 the following lines anywhere in the buffer:
1060 #+STARTUP: latexpreview
1061 #+STARTUP: nolatexpreview"
1062 :group 'org-startup
1063 :version "24.4"
1064 :package-version '(Org . "8.0")
1065 :type 'boolean)
1067 (defcustom org-insert-mode-line-in-empty-file nil
1068 "Non-nil means insert the first line setting Org mode in empty files.
1069 When the function `org-mode' is called interactively in an empty file, this
1070 normally means that the file name does not automatically trigger Org mode.
1071 To ensure that the file will always be in Org mode in the future, a
1072 line enforcing Org mode will be inserted into the buffer, if this option
1073 has been set."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-replace-disputed-keys nil
1078 "Non-nil means use alternative key bindings for some keys.
1080 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1081 These keys are also used by other packages like Shift Select mode,
1082 CUA mode or Windmove. If you want to use Org mode together with
1083 one of these other modes, or more generally if you would like to
1084 move some Org mode commands to other keys, set this variable and
1085 configure the keys with the variable `org-disputed-keys'.
1087 This option is only relevant at load-time of Org mode, and must be set
1088 *before* org.el is loaded. Changing it requires a restart of Emacs to
1089 become effective."
1090 :group 'org-startup
1091 :type 'boolean)
1093 (defcustom org-use-extra-keys nil
1094 "Non-nil means use extra key sequence definitions for certain commands.
1095 This happens automatically if `window-system' is nil. This
1096 variable lets you do the same manually. You must set it before
1097 loading Org."
1098 :group 'org-startup
1099 :type 'boolean)
1101 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1103 (defcustom org-disputed-keys
1104 '(([(shift up)] . [(meta p)])
1105 ([(shift down)] . [(meta n)])
1106 ([(shift left)] . [(meta -)])
1107 ([(shift right)] . [(meta +)])
1108 ([(control shift right)] . [(meta shift +)])
1109 ([(control shift left)] . [(meta shift -)]))
1110 "Keys for which Org mode and other modes compete.
1111 This is an alist, cars are the default keys, second element specifies
1112 the alternative to use when `org-replace-disputed-keys' is t.
1114 Keys can be specified in any syntax supported by `define-key'.
1115 The value of this option takes effect only at Org mode startup,
1116 therefore you'll have to restart Emacs to apply it after changing."
1117 :group 'org-startup
1118 :type 'alist)
1120 (defun org-key (key)
1121 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1122 Or return the original if not disputed."
1123 (when org-replace-disputed-keys
1124 (let* ((nkey (key-description key))
1125 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1126 org-disputed-keys)))
1127 (setq key (if x (cdr x) key))))
1128 key)
1130 (defun org-defkey (keymap key def)
1131 "Define a key, possibly translated, as returned by `org-key'."
1132 (define-key keymap (org-key key) def))
1134 (defcustom org-ellipsis nil
1135 "The ellipsis to use in the Org mode outline.
1137 When nil, just use the standard three dots. When a non-empty string,
1138 use that string instead.
1140 The change affects only Org mode (which will then use its own display table).
1141 Changing this requires executing `\\[org-mode]' in a buffer to become
1142 effective."
1143 :group 'org-startup
1144 :type '(choice (const :tag "Default" nil)
1145 (string :tag "String" :value "...#"))
1146 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1148 (defvar org-display-table nil
1149 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1151 (defgroup org-keywords nil
1152 "Keywords in Org mode."
1153 :tag "Org Keywords"
1154 :group 'org)
1156 (defcustom org-closed-keep-when-no-todo nil
1157 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1158 :group 'org-todo
1159 :group 'org-keywords
1160 :version "24.4"
1161 :package-version '(Org . "8.0")
1162 :type 'boolean)
1164 (defgroup org-structure nil
1165 "Options concerning the general structure of Org files."
1166 :tag "Org Structure"
1167 :group 'org)
1169 (defgroup org-reveal-location nil
1170 "Options about how to make context of a location visible."
1171 :tag "Org Reveal Location"
1172 :group 'org-structure)
1174 (defcustom org-show-context-detail '((agenda . local)
1175 (bookmark-jump . lineage)
1176 (isearch . lineage)
1177 (default . ancestors))
1178 "Alist between context and visibility span when revealing a location.
1180 \\<org-mode-map>Some actions may move point into invisible
1181 locations. As a consequence, Org always expose a neighborhood
1182 around point. How much is shown depends on the initial action,
1183 or context. Valid contexts are
1185 agenda when exposing an entry from the agenda
1186 org-goto when using the command `org-goto' (`\\[org-goto]')
1187 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1188 tags-tree when constructing a sparse tree based on tags matches
1189 link-search when exposing search matches associated with a link
1190 mark-goto when exposing the jump goal of a mark
1191 bookmark-jump when exposing a bookmark location
1192 isearch when exiting from an incremental search
1193 default default for all contexts not set explicitly
1195 Allowed visibility spans are
1197 minimal show current headline; if point is not on headline,
1198 also show entry
1200 local show current headline, entry and next headline
1202 ancestors show current headline and its direct ancestors; if
1203 point is not on headline, also show entry
1205 lineage show current headline, its direct ancestors and all
1206 their children; if point is not on headline, also show
1207 entry and first child
1209 tree show current headline, its direct ancestors and all
1210 their children; if point is not on headline, also show
1211 entry and all children
1213 canonical show current headline, its direct ancestors along with
1214 their entries and children; if point is not located on
1215 the headline, also show current entry and all children
1217 As special cases, a nil or t value means show all contexts in
1218 `minimal' or `canonical' view, respectively.
1220 Some views can make displayed information very compact, but also
1221 make it harder to edit the location of the match. In such
1222 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1223 more context."
1224 :group 'org-reveal-location
1225 :version "26.1"
1226 :package-version '(Org . "9.0")
1227 :type '(choice
1228 (const :tag "Canonical" t)
1229 (const :tag "Minimal" nil)
1230 (repeat :greedy t :tag "Individual contexts"
1231 (cons
1232 (choice :tag "Context"
1233 (const agenda)
1234 (const org-goto)
1235 (const occur-tree)
1236 (const tags-tree)
1237 (const link-search)
1238 (const mark-goto)
1239 (const bookmark-jump)
1240 (const isearch)
1241 (const default))
1242 (choice :tag "Detail level"
1243 (const minimal)
1244 (const local)
1245 (const ancestors)
1246 (const lineage)
1247 (const tree)
1248 (const canonical))))))
1250 (defcustom org-indirect-buffer-display 'other-window
1251 "How should indirect tree buffers be displayed?
1253 This applies to indirect buffers created with the commands
1254 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1256 Valid values are:
1257 current-window Display in the current window
1258 other-window Just display in another window.
1259 dedicated-frame Create one new frame, and re-use it each time.
1260 new-frame Make a new frame each time. Note that in this case
1261 previously-made indirect buffers are kept, and you need to
1262 kill these buffers yourself."
1263 :group 'org-structure
1264 :group 'org-agenda-windows
1265 :type '(choice
1266 (const :tag "In current window" current-window)
1267 (const :tag "In current frame, other window" other-window)
1268 (const :tag "Each time a new frame" new-frame)
1269 (const :tag "One dedicated frame" dedicated-frame)))
1271 (defcustom org-use-speed-commands nil
1272 "Non-nil means activate single letter commands at beginning of a headline.
1273 This may also be a function to test for appropriate locations where speed
1274 commands should be active.
1276 For example, to activate speed commands when the point is on any
1277 star at the beginning of the headline, you can do this:
1279 (setq org-use-speed-commands
1280 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1281 :group 'org-structure
1282 :type '(choice
1283 (const :tag "Never" nil)
1284 (const :tag "At beginning of headline stars" t)
1285 (function)))
1287 (defcustom org-speed-commands-user nil
1288 "Alist of additional speed commands.
1289 This list will be checked before `org-speed-commands-default'
1290 when the variable `org-use-speed-commands' is non-nil
1291 and when the cursor is at the beginning of a headline.
1292 The car of each entry is a string with a single letter, which must
1293 be assigned to `self-insert-command' in the global map.
1294 The cdr is either a command to be called interactively, a function
1295 to be called, or a form to be evaluated.
1296 An entry that is just a list with a single string will be interpreted
1297 as a descriptive headline that will be added when listing the speed
1298 commands in the Help buffer using the `?' speed command."
1299 :group 'org-structure
1300 :type '(repeat :value ("k" . ignore)
1301 (choice :value ("k" . ignore)
1302 (list :tag "Descriptive Headline" (string :tag "Headline"))
1303 (cons :tag "Letter and Command"
1304 (string :tag "Command letter")
1305 (choice
1306 (function)
1307 (sexp))))))
1309 (defcustom org-bookmark-names-plist
1310 '(:last-capture "org-capture-last-stored"
1311 :last-refile "org-refile-last-stored"
1312 :last-capture-marker "org-capture-last-stored-marker")
1313 "Names for bookmarks automatically set by some Org commands.
1314 This can provide strings as names for a number of bookmarks Org sets
1315 automatically. The following keys are currently implemented:
1316 :last-capture
1317 :last-capture-marker
1318 :last-refile
1319 When a key does not show up in the property list, the corresponding bookmark
1320 is not set."
1321 :group 'org-structure
1322 :type 'plist)
1324 (defgroup org-cycle nil
1325 "Options concerning visibility cycling in Org mode."
1326 :tag "Org Cycle"
1327 :group 'org-structure)
1329 (defcustom org-cycle-skip-children-state-if-no-children t
1330 "Non-nil means skip CHILDREN state in entries that don't have any."
1331 :group 'org-cycle
1332 :type 'boolean)
1334 (defcustom org-cycle-max-level nil
1335 "Maximum level which should still be subject to visibility cycling.
1336 Levels higher than this will, for cycling, be treated as text, not a headline.
1337 When `org-odd-levels-only' is set, a value of N in this variable actually
1338 means 2N-1 stars as the limiting headline.
1339 When nil, cycle all levels.
1340 Note that the limiting level of cycling is also influenced by
1341 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1342 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1343 than its value."
1344 :group 'org-cycle
1345 :type '(choice
1346 (const :tag "No limit" nil)
1347 (integer :tag "Maximum level")))
1349 (defcustom org-hide-block-startup nil
1350 "Non-nil means entering Org mode will fold all blocks.
1351 This can also be set in on a per-file basis with
1353 #+STARTUP: hideblocks
1354 #+STARTUP: showblocks"
1355 :group 'org-startup
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-global-at-bob nil
1360 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1362 This makes it possible to do global cycling without having to use `S-TAB'
1363 or `\\[universal-argument] TAB'. For this special case to work, the first \
1364 line of the buffer
1365 must not be a headline -- it may be empty or some other text.
1367 When used in this way, `org-cycle-hook' is disabled temporarily to make
1368 sure the cursor stays at the beginning of the buffer.
1370 When this option is nil, don't do anything special at the beginning of
1371 the buffer."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-level-after-item/entry-creation t
1376 "Non-nil means cycle entry level or item indentation in new empty entries.
1378 When the cursor is at the end of an empty headline, i.e., with only stars
1379 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1380 and then all possible ancestor states, before returning to the original state.
1381 This makes data entry extremely fast: M-RET to create a new headline,
1382 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1384 When the cursor is at the end of an empty plain list item, one TAB will
1385 make it a subitem, two or more tabs will back up to make this an item
1386 higher up in the item hierarchy."
1387 :group 'org-cycle
1388 :type 'boolean)
1390 (defcustom org-cycle-emulate-tab t
1391 "Where should `org-cycle' emulate TAB.
1392 nil Never
1393 white Only in completely white lines
1394 whitestart Only at the beginning of lines, before the first non-white char
1395 t Everywhere except in headlines
1396 exc-hl-bol Everywhere except at the start of a headline
1397 If TAB is used in a place where it does not emulate TAB, the current subtree
1398 visibility is cycled."
1399 :group 'org-cycle
1400 :type '(choice (const :tag "Never" nil)
1401 (const :tag "Only in completely white lines" white)
1402 (const :tag "Before first char in a line" whitestart)
1403 (const :tag "Everywhere except in headlines" t)
1404 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1406 (defcustom org-cycle-separator-lines 2
1407 "Number of empty lines needed to keep an empty line between collapsed trees.
1408 If you leave an empty line between the end of a subtree and the following
1409 headline, this empty line is hidden when the subtree is folded.
1410 Org mode will leave (exactly) one empty line visible if the number of
1411 empty lines is equal or larger to the number given in this variable.
1412 So the default 2 means at least 2 empty lines after the end of a subtree
1413 are needed to produce free space between a collapsed subtree and the
1414 following headline.
1416 If the number is negative, and the number of empty lines is at least -N,
1417 all empty lines are shown.
1419 Special case: when 0, never leave empty lines in collapsed view."
1420 :group 'org-cycle
1421 :type 'integer)
1422 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1424 (defcustom org-pre-cycle-hook nil
1425 "Hook that is run before visibility cycling is happening.
1426 The function(s) in this hook must accept a single argument which indicates
1427 the new state that will be set right after running this hook. The
1428 argument is a symbol. Before a global state change, it can have the values
1429 `overview', `content', or `all'. Before a local state change, it can have
1430 the values `folded', `children', or `subtree'."
1431 :group 'org-cycle
1432 :type 'hook)
1434 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1435 org-cycle-show-empty-lines
1436 org-optimize-window-after-visibility-change)
1437 "Hook that is run after `org-cycle' has changed the buffer visibility.
1438 The function(s) in this hook must accept a single argument which indicates
1439 the new state that was set by the most recent `org-cycle' command. The
1440 argument is a symbol. After a global state change, it can have the values
1441 `overview', `contents', or `all'. After a local state change, it can have
1442 the values `folded', `children', or `subtree'."
1443 :group 'org-cycle
1444 :type 'hook
1445 :version "26.1"
1446 :package-version '(Org . "8.3"))
1448 (defgroup org-edit-structure nil
1449 "Options concerning structure editing in Org mode."
1450 :tag "Org Edit Structure"
1451 :group 'org-structure)
1453 (defcustom org-odd-levels-only nil
1454 "Non-nil means skip even levels and only use odd levels for the outline.
1455 This has the effect that two stars are being added/taken away in
1456 promotion/demotion commands. It also influences how levels are
1457 handled by the exporters.
1458 Changing it requires restart of `font-lock-mode' to become effective
1459 for fontification also in regions already fontified.
1460 You may also set this on a per-file basis by adding one of the following
1461 lines to the buffer:
1463 #+STARTUP: odd
1464 #+STARTUP: oddeven"
1465 :group 'org-edit-structure
1466 :group 'org-appearance
1467 :type 'boolean)
1469 (defcustom org-adapt-indentation t
1470 "Non-nil means adapt indentation to outline node level.
1472 When this variable is set, Org assumes that you write outlines by
1473 indenting text in each node to align with the headline (after the
1474 stars). The following issues are influenced by this variable:
1476 - The indentation is increased by one space in a demotion
1477 command, and decreased by one in a promotion command. However,
1478 in the latter case, if shifting some line in the entry body
1479 would alter document structure (e.g., insert a new headline),
1480 indentation is not changed at all.
1482 - Property drawers and planning information is inserted indented
1483 when this variable is set. When nil, they will not be indented.
1485 - TAB indents a line relative to current level. The lines below
1486 a headline will be indented when this variable is set.
1488 Note that this is all about true indentation, by adding and
1489 removing space characters. See also \"org-indent.el\" which does
1490 level-dependent indentation in a virtual way, i.e. at display
1491 time in Emacs."
1492 :group 'org-edit-structure
1493 :type 'boolean
1494 :safe #'booleanp)
1496 (defcustom org-special-ctrl-a/e nil
1497 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1499 When t, `C-a' will bring back the cursor to the beginning of the
1500 headline text, i.e. after the stars and after a possible TODO
1501 keyword. In an item, this will be the position after bullet and
1502 check-box, if any. When the cursor is already at that position,
1503 another `C-a' will bring it to the beginning of the line.
1505 `C-e' will jump to the end of the headline, ignoring the presence
1506 of tags in the headline. A second `C-e' will then jump to the
1507 true end of the line, after any tags. This also means that, when
1508 this variable is non-nil, `C-e' also will never jump beyond the
1509 end of the heading of a folded section, i.e. not after the
1510 ellipses.
1512 When set to the symbol `reversed', the first `C-a' or `C-e' works
1513 normally, going to the true line boundary first. Only a directly
1514 following, identical keypress will bring the cursor to the
1515 special positions.
1517 This may also be a cons cell where the behavior for `C-a' and
1518 `C-e' is set separately."
1519 :group 'org-edit-structure
1520 :type '(choice
1521 (const :tag "off" nil)
1522 (const :tag "on: after stars/bullet and before tags first" t)
1523 (const :tag "reversed: true line boundary first" reversed)
1524 (cons :tag "Set C-a and C-e separately"
1525 (choice :tag "Special C-a"
1526 (const :tag "off" nil)
1527 (const :tag "on: after stars/bullet first" t)
1528 (const :tag "reversed: before stars/bullet first" reversed))
1529 (choice :tag "Special C-e"
1530 (const :tag "off" nil)
1531 (const :tag "on: before tags first" t)
1532 (const :tag "reversed: after tags first" reversed)))))
1533 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1535 (defcustom org-special-ctrl-k nil
1536 "Non-nil means `C-k' will behave specially in headlines.
1537 When nil, `C-k' will call the default `kill-line' command.
1538 When t, the following will happen while the cursor is in the headline:
1540 - When the cursor is at the beginning of a headline, kill the entire
1541 line and possible the folded subtree below the line.
1542 - When in the middle of the headline text, kill the headline up to the tags.
1543 - When after the headline text, kill the tags."
1544 :group 'org-edit-structure
1545 :type 'boolean)
1547 (defcustom org-ctrl-k-protect-subtree nil
1548 "Non-nil means, do not delete a hidden subtree with C-k.
1549 When set to the symbol `error', simply throw an error when C-k is
1550 used to kill (part-of) a headline that has hidden text behind it.
1551 Any other non-nil value will result in a query to the user, if it is
1552 OK to kill that hidden subtree. When nil, kill without remorse."
1553 :group 'org-edit-structure
1554 :version "24.1"
1555 :type '(choice
1556 (const :tag "Do not protect hidden subtrees" nil)
1557 (const :tag "Protect hidden subtrees with a security query" t)
1558 (const :tag "Never kill a hidden subtree with C-k" error)))
1560 (defcustom org-special-ctrl-o t
1561 "Non-nil means, make `C-o' insert a row in tables."
1562 :group 'org-edit-structure
1563 :type 'boolean)
1565 (defcustom org-catch-invisible-edits nil
1566 "Check if in invisible region before inserting or deleting a character.
1567 Valid values are:
1569 nil Do not check, so just do invisible edits.
1570 error Throw an error and do nothing.
1571 show Make point visible, and do the requested edit.
1572 show-and-error Make point visible, then throw an error and abort the edit.
1573 smart Make point visible, and do insertion/deletion if it is
1574 adjacent to visible text and the change feels predictable.
1575 Never delete a previously invisible character or add in the
1576 middle or right after an invisible region. Basically, this
1577 allows insertion and backward-delete right before ellipses.
1578 FIXME: maybe in this case we should not even show?"
1579 :group 'org-edit-structure
1580 :version "24.1"
1581 :type '(choice
1582 (const :tag "Do not check" nil)
1583 (const :tag "Throw error when trying to edit" error)
1584 (const :tag "Unhide, but do not do the edit" show-and-error)
1585 (const :tag "Show invisible part and do the edit" show)
1586 (const :tag "Be smart and do the right thing" smart)))
1588 (defcustom org-yank-folded-subtrees t
1589 "Non-nil means when yanking subtrees, fold them.
1590 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1591 it starts with a heading and all other headings in it are either children
1592 or siblings, then fold all the subtrees. However, do this only if no
1593 text after the yank would be swallowed into a folded tree by this action."
1594 :group 'org-edit-structure
1595 :type 'boolean)
1597 (defcustom org-yank-adjusted-subtrees nil
1598 "Non-nil means when yanking subtrees, adjust the level.
1599 With this setting, `org-paste-subtree' is used to insert the subtree, see
1600 this function for details."
1601 :group 'org-edit-structure
1602 :type 'boolean)
1604 (defcustom org-M-RET-may-split-line '((default . t))
1605 "Non-nil means M-RET will split the line at the cursor position.
1606 When nil, it will go to the end of the line before making a
1607 new line.
1608 You may also set this option in a different way for different
1609 contexts. Valid contexts are:
1611 headline when creating a new headline
1612 item when creating a new item
1613 table in a table field
1614 default the value to be used for all contexts not explicitly
1615 customized"
1616 :group 'org-structure
1617 :group 'org-table
1618 :type '(choice
1619 (const :tag "Always" t)
1620 (const :tag "Never" nil)
1621 (repeat :greedy t :tag "Individual contexts"
1622 (cons
1623 (choice :tag "Context"
1624 (const headline)
1625 (const item)
1626 (const table)
1627 (const default))
1628 (boolean)))))
1631 (defcustom org-insert-heading-respect-content nil
1632 "Non-nil means insert new headings after the current subtree.
1633 \\<org-mode-map>
1634 When nil, the new heading is created directly after the current line.
1635 The commands `\\[org-insert-heading-respect-content]' and \
1636 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1637 for the duration of the command."
1638 :group 'org-structure
1639 :type 'boolean)
1641 (defcustom org-blank-before-new-entry '((heading . auto)
1642 (plain-list-item . auto))
1643 "Should `org-insert-heading' leave a blank line before new heading/item?
1644 The value is an alist, with `heading' and `plain-list-item' as CAR,
1645 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1646 which case Org will look at the surrounding headings/items and try to
1647 make an intelligent decision whether to insert a blank line or not."
1648 :group 'org-edit-structure
1649 :type '(list
1650 (cons (const heading)
1651 (choice (const :tag "Never" nil)
1652 (const :tag "Always" t)
1653 (const :tag "Auto" auto)))
1654 (cons (const plain-list-item)
1655 (choice (const :tag "Never" nil)
1656 (const :tag "Always" t)
1657 (const :tag "Auto" auto)))))
1659 (defcustom org-insert-heading-hook nil
1660 "Hook being run after inserting a new heading."
1661 :group 'org-edit-structure
1662 :type 'hook)
1664 (defcustom org-enable-fixed-width-editor t
1665 "Non-nil means lines starting with \":\" are treated as fixed-width.
1666 This currently only means they are never auto-wrapped.
1667 When nil, such lines will be treated like ordinary lines."
1668 :group 'org-edit-structure
1669 :type 'boolean)
1671 (defgroup org-sparse-trees nil
1672 "Options concerning sparse trees in Org mode."
1673 :tag "Org Sparse Trees"
1674 :group 'org-structure)
1676 (defcustom org-highlight-sparse-tree-matches t
1677 "Non-nil means highlight all matches that define a sparse tree.
1678 The highlights will automatically disappear the next time the buffer is
1679 changed by an edit command."
1680 :group 'org-sparse-trees
1681 :type 'boolean)
1683 (defcustom org-remove-highlights-with-change t
1684 "Non-nil means any change to the buffer will remove temporary highlights.
1685 \\<org-mode-map>\
1686 Such highlights are created by `org-occur' and `org-clock-display'.
1687 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1688 to get rid of the highlights.
1689 The highlights created by `org-toggle-latex-fragment' always need
1690 `\\[org-toggle-latex-fragment]' to be removed."
1691 :group 'org-sparse-trees
1692 :group 'org-time
1693 :type 'boolean)
1695 (defcustom org-occur-case-fold-search t
1696 "Non-nil means `org-occur' should be case-insensitive.
1697 If set to `smart' the search will be case-insensitive only if it
1698 doesn't specify any upper case character."
1699 :group 'org-sparse-trees
1700 :version "26.1"
1701 :type '(choice
1702 (const :tag "Case-sensitive" nil)
1703 (const :tag "Case-insensitive" t)
1704 (const :tag "Case-insensitive for lower case searches only" smart)))
1706 (defcustom org-occur-hook '(org-first-headline-recenter)
1707 "Hook that is run after `org-occur' has constructed a sparse tree.
1708 This can be used to recenter the window to show as much of the structure
1709 as possible."
1710 :group 'org-sparse-trees
1711 :type 'hook)
1713 (defgroup org-table nil
1714 "Options concerning tables in Org mode."
1715 :tag "Org Table"
1716 :group 'org)
1718 (defcustom org-self-insert-cluster-for-undo nil
1719 "Non-nil means cluster self-insert commands for undo when possible.
1720 If this is set, then, like in the Emacs command loop, 20 consecutive
1721 characters will be undone together.
1722 This is configurable, because there is some impact on typing performance."
1723 :group 'org-table
1724 :type 'boolean)
1726 (defcustom org-table-tab-recognizes-table.el t
1727 "Non-nil means TAB will automatically notice a table.el table.
1728 When it sees such a table, it moves point into it and - if necessary -
1729 calls `table-recognize-table'."
1730 :group 'org-table-editing
1731 :type 'boolean)
1733 (defgroup org-link nil
1734 "Options concerning links in Org mode."
1735 :tag "Org Link"
1736 :group 'org)
1738 (defvar-local org-link-abbrev-alist-local nil
1739 "Buffer-local version of `org-link-abbrev-alist', which see.
1740 The value of this is taken from the #+LINK lines.")
1742 (defcustom org-link-parameters
1743 '(("doi" :follow org--open-doi-link)
1744 ("elisp" :follow org--open-elisp-link)
1745 ("file" :complete org-file-complete-link)
1746 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1747 ("help" :follow org--open-help-link)
1748 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1749 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1750 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1751 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1752 ("shell" :follow org--open-shell-link))
1753 "An alist of properties that defines all the links in Org mode.
1754 The key in each association is a string of the link type.
1755 Subsequent optional elements make up a p-list of link properties.
1757 :follow - A function that takes the link path as an argument.
1759 :export - A function that takes the link path, description and
1760 export-backend as arguments.
1762 :store - A function responsible for storing the link. See the
1763 function `org-store-link-functions'.
1765 :complete - A function that inserts a link with completion. The
1766 function takes one optional prefix arg.
1768 :face - A face for the link, or a function that returns a face.
1769 The function takes one argument which is the link path. The
1770 default face is `org-link'.
1772 :mouse-face - The mouse-face. The default is `highlight'.
1774 :display - `full' will not fold the link in descriptive
1775 display. Default is `org-link'.
1777 :help-echo - A string or function that takes (window object position)
1778 as arguments and returns a string.
1780 :keymap - A keymap that is active on the link. The default is
1781 `org-mouse-map'.
1783 :htmlize-link - A function for the htmlize-link. Defaults
1784 to (list :uri \"type:path\")
1786 :activate-func - A function to run at the end of font-lock
1787 activation. The function must accept (link-start link-end path bracketp)
1788 as arguments."
1789 :group 'org-link
1790 :type '(alist :tag "Link display parameters"
1791 :value-type plist)
1792 :version "26.1"
1793 :package-version '(Org . "9.1"))
1795 (defun org-link-get-parameter (type key)
1796 "Get TYPE link property for KEY.
1797 TYPE is a string and KEY is a plist keyword."
1798 (plist-get
1799 (cdr (assoc type org-link-parameters))
1800 key))
1802 (defun org-link-set-parameters (type &rest parameters)
1803 "Set link TYPE properties to PARAMETERS.
1804 PARAMETERS should be :key val pairs."
1805 (let ((data (assoc type org-link-parameters)))
1806 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1807 (push (cons type parameters) org-link-parameters)
1808 (org-make-link-regexps)
1809 (org-element-update-syntax))))
1811 (defun org-link-types ()
1812 "Return a list of known link types."
1813 (mapcar #'car org-link-parameters))
1815 (defcustom org-link-abbrev-alist nil
1816 "Alist of link abbreviations.
1817 The car of each element is a string, to be replaced at the start of a link.
1818 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1819 links in Org buffers can have an optional tag after a double colon, e.g.,
1821 [[linkkey:tag][description]]
1823 The `linkkey' must be a single word, starting with a letter, followed
1824 by letters, numbers, `-' or `_'.
1826 If REPLACE is a string, the tag will simply be appended to create the link.
1827 If the string contains \"%s\", the tag will be inserted there. If the string
1828 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1829 at that point (see the function `url-hexify-string'). If the string contains
1830 the specifier \"%(my-function)\", then the custom function `my-function' will
1831 be invoked: this function takes the tag as its only argument and must return
1832 a string.
1834 REPLACE may also be a function that will be called with the tag as the
1835 only argument to create the link, which should be returned as a string.
1837 See the manual for examples."
1838 :group 'org-link
1839 :type '(repeat
1840 (cons
1841 (string :tag "Protocol")
1842 (choice
1843 (string :tag "Format")
1844 (function)))))
1846 (defcustom org-descriptive-links t
1847 "Non-nil means Org will display descriptive links.
1848 E.g. [[https://orgmode.org][Org website]] will be displayed as
1849 \"Org Website\", hiding the link itself and just displaying its
1850 description. When set to nil, Org will display the full links
1851 literally.
1853 You can interactively set the value of this variable by calling
1854 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1855 :group 'org-link
1856 :type 'boolean)
1858 (defcustom org-link-file-path-type 'adaptive
1859 "How the path name in file links should be stored.
1860 Valid values are:
1862 relative Relative to the current directory, i.e. the directory of the file
1863 into which the link is being inserted.
1864 absolute Absolute path, if possible with ~ for home directory.
1865 noabbrev Absolute path, no abbreviation of home directory.
1866 adaptive Use relative path for files in the current directory and sub-
1867 directories of it. For other files, use an absolute path."
1868 :group 'org-link
1869 :type '(choice
1870 (const relative)
1871 (const absolute)
1872 (const noabbrev)
1873 (const adaptive)))
1875 (defvaralias 'org-activate-links 'org-highlight-links)
1876 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1877 "Types of links that should be highlighted in Org files.
1879 This is a list of symbols, each one of them leading to the
1880 highlighting of a certain link type.
1882 You can still open links that are not highlighted.
1884 In principle, it does not hurt to turn on highlighting for all
1885 link types. There may be a small gain when turning off unused
1886 link types. The types are:
1888 bracket The recommended [[link][description]] or [[link]] links with hiding.
1889 angle Links in angular brackets that may contain whitespace like
1890 <bbdb:Carsten Dominik>.
1891 plain Plain links in normal text, no whitespace, like http://google.com.
1892 radio Text that is matched by a radio target, see manual for details.
1893 tag Tag settings in a headline (link to tag search).
1894 date Time stamps (link to calendar).
1895 footnote Footnote labels.
1897 If you set this variable during an Emacs session, use `org-mode-restart'
1898 in the Org buffer so that the change takes effect."
1899 :group 'org-link
1900 :group 'org-appearance
1901 :type '(set :greedy t
1902 (const :tag "Double bracket links" bracket)
1903 (const :tag "Angular bracket links" angle)
1904 (const :tag "Plain text links" plain)
1905 (const :tag "Radio target matches" radio)
1906 (const :tag "Tags" tag)
1907 (const :tag "Timestamps" date)
1908 (const :tag "Footnotes" footnote)))
1910 (defcustom org-make-link-description-function nil
1911 "Function to use for generating link descriptions from links.
1912 This function must take two parameters: the first one is the
1913 link, the second one is the description generated by
1914 `org-insert-link'. The function should return the description to
1915 use."
1916 :group 'org-link
1917 :type '(choice (const nil) (function)))
1919 (defgroup org-link-store nil
1920 "Options concerning storing links in Org mode."
1921 :tag "Org Store Link"
1922 :group 'org-link)
1924 (defcustom org-url-hexify-p t
1925 "When non-nil, hexify URL when creating a link."
1926 :type 'boolean
1927 :version "24.3"
1928 :group 'org-link-store)
1930 (defcustom org-email-link-description-format "Email %c: %.30s"
1931 "Format of the description part of a link to an email or usenet message.
1932 The following %-escapes will be replaced by corresponding information:
1934 %F full \"From\" field
1935 %f name, taken from \"From\" field, address if no name
1936 %T full \"To\" field
1937 %t first name in \"To\" field, address if no name
1938 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1939 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1940 %s subject
1941 %d date
1942 %m message-id.
1944 You may use normal field width specification between the % and the letter.
1945 This is for example useful to limit the length of the subject.
1947 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1948 :group 'org-link-store
1949 :type 'string)
1951 (defcustom org-from-is-user-regexp
1952 (let (r1 r2)
1953 (when (and user-mail-address (not (string= user-mail-address "")))
1954 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1955 (when (and user-full-name (not (string= user-full-name "")))
1956 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1957 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1958 "Regexp matched against the \"From:\" header of an email or usenet message.
1959 It should match if the message is from the user him/herself."
1960 :group 'org-link-store
1961 :type 'regexp)
1963 (defcustom org-context-in-file-links t
1964 "Non-nil means file links from `org-store-link' contain context.
1965 \\<org-mode-map>
1966 A search string will be added to the file name with :: as separator
1967 and used to find the context when the link is activated by the command
1968 `org-open-at-point'. When this option is t, the entire active region
1969 will be placed in the search string of the file link. If set to a
1970 positive integer, only the first n lines of context will be stored.
1972 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1973 \\[org-store-link]')
1974 negates this setting for the duration of the command."
1975 :group 'org-link-store
1976 :type '(choice boolean integer))
1978 (defcustom org-keep-stored-link-after-insertion nil
1979 "Non-nil means keep link in list for entire session.
1980 \\<org-mode-map>
1981 The command `org-store-link' adds a link pointing to the current
1982 location to an internal list. These links accumulate during a session.
1983 The command `org-insert-link' can be used to insert links into any
1984 Org file (offering completion for all stored links).
1986 When this option is nil, every link which has been inserted once using
1987 `\\[org-insert-link]' will be removed from the list, to make completing the \
1988 unused
1989 links more efficient."
1990 :group 'org-link-store
1991 :type 'boolean)
1993 (defgroup org-link-follow nil
1994 "Options concerning following links in Org mode."
1995 :tag "Org Follow Link"
1996 :group 'org-link)
1998 (defcustom org-link-translation-function nil
1999 "Function to translate links with different syntax to Org syntax.
2000 This can be used to translate links created for example by the Planner
2001 or emacs-wiki packages to Org syntax.
2002 The function must accept two parameters, a TYPE containing the link
2003 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2004 which is everything after the link protocol. It should return a cons
2005 with possibly modified values of type and path.
2006 Org contains a function for this, so if you set this variable to
2007 `org-translate-link-from-planner', you should be able follow many
2008 links created by planner."
2009 :group 'org-link-follow
2010 :type '(choice (const nil) (function)))
2012 (defcustom org-follow-link-hook nil
2013 "Hook that is run after a link has been followed."
2014 :group 'org-link-follow
2015 :type 'hook)
2017 (defcustom org-tab-follows-link nil
2018 "Non-nil means on links TAB will follow the link.
2019 Needs to be set before org.el is loaded.
2020 This really should not be used, it does not make sense, and the
2021 implementation is bad."
2022 :group 'org-link-follow
2023 :type 'boolean)
2025 (defcustom org-return-follows-link nil
2026 "Non-nil means on links RET will follow the link.
2027 In tables, the special behavior of RET has precedence."
2028 :group 'org-link-follow
2029 :type 'boolean)
2031 (defcustom org-mouse-1-follows-link
2032 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2033 "Non-nil means mouse-1 on a link will follow the link.
2034 A longer mouse click will still set point. Needs to be set
2035 before org.el is loaded."
2036 :group 'org-link-follow
2037 :version "26.1"
2038 :package-version '(Org . "8.3")
2039 :type '(choice
2040 (const :tag "A double click follows the link" double)
2041 (const :tag "Unconditionally follow the link with mouse-1" t)
2042 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2044 (defcustom org-mark-ring-length 4
2045 "Number of different positions to be recorded in the ring.
2046 Changing this requires a restart of Emacs to work correctly."
2047 :group 'org-link-follow
2048 :type 'integer)
2050 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2051 "Non-nil means internal fuzzy links can only match headlines.
2053 When nil, the a fuzzy link may point to a target or a named
2054 construct in the document. When set to the special value
2055 `query-to-create', offer to create a new headline when none
2056 matched.
2058 Spaces and statistics cookies are ignored during heading searches."
2059 :group 'org-link-follow
2060 :version "24.1"
2061 :type '(choice
2062 (const :tag "Use fuzzy text search" nil)
2063 (const :tag "Match only exact headline" t)
2064 (const :tag "Match exact headline or query to create it"
2065 query-to-create))
2066 :safe #'symbolp)
2068 (defcustom org-link-frame-setup
2069 '((vm . vm-visit-folder-other-frame)
2070 (vm-imap . vm-visit-imap-folder-other-frame)
2071 (gnus . org-gnus-no-new-news)
2072 (file . find-file-other-window)
2073 (wl . wl-other-frame))
2074 "Setup the frame configuration for following links.
2075 When following a link with Emacs, it may often be useful to display
2076 this link in another window or frame. This variable can be used to
2077 set this up for the different types of links.
2078 For VM, use any of
2079 `vm-visit-folder'
2080 `vm-visit-folder-other-window'
2081 `vm-visit-folder-other-frame'
2082 For Gnus, use any of
2083 `gnus'
2084 `gnus-other-frame'
2085 `org-gnus-no-new-news'
2086 For FILE, use any of
2087 `find-file'
2088 `find-file-other-window'
2089 `find-file-other-frame'
2090 For Wanderlust use any of
2091 `wl'
2092 `wl-other-frame'
2093 For the calendar, use the variable `calendar-setup'.
2094 For BBDB, it is currently only possible to display the matches in
2095 another window."
2096 :group 'org-link-follow
2097 :type '(list
2098 (cons (const vm)
2099 (choice
2100 (const vm-visit-folder)
2101 (const vm-visit-folder-other-window)
2102 (const vm-visit-folder-other-frame)))
2103 (cons (const vm-imap)
2104 (choice
2105 (const vm-visit-imap-folder)
2106 (const vm-visit-imap-folder-other-window)
2107 (const vm-visit-imap-folder-other-frame)))
2108 (cons (const gnus)
2109 (choice
2110 (const gnus)
2111 (const gnus-other-frame)
2112 (const org-gnus-no-new-news)))
2113 (cons (const file)
2114 (choice
2115 (const find-file)
2116 (const find-file-other-window)
2117 (const find-file-other-frame)))
2118 (cons (const wl)
2119 (choice
2120 (const wl)
2121 (const wl-other-frame)))))
2123 (defcustom org-display-internal-link-with-indirect-buffer nil
2124 "Non-nil means use indirect buffer to display infile links.
2125 Activating internal links (from one location in a file to another location
2126 in the same file) normally just jumps to the location. When the link is
2127 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2128 is displayed in
2129 another window. When this option is set, the other window actually displays
2130 an indirect buffer clone of the current buffer, to avoid any visibility
2131 changes to the current buffer."
2132 :group 'org-link-follow
2133 :type 'boolean)
2135 (defcustom org-open-non-existing-files nil
2136 "Non-nil means `org-open-file' will open non-existing files.
2137 When nil, an error will be generated.
2138 This variable applies only to external applications because they
2139 might choke on non-existing files. If the link is to a file that
2140 will be opened in Emacs, the variable is ignored."
2141 :group 'org-link-follow
2142 :type 'boolean)
2144 (defcustom org-open-directory-means-index-dot-org nil
2145 "Non-nil means a link to a directory really means to index.org.
2146 When nil, following a directory link will run dired or open a finder/explorer
2147 window on that directory."
2148 :group 'org-link-follow
2149 :type 'boolean)
2151 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2152 "Non-nil means ask for confirmation before executing shell links.
2153 Shell links can be dangerous: just think about a link
2155 [[shell:rm -rf ~/*][Google Search]]
2157 This link would show up in your Org document as \"Google Search\",
2158 but really it would remove your entire home directory.
2159 Therefore we advise against setting this variable to nil.
2160 Just change it to `y-or-n-p' if you want to confirm with a
2161 single keystroke rather than having to type \"yes\"."
2162 :group 'org-link-follow
2163 :type '(choice
2164 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2165 (const :tag "with y-or-n (faster)" y-or-n-p)
2166 (const :tag "no confirmation (dangerous)" nil)))
2167 (put 'org-confirm-shell-link-function
2168 'safe-local-variable
2169 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2171 (defcustom org-confirm-shell-link-not-regexp ""
2172 "A regexp to skip confirmation for shell links."
2173 :group 'org-link-follow
2174 :version "24.1"
2175 :type 'regexp)
2177 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2178 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2179 Elisp links can be dangerous: just think about a link
2181 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2183 This link would show up in your Org document as \"Google Search\",
2184 but really it would remove your entire home directory.
2185 Therefore we advise against setting this variable to nil.
2186 Just change it to `y-or-n-p' if you want to confirm with a
2187 single keystroke rather than having to type \"yes\"."
2188 :group 'org-link-follow
2189 :type '(choice
2190 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2191 (const :tag "with y-or-n (faster)" y-or-n-p)
2192 (const :tag "no confirmation (dangerous)" nil)))
2193 (put 'org-confirm-shell-link-function
2194 'safe-local-variable
2195 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2197 (defcustom org-confirm-elisp-link-not-regexp ""
2198 "A regexp to skip confirmation for Elisp links."
2199 :group 'org-link-follow
2200 :version "24.1"
2201 :type 'regexp)
2203 (defconst org-file-apps-defaults-gnu
2204 '((remote . emacs)
2205 (system . mailcap)
2206 (t . mailcap))
2207 "Default file applications on a UNIX or GNU/Linux system.
2208 See `org-file-apps'.")
2210 (defconst org-file-apps-defaults-macosx
2211 '((remote . emacs)
2212 (system . "open %s")
2213 ("ps.gz" . "gv %s")
2214 ("eps.gz" . "gv %s")
2215 ("dvi" . "xdvi %s")
2216 ("fig" . "xfig %s")
2217 (t . "open %s"))
2218 "Default file applications on a macOS system.
2219 The system \"open\" is known as a default, but we use X11 applications
2220 for some files for which the OS does not have a good default.
2221 See `org-file-apps'.")
2223 (defconst org-file-apps-defaults-windowsnt
2224 (list '(remote . emacs)
2225 (cons 'system (lambda (file _path)
2226 (with-no-warnings (w32-shell-execute "open" file))))
2227 (cons t (lambda (file _path)
2228 (with-no-warnings (w32-shell-execute "open" file)))))
2229 "Default file applications on a Windows NT system.
2230 The system \"open\" is used for most files.
2231 See `org-file-apps'.")
2233 (defcustom org-file-apps
2234 '((auto-mode . emacs)
2235 ("\\.mm\\'" . default)
2236 ("\\.x?html?\\'" . default)
2237 ("\\.pdf\\'" . default))
2238 "External applications for opening `file:path' items in a document.
2239 \\<org-mode-map>\
2241 Org mode uses system defaults for different file types, but
2242 you can use this variable to set the application for a given file
2243 extension. The entries in this list are cons cells where the car identifies
2244 files and the cdr the corresponding command.
2246 Possible values for the file identifier are:
2248 \"string\" A string as a file identifier can be interpreted in different
2249 ways, depending on its contents:
2251 - Alphanumeric characters only:
2252 Match links with this file extension.
2253 Example: (\"pdf\" . \"evince %s\")
2254 to open PDFs with evince.
2256 - Regular expression: Match links where the
2257 filename matches the regexp. If you want to
2258 use groups here, use shy groups.
2260 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2261 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2262 to open *.html and *.xhtml with firefox.
2264 - Regular expression which contains (non-shy) groups:
2265 Match links where the whole link, including \"::\", and
2266 anything after that, matches the regexp.
2267 In a custom command string, %1, %2, etc. are replaced with
2268 the parts of the link that were matched by the groups.
2269 For backwards compatibility, if a command string is given
2270 that does not use any of the group matches, this case is
2271 handled identically to the second one (i.e. match against
2272 file name only).
2273 In a custom function, you can access the group matches with
2274 (match-string n link).
2276 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2277 \"evince -p %1 %s\")
2278 to open [[file:document.pdf::5]] with evince at page 5.
2280 `directory' Matches a directory
2281 `remote' Matches a remote file, accessible through tramp or efs.
2282 Remote files most likely should be visited through Emacs
2283 because external applications cannot handle such paths.
2284 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2285 so all files Emacs knows how to handle. Using this with
2286 command `emacs' will open most files in Emacs. Beware that this
2287 will also open html files inside Emacs, unless you add
2288 (\"html\" . default) to the list as well.
2289 `system' The system command to open files, like `open' on Windows
2290 and macOS, and mailcap under GNU/Linux. This is the command
2291 that will be selected if you call `org-open-at-point' with a
2292 double prefix argument (`\\[universal-argument] \
2293 \\[universal-argument] \\[org-open-at-point]').
2294 t Default for files not matched by any of the other options.
2296 Possible values for the command are:
2298 `emacs' The file will be visited by the current Emacs process.
2299 `default' Use the default application for this file type, which is the
2300 association for t in the list, most likely in the system-specific
2301 part. This can be used to overrule an unwanted setting in the
2302 system-specific variable.
2303 `system' Use the system command for opening files, like \"open\".
2304 This command is specified by the entry whose car is `system'.
2305 Most likely, the system-specific version of this variable
2306 does define this command, but you can overrule/replace it
2307 here.
2308 `mailcap' Use command specified in the mailcaps.
2309 string A command to be executed by a shell; %s will be replaced
2310 by the path to the file.
2311 function A Lisp function, which will be called with two arguments:
2312 the file path and the original link string, without the
2313 \"file:\" prefix.
2315 For more examples, see the system specific constants
2316 `org-file-apps-defaults-macosx'
2317 `org-file-apps-defaults-windowsnt'
2318 `org-file-apps-defaults-gnu'."
2319 :group 'org-link-follow
2320 :type '(repeat
2321 (cons (choice :value ""
2322 (string :tag "Extension")
2323 (const :tag "System command to open files" system)
2324 (const :tag "Default for unrecognized files" t)
2325 (const :tag "Remote file" remote)
2326 (const :tag "Links to a directory" directory)
2327 (const :tag "Any files that have Emacs modes"
2328 auto-mode))
2329 (choice :value ""
2330 (const :tag "Visit with Emacs" emacs)
2331 (const :tag "Use default" default)
2332 (const :tag "Use the system command" system)
2333 (string :tag "Command")
2334 (function :tag "Function")))))
2336 (defcustom org-doi-server-url "http://dx.doi.org/"
2337 "The URL of the DOI server."
2338 :type 'string
2339 :version "24.3"
2340 :group 'org-link-follow)
2342 (defgroup org-refile nil
2343 "Options concerning refiling entries in Org mode."
2344 :tag "Org Refile"
2345 :group 'org)
2347 (defcustom org-directory "~/org"
2348 "Directory with Org files.
2349 This is just a default location to look for Org files. There is no need
2350 at all to put your files into this directory. It is used in the
2351 following situations:
2353 1. When a capture template specifies a target file that is not an
2354 absolute path. The path will then be interpreted relative to
2355 `org-directory'
2356 2. When the value of variable `org-agenda-files' is a single file, any
2357 relative paths in this file will be taken as relative to
2358 `org-directory'."
2359 :group 'org-refile
2360 :group 'org-capture
2361 :type 'directory)
2363 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2364 "Default target for storing notes.
2365 Used as a fall back file for org-capture.el, for templates that
2366 do not specify a target file."
2367 :group 'org-refile
2368 :group 'org-capture
2369 :type 'file)
2371 (defcustom org-reverse-note-order nil
2372 "Non-nil means store new notes at the beginning of a file or entry.
2373 When nil, new notes will be filed to the end of a file or entry.
2374 This can also be a list with cons cells of regular expressions that
2375 are matched against file names, and values."
2376 :group 'org-capture
2377 :group 'org-refile
2378 :type '(choice
2379 (const :tag "Reverse always" t)
2380 (const :tag "Reverse never" nil)
2381 (repeat :tag "By file name regexp"
2382 (cons regexp boolean))))
2384 (defcustom org-log-refile nil
2385 "Information to record when a task is refiled.
2387 Possible values are:
2389 nil Don't add anything
2390 time Add a time stamp to the task
2391 note Prompt for a note and add it with template `org-log-note-headings'
2393 This option can also be set with on a per-file-basis with
2395 #+STARTUP: nologrefile
2396 #+STARTUP: logrefile
2397 #+STARTUP: lognoterefile
2399 You can have local logging settings for a subtree by setting the LOGGING
2400 property to one or more of these keywords.
2402 When bulk-refiling from the agenda, the value `note' is forbidden and
2403 will temporarily be changed to `time'."
2404 :group 'org-refile
2405 :group 'org-progress
2406 :version "24.1"
2407 :type '(choice
2408 (const :tag "No logging" nil)
2409 (const :tag "Record timestamp" time)
2410 (const :tag "Record timestamp with note." note)))
2412 (defcustom org-refile-targets nil
2413 "Targets for refiling entries with `\\[org-refile]'.
2414 This is a list of cons cells. Each cell contains:
2415 - a specification of the files to be considered, either a list of files,
2416 or a symbol whose function or variable value will be used to retrieve
2417 a file name or a list of file names. If you use `org-agenda-files' for
2418 that, all agenda files will be scanned for targets. Nil means consider
2419 headings in the current buffer.
2420 - A specification of how to find candidate refile targets. This may be
2421 any of:
2422 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2423 This tag has to be present in all target headlines, inheritance will
2424 not be considered.
2425 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2426 todo keyword.
2427 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2428 headlines that are refiling targets.
2429 - a cons cell (:level . N). Any headline of level N is considered a target.
2430 Note that, when `org-odd-levels-only' is set, level corresponds to
2431 order in hierarchy, not to the number of stars.
2432 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2433 Note that, when `org-odd-levels-only' is set, level corresponds to
2434 order in hierarchy, not to the number of stars.
2436 Each element of this list generates a set of possible targets.
2437 The union of these sets is presented (with completion) to
2438 the user by `org-refile'.
2440 You can set the variable `org-refile-target-verify-function' to a function
2441 to verify each headline found by the simple criteria above.
2443 When this variable is nil, all top-level headlines in the current buffer
2444 are used, equivalent to the value `((nil . (:level . 1))'."
2445 :group 'org-refile
2446 :type '(repeat
2447 (cons
2448 (choice :value org-agenda-files
2449 (const :tag "All agenda files" org-agenda-files)
2450 (const :tag "Current buffer" nil)
2451 (function) (variable) (file))
2452 (choice :tag "Identify target headline by"
2453 (cons :tag "Specific tag" (const :value :tag) (string))
2454 (cons :tag "TODO keyword" (const :value :todo) (string))
2455 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2456 (cons :tag "Level number" (const :value :level) (integer))
2457 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2459 (defcustom org-refile-target-verify-function nil
2460 "Function to verify if the headline at point should be a refile target.
2461 The function will be called without arguments, with point at the
2462 beginning of the headline. It should return t and leave point
2463 where it is if the headline is a valid target for refiling.
2465 If the target should not be selected, the function must return nil.
2466 In addition to this, it may move point to a place from where the search
2467 should be continued. For example, the function may decide that the entire
2468 subtree of the current entry should be excluded and move point to the end
2469 of the subtree."
2470 :group 'org-refile
2471 :type '(choice
2472 (const nil)
2473 (function)))
2475 (defcustom org-refile-use-cache nil
2476 "Non-nil means cache refile targets to speed up the process.
2477 \\<org-mode-map>\
2478 The cache for a particular file will be updated automatically when
2479 the buffer has been killed, or when any of the marker used for flagging
2480 refile targets no longer points at a live buffer.
2481 If you have added new entries to a buffer that might themselves be targets,
2482 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2483 if you find that easier, \
2484 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2485 \\[org-refile]'."
2486 :group 'org-refile
2487 :version "24.1"
2488 :type 'boolean)
2490 (defcustom org-refile-use-outline-path nil
2491 "Non-nil means provide refile targets as paths.
2492 So a level 3 headline will be available as level1/level2/level3.
2494 When the value is `file', also include the file name (without directory)
2495 into the path. In this case, you can also stop the completion after
2496 the file name, to get entries inserted as top level in the file.
2498 When `full-file-path', include the full file path.
2500 When `buffer-name', use the buffer name."
2501 :group 'org-refile
2502 :type '(choice
2503 (const :tag "Not" nil)
2504 (const :tag "Yes" t)
2505 (const :tag "Start with file name" file)
2506 (const :tag "Start with full file path" full-file-path)
2507 (const :tag "Start with buffer name" buffer-name)))
2509 (defcustom org-outline-path-complete-in-steps t
2510 "Non-nil means complete the outline path in hierarchical steps.
2511 When Org uses the refile interface to select an outline path (see
2512 `org-refile-use-outline-path'), the completion of the path can be
2513 done in a single go, or it can be done in steps down the headline
2514 hierarchy. Going in steps is probably the best if you do not use
2515 a special completion package like `ido' or `icicles'. However,
2516 when using these packages, going in one step can be very fast,
2517 while still showing the whole path to the entry."
2518 :group 'org-refile
2519 :type 'boolean)
2521 (defcustom org-refile-allow-creating-parent-nodes nil
2522 "Non-nil means allow the creation of new nodes as refile targets.
2523 New nodes are then created by adding \"/new node name\" to the completion
2524 of an existing node. When the value of this variable is `confirm',
2525 new node creation must be confirmed by the user (recommended).
2526 When nil, the completion must match an existing entry.
2528 Note that, if the new heading is not seen by the criteria
2529 listed in `org-refile-targets', multiple instances of the same
2530 heading would be created by trying again to file under the new
2531 heading."
2532 :group 'org-refile
2533 :type '(choice
2534 (const :tag "Never" nil)
2535 (const :tag "Always" t)
2536 (const :tag "Prompt for confirmation" confirm)))
2538 (defcustom org-refile-active-region-within-subtree nil
2539 "Non-nil means also refile active region within a subtree.
2541 By default `org-refile' doesn't allow refiling regions if they
2542 don't contain a set of subtrees, but it might be convenient to
2543 do so sometimes: in that case, the first line of the region is
2544 converted to a headline before refiling."
2545 :group 'org-refile
2546 :version "24.1"
2547 :type 'boolean)
2549 (defgroup org-todo nil
2550 "Options concerning TODO items in Org mode."
2551 :tag "Org TODO"
2552 :group 'org)
2554 (defgroup org-progress nil
2555 "Options concerning Progress logging in Org mode."
2556 :tag "Org Progress"
2557 :group 'org-time)
2559 (defvar org-todo-interpretation-widgets
2560 '((:tag "Sequence (cycling hits every state)" sequence)
2561 (:tag "Type (cycling directly to DONE)" type))
2562 "The available interpretation symbols for customizing `org-todo-keywords'.
2563 Interested libraries should add to this list.")
2565 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2566 "List of TODO entry keyword sequences and their interpretation.
2567 \\<org-mode-map>This is a list of sequences.
2569 Each sequence starts with a symbol, either `sequence' or `type',
2570 indicating if the keywords should be interpreted as a sequence of
2571 action steps, or as different types of TODO items. The first
2572 keywords are states requiring action - these states will select a headline
2573 for inclusion into the global TODO list Org produces. If one of the
2574 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2575 signify that no further action is necessary. If \"|\" is not found,
2576 the last keyword is treated as the only DONE state of the sequence.
2578 The command `\\[org-todo]' cycles an entry through these states, and one
2579 additional state where no keyword is present. For details about this
2580 cycling, see the manual.
2582 TODO keywords and interpretation can also be set on a per-file basis with
2583 the special #+SEQ_TODO and #+TYP_TODO lines.
2585 Each keyword can optionally specify a character for fast state selection
2586 \(in combination with the variable `org-use-fast-todo-selection')
2587 and specifiers for state change logging, using the same syntax that
2588 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2589 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2590 indicates to record a time stamp each time this state is selected.
2592 Each keyword may also specify if a timestamp or a note should be
2593 recorded when entering or leaving the state, by adding additional
2594 characters in the parenthesis after the keyword. This looks like this:
2595 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2596 record only the time of the state change. With X and Y being either
2597 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2598 Y when leaving the state if and only if the *target* state does not
2599 define X. You may omit any of the fast-selection key or X or /Y,
2600 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2602 For backward compatibility, this variable may also be just a list
2603 of keywords. In this case the interpretation (sequence or type) will be
2604 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2605 :group 'org-todo
2606 :group 'org-keywords
2607 :type '(choice
2608 (repeat :tag "Old syntax, just keywords"
2609 (string :tag "Keyword"))
2610 (repeat :tag "New syntax"
2611 (cons
2612 (choice
2613 :tag "Interpretation"
2614 ;;Quick and dirty way to see
2615 ;;`org-todo-interpretations'. This takes the
2616 ;;place of item arguments
2617 :convert-widget
2618 (lambda (widget)
2619 (widget-put widget
2620 :args (mapcar
2621 (lambda (x)
2622 (widget-convert
2623 (cons 'const x)))
2624 org-todo-interpretation-widgets))
2625 widget))
2626 (repeat
2627 (string :tag "Keyword"))))))
2629 (defvar-local org-todo-keywords-1 nil
2630 "All TODO and DONE keywords active in a buffer.")
2631 (defvar org-todo-keywords-for-agenda nil)
2632 (defvar org-done-keywords-for-agenda nil)
2633 (defvar org-todo-keyword-alist-for-agenda nil)
2634 (defvar org-tag-alist-for-agenda nil
2635 "Alist of all tags from all agenda files.")
2636 (defvar org-tag-groups-alist-for-agenda nil
2637 "Alist of all groups tags from all current agenda files.")
2638 (defvar-local org-tag-groups-alist nil)
2639 (defvar org-agenda-contributing-files nil)
2640 (defvar-local org-current-tag-alist nil
2641 "Alist of all tag groups in current buffer.
2642 This variable takes into consideration `org-tag-alist',
2643 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2644 (defvar-local org-not-done-keywords nil)
2645 (defvar-local org-done-keywords nil)
2646 (defvar-local org-todo-heads nil)
2647 (defvar-local org-todo-sets nil)
2648 (defvar-local org-todo-log-states nil)
2649 (defvar-local org-todo-kwd-alist nil)
2650 (defvar-local org-todo-key-alist nil)
2651 (defvar-local org-todo-key-trigger nil)
2653 (defcustom org-todo-interpretation 'sequence
2654 "Controls how TODO keywords are interpreted.
2655 This variable is in principle obsolete and is only used for
2656 backward compatibility, if the interpretation of todo keywords is
2657 not given already in `org-todo-keywords'. See that variable for
2658 more information."
2659 :group 'org-todo
2660 :group 'org-keywords
2661 :type '(choice (const sequence)
2662 (const type)))
2664 (defcustom org-use-fast-todo-selection t
2665 "\\<org-mode-map>\
2666 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2667 This variable describes if and under what circumstances the cycling
2668 mechanism for TODO keywords will be replaced by a single-key, direct
2669 selection scheme.
2671 When nil, fast selection is never used.
2673 When the symbol `prefix', it will be used when `org-todo' is called
2674 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2675 in an Org buffer, and
2676 `\\[universal-argument] t' in an agenda buffer.
2678 When t, fast selection is used by default. In this case, the prefix
2679 argument forces cycling instead.
2681 In all cases, the special interface is only used if access keys have
2682 actually been assigned by the user, i.e. if keywords in the configuration
2683 are followed by a letter in parenthesis, like TODO(t)."
2684 :group 'org-todo
2685 :type '(choice
2686 (const :tag "Never" nil)
2687 (const :tag "By default" t)
2688 (const :tag "Only with C-u C-c C-t" prefix)))
2690 (defcustom org-provide-todo-statistics t
2691 "Non-nil means update todo statistics after insert and toggle.
2692 ALL-HEADLINES means update todo statistics by including headlines
2693 with no TODO keyword as well, counting them as not done.
2694 A list of TODO keywords means the same, but skip keywords that are
2695 not in this list.
2696 When set to a list of two lists, the first list contains keywords
2697 to consider as TODO keywords, the second list contains keywords
2698 to consider as DONE keywords.
2700 When this is set, todo statistics is updated in the parent of the
2701 current entry each time a todo state is changed."
2702 :group 'org-todo
2703 :type '(choice
2704 (const :tag "Yes, only for TODO entries" t)
2705 (const :tag "Yes, including all entries" all-headlines)
2706 (repeat :tag "Yes, for TODOs in this list"
2707 (string :tag "TODO keyword"))
2708 (list :tag "Yes, for TODOs and DONEs in these lists"
2709 (repeat (string :tag "TODO keyword"))
2710 (repeat (string :tag "DONE keyword")))
2711 (other :tag "No TODO statistics" nil)))
2713 (defcustom org-hierarchical-todo-statistics t
2714 "Non-nil means TODO statistics covers just direct children.
2715 When nil, all entries in the subtree are considered.
2716 This has only an effect if `org-provide-todo-statistics' is set.
2717 To set this to nil for only a single subtree, use a COOKIE_DATA
2718 property and include the word \"recursive\" into the value."
2719 :group 'org-todo
2720 :type 'boolean)
2722 (defcustom org-after-todo-state-change-hook nil
2723 "Hook which is run after the state of a TODO item was changed.
2724 The new state (a string with a TODO keyword, or nil) is available in the
2725 Lisp variable `org-state'."
2726 :group 'org-todo
2727 :type 'hook)
2729 (defvar org-blocker-hook nil
2730 "Hook for functions that are allowed to block a state change.
2732 Functions in this hook should not modify the buffer.
2733 Each function gets as its single argument a property list,
2734 see `org-trigger-hook' for more information about this list.
2736 If any of the functions in this hook returns nil, the state change
2737 is blocked.")
2739 (defvar org-trigger-hook nil
2740 "Hook for functions that are triggered by a state change.
2742 Each function gets as its single argument a property list with at
2743 least the following elements:
2745 (:type type-of-change :position pos-at-entry-start
2746 :from old-state :to new-state)
2748 Depending on the type, more properties may be present.
2750 This mechanism is currently implemented for:
2752 TODO state changes
2753 ------------------
2754 :type todo-state-change
2755 :from previous state (keyword as a string), or nil, or a symbol
2756 `todo' or `done', to indicate the general type of state.
2757 :to new state, like in :from")
2759 (defcustom org-enforce-todo-dependencies nil
2760 "Non-nil means undone TODO entries will block switching the parent to DONE.
2761 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2762 be blocked if any prior sibling is not yet done.
2763 Finally, if the parent is blocked because of ordered siblings of its own,
2764 the child will also be blocked."
2765 :set (lambda (var val)
2766 (set var val)
2767 (if val
2768 (add-hook 'org-blocker-hook
2769 'org-block-todo-from-children-or-siblings-or-parent)
2770 (remove-hook 'org-blocker-hook
2771 'org-block-todo-from-children-or-siblings-or-parent)))
2772 :group 'org-todo
2773 :type 'boolean)
2775 (defcustom org-enforce-todo-checkbox-dependencies nil
2776 "Non-nil means unchecked boxes will block switching the parent to DONE.
2777 When this is nil, checkboxes have no influence on switching TODO states.
2778 When non-nil, you first need to check off all check boxes before the TODO
2779 entry can be switched to DONE.
2780 This variable needs to be set before org.el is loaded, and you need to
2781 restart Emacs after a change to make the change effective. The only way
2782 to change is while Emacs is running is through the customize interface."
2783 :set (lambda (var val)
2784 (set var val)
2785 (if val
2786 (add-hook 'org-blocker-hook
2787 'org-block-todo-from-checkboxes)
2788 (remove-hook 'org-blocker-hook
2789 'org-block-todo-from-checkboxes)))
2790 :group 'org-todo
2791 :type 'boolean)
2793 (defcustom org-treat-insert-todo-heading-as-state-change nil
2794 "Non-nil means inserting a TODO heading is treated as state change.
2795 So when the command `\\[org-insert-todo-heading]' is used, state change
2796 logging will apply if appropriate. When nil, the new TODO item will
2797 be inserted directly, and no logging will take place."
2798 :group 'org-todo
2799 :type 'boolean)
2801 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2802 "Non-nil means switching TODO states with S-cursor counts as state change.
2803 This is the default behavior. However, setting this to nil allows a
2804 convenient way to select a TODO state and bypass any logging associated
2805 with that."
2806 :group 'org-todo
2807 :type 'boolean)
2809 (defcustom org-todo-state-tags-triggers nil
2810 "Tag changes that should be triggered by TODO state changes.
2811 This is a list. Each entry is
2813 (state-change (tag . flag) .......)
2815 State-change can be a string with a state, and empty string to indicate the
2816 state that has no TODO keyword, or it can be one of the symbols `todo'
2817 or `done', meaning any not-done or done state, respectively."
2818 :group 'org-todo
2819 :group 'org-tags
2820 :type '(repeat
2821 (cons (choice :tag "When changing to"
2822 (const :tag "Not-done state" todo)
2823 (const :tag "Done state" done)
2824 (string :tag "State"))
2825 (repeat
2826 (cons :tag "Tag action"
2827 (string :tag "Tag")
2828 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2830 (defcustom org-log-done nil
2831 "Information to record when a task moves to the DONE state.
2833 Possible values are:
2835 nil Don't add anything, just change the keyword
2836 time Add a time stamp to the task
2837 note Prompt for a note and add it with template `org-log-note-headings'
2839 This option can also be set with on a per-file-basis with
2841 #+STARTUP: nologdone
2842 #+STARTUP: logdone
2843 #+STARTUP: lognotedone
2845 You can have local logging settings for a subtree by setting the LOGGING
2846 property to one or more of these keywords."
2847 :group 'org-todo
2848 :group 'org-progress
2849 :type '(choice
2850 (const :tag "No logging" nil)
2851 (const :tag "Record CLOSED timestamp" time)
2852 (const :tag "Record CLOSED timestamp with note." note)))
2854 ;; Normalize old uses of org-log-done.
2855 (cond
2856 ((eq org-log-done t) (setq org-log-done 'time))
2857 ((and (listp org-log-done) (memq 'done org-log-done))
2858 (setq org-log-done 'note)))
2860 (defcustom org-log-reschedule nil
2861 "Information to record when the scheduling date of a tasks is modified.
2863 Possible values are:
2865 nil Don't add anything, just change the date
2866 time Add a time stamp to the task
2867 note Prompt for a note and add it with template `org-log-note-headings'
2869 This option can also be set with on a per-file-basis with
2871 #+STARTUP: nologreschedule
2872 #+STARTUP: logreschedule
2873 #+STARTUP: lognotereschedule"
2874 :group 'org-todo
2875 :group 'org-progress
2876 :type '(choice
2877 (const :tag "No logging" nil)
2878 (const :tag "Record timestamp" time)
2879 (const :tag "Record timestamp with note." note)))
2881 (defcustom org-log-redeadline nil
2882 "Information to record when the deadline date of a tasks is modified.
2884 Possible values are:
2886 nil Don't add anything, just change the date
2887 time Add a time stamp to the task
2888 note Prompt for a note and add it with template `org-log-note-headings'
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: nologredeadline
2893 #+STARTUP: logredeadline
2894 #+STARTUP: lognoteredeadline
2896 You can have local logging settings for a subtree by setting the LOGGING
2897 property to one or more of these keywords."
2898 :group 'org-todo
2899 :group 'org-progress
2900 :type '(choice
2901 (const :tag "No logging" nil)
2902 (const :tag "Record timestamp" time)
2903 (const :tag "Record timestamp with note." note)))
2905 (defcustom org-log-note-clock-out nil
2906 "Non-nil means record a note when clocking out of an item.
2907 This can also be configured on a per-file basis by adding one of
2908 the following lines anywhere in the buffer:
2910 #+STARTUP: lognoteclock-out
2911 #+STARTUP: nolognoteclock-out"
2912 :group 'org-todo
2913 :group 'org-progress
2914 :type 'boolean)
2916 (defcustom org-log-done-with-time t
2917 "Non-nil means the CLOSED time stamp will contain date and time.
2918 When nil, only the date will be recorded."
2919 :group 'org-progress
2920 :type 'boolean)
2922 (defcustom org-log-note-headings
2923 '((done . "CLOSING NOTE %t")
2924 (state . "State %-12s from %-12S %t")
2925 (note . "Note taken on %t")
2926 (reschedule . "Rescheduled from %S on %t")
2927 (delschedule . "Not scheduled, was %S on %t")
2928 (redeadline . "New deadline from %S on %t")
2929 (deldeadline . "Removed deadline, was %S on %t")
2930 (refile . "Refiled on %t")
2931 (clock-out . ""))
2932 "Headings for notes added to entries.
2934 The value is an alist, with the car being a symbol indicating the
2935 note context, and the cdr is the heading to be used. The heading
2936 may also be the empty string. The following placeholders can be
2937 used:
2939 %t a time stamp.
2940 %T an active time stamp instead the default inactive one
2941 %d a short-format time stamp.
2942 %D an active short-format time stamp.
2943 %s the new TODO state or time stamp (inactive), in double quotes.
2944 %S the old TODO state or time stamp (inactive), in double quotes.
2945 %u the user name.
2946 %U full user name.
2948 In fact, it is not a good idea to change the `state' entry,
2949 because Agenda Log mode depends on the format of these entries."
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type '(list :greedy t
2953 (cons (const :tag "Heading when closing an item" done) string)
2954 (cons (const :tag
2955 "Heading when changing todo state (todo sequence only)"
2956 state) string)
2957 (cons (const :tag "Heading when just taking a note" note) string)
2958 (cons (const :tag "Heading when rescheduling" reschedule) string)
2959 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2960 (cons (const :tag "Heading when changing deadline" redeadline) string)
2961 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2962 (cons (const :tag "Heading when refiling" refile) string)
2963 (cons (const :tag "Heading when clocking out" clock-out) string)))
2965 (unless (assq 'note org-log-note-headings)
2966 (push '(note . "%t") org-log-note-headings))
2968 (defcustom org-log-into-drawer nil
2969 "Non-nil means insert state change notes and time stamps into a drawer.
2970 When nil, state changes notes will be inserted after the headline and
2971 any scheduling and clock lines, but not inside a drawer.
2973 The value of this variable should be the name of the drawer to use.
2974 LOGBOOK is proposed as the default drawer for this purpose, you can
2975 also set this to a string to define the drawer of your choice.
2977 A value of t is also allowed, representing \"LOGBOOK\".
2979 A value of t or nil can also be set with on a per-file-basis with
2981 #+STARTUP: logdrawer
2982 #+STARTUP: nologdrawer
2984 If this variable is set, `org-log-state-notes-insert-after-drawers'
2985 will be ignored.
2987 You can set the property LOG_INTO_DRAWER to overrule this setting for
2988 a subtree.
2990 Do not check directly this variable in a Lisp program. Call
2991 function `org-log-into-drawer' instead."
2992 :group 'org-todo
2993 :group 'org-progress
2994 :type '(choice
2995 (const :tag "Not into a drawer" nil)
2996 (const :tag "LOGBOOK" t)
2997 (string :tag "Other")))
2999 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3001 (defun org-log-into-drawer ()
3002 "Name of the log drawer, as a string, or nil.
3003 This is the value of `org-log-into-drawer'. However, if the
3004 current entry has or inherits a LOG_INTO_DRAWER property, it will
3005 be used instead of the default value."
3006 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3007 (cond ((equal p "nil") nil)
3008 ((equal p "t") "LOGBOOK")
3009 ((stringp p) p)
3010 (p "LOGBOOK")
3011 ((stringp org-log-into-drawer) org-log-into-drawer)
3012 (org-log-into-drawer "LOGBOOK"))))
3014 (defcustom org-log-state-notes-insert-after-drawers nil
3015 "Non-nil means insert state change notes after any drawers in entry.
3016 Only the drawers that *immediately* follow the headline and the
3017 deadline/scheduled line are skipped.
3018 When nil, insert notes right after the heading and perhaps the line
3019 with deadline/scheduling if present.
3021 This variable will have no effect if `org-log-into-drawer' is
3022 set."
3023 :group 'org-todo
3024 :group 'org-progress
3025 :type 'boolean)
3027 (defcustom org-log-states-order-reversed t
3028 "Non-nil means the latest state note will be directly after heading.
3029 When nil, the state change notes will be ordered according to time.
3031 This option can also be set with on a per-file-basis with
3033 #+STARTUP: logstatesreversed
3034 #+STARTUP: nologstatesreversed"
3035 :group 'org-todo
3036 :group 'org-progress
3037 :type 'boolean)
3039 (defcustom org-todo-repeat-to-state nil
3040 "The TODO state to which a repeater should return the repeating task.
3041 By default this is the first task of a TODO sequence or the
3042 previous state of a TYPE_TODO set. But you can specify to use
3043 the previous state in a TODO sequence or a string.
3045 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3046 entry, which has precedence over this option."
3047 :group 'org-todo
3048 :version "24.1"
3049 :type '(choice (const :tag "Use the previous TODO state" t)
3050 (const :tag "Use the head of the TODO sequence" nil)
3051 (string :tag "Use a specific TODO state")))
3053 (defcustom org-log-repeat 'time
3054 "Non-nil means record moving through the DONE state when triggering repeat.
3055 An auto-repeating task is immediately switched back to TODO when
3056 marked DONE. If you are not logging state changes (by adding \"@\"
3057 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3058 record a closing note, there will be no record of the task moving
3059 through DONE. This variable forces taking a note anyway.
3061 nil Don't force a record
3062 time Record a time stamp
3063 note Prompt for a note and add it with template `org-log-note-headings'
3065 This option can also be set with on a per-file-basis with
3067 #+STARTUP: nologrepeat
3068 #+STARTUP: logrepeat
3069 #+STARTUP: lognoterepeat
3071 You can have local logging settings for a subtree by setting the LOGGING
3072 property to one or more of these keywords."
3073 :group 'org-todo
3074 :group 'org-progress
3075 :type '(choice
3076 (const :tag "Don't force a record" nil)
3077 (const :tag "Force recording the DONE state" time)
3078 (const :tag "Force recording a note with the DONE state" note)))
3081 (defgroup org-priorities nil
3082 "Priorities in Org mode."
3083 :tag "Org Priorities"
3084 :group 'org-todo)
3086 (defcustom org-enable-priority-commands t
3087 "Non-nil means priority commands are active.
3088 When nil, these commands will be disabled, so that you never accidentally
3089 set a priority."
3090 :group 'org-priorities
3091 :type 'boolean)
3093 (defcustom org-highest-priority ?A
3094 "The highest priority of TODO items. A character like ?A, ?B etc.
3095 Must have a smaller ASCII number than `org-lowest-priority'."
3096 :group 'org-priorities
3097 :type 'character)
3099 (defcustom org-lowest-priority ?C
3100 "The lowest priority of TODO items. A character like ?A, ?B etc.
3101 Must have a larger ASCII number than `org-highest-priority'."
3102 :group 'org-priorities
3103 :type 'character)
3105 (defcustom org-default-priority ?B
3106 "The default priority of TODO items.
3107 This is the priority an item gets if no explicit priority is given.
3108 When starting to cycle on an empty priority the first step in the cycle
3109 depends on `org-priority-start-cycle-with-default'. The resulting first
3110 step priority must not exceed the range from `org-highest-priority' to
3111 `org-lowest-priority' which means that `org-default-priority' has to be
3112 in this range exclusive or inclusive the range boundaries. Else the
3113 first step refuses to set the default and the second will fall back
3114 to (depending on the command used) the highest or lowest priority."
3115 :group 'org-priorities
3116 :type 'character)
3118 (defcustom org-priority-start-cycle-with-default t
3119 "Non-nil means start with default priority when starting to cycle.
3120 When this is nil, the first step in the cycle will be (depending on the
3121 command used) one higher or lower than the default priority.
3122 See also `org-default-priority'."
3123 :group 'org-priorities
3124 :type 'boolean)
3126 (defcustom org-get-priority-function nil
3127 "Function to extract the priority from a string.
3128 The string is normally the headline. If this is nil Org computes the
3129 priority from the priority cookie like [#A] in the headline. It returns
3130 an integer, increasing by 1000 for each priority level.
3131 The user can set a different function here, which should take a string
3132 as an argument and return the numeric priority."
3133 :group 'org-priorities
3134 :version "24.1"
3135 :type '(choice
3136 (const nil)
3137 (function)))
3139 (defgroup org-time nil
3140 "Options concerning time stamps and deadlines in Org mode."
3141 :tag "Org Time"
3142 :group 'org)
3144 (defcustom org-time-stamp-rounding-minutes '(0 5)
3145 "Number of minutes to round time stamps to.
3146 \\<org-mode-map>\
3147 These are two values, the first applies when first creating a time stamp.
3148 The second applies when changing it with the commands `S-up' and `S-down'.
3149 When changing the time stamp, this means that it will change in steps
3150 of N minutes, as given by the second value.
3152 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3153 numbers should be factors of 60, so for example 5, 10, 15.
3155 When this is larger than 1, you can still force an exact time stamp by using
3156 a double prefix argument to a time stamp command like \
3157 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3158 and by using a prefix arg to `S-up/down' to specify the exact number
3159 of minutes to shift."
3160 :group 'org-time
3161 :get (lambda (var) ; Make sure both elements are there
3162 (if (integerp (default-value var))
3163 (list (default-value var) 5)
3164 (default-value var)))
3165 :type '(list
3166 (integer :tag "when inserting times")
3167 (integer :tag "when modifying times")))
3169 ;; Normalize old customizations of this variable.
3170 (when (integerp org-time-stamp-rounding-minutes)
3171 (setq org-time-stamp-rounding-minutes
3172 (list org-time-stamp-rounding-minutes
3173 org-time-stamp-rounding-minutes)))
3175 (defcustom org-display-custom-times nil
3176 "Non-nil means overlay custom formats over all time stamps.
3177 The formats are defined through the variable `org-time-stamp-custom-formats'.
3178 To turn this on on a per-file basis, insert anywhere in the file:
3179 #+STARTUP: customtime"
3180 :group 'org-time
3181 :set 'set-default
3182 :type 'sexp)
3183 (make-variable-buffer-local 'org-display-custom-times)
3185 (defcustom org-time-stamp-custom-formats
3186 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3187 "Custom formats for time stamps. See `format-time-string' for the syntax.
3188 These are overlaid over the default ISO format if the variable
3189 `org-display-custom-times' is set. Time like %H:%M should be at the
3190 end of the second format. The custom formats are also honored by export
3191 commands, if custom time display is turned on at the time of export."
3192 :group 'org-time
3193 :type 'sexp)
3195 (defun org-time-stamp-format (&optional long inactive)
3196 "Get the right format for a time string."
3197 (let ((f (if long (cdr org-time-stamp-formats)
3198 (car org-time-stamp-formats))))
3199 (if inactive
3200 (concat "[" (substring f 1 -1) "]")
3201 f)))
3203 (defcustom org-deadline-warning-days 14
3204 "Number of days before expiration during which a deadline becomes active.
3205 This variable governs the display in sparse trees and in the agenda.
3206 When 0 or negative, it means use this number (the absolute value of it)
3207 even if a deadline has a different individual lead time specified.
3209 Custom commands can set this variable in the options section."
3210 :group 'org-time
3211 :group 'org-agenda-daily/weekly
3212 :type 'integer)
3214 (defcustom org-scheduled-delay-days 0
3215 "Number of days before a scheduled item becomes active.
3216 This variable governs the display in sparse trees and in the agenda.
3217 The default value (i.e. 0) means: don't delay scheduled item.
3218 When negative, it means use this number (the absolute value of it)
3219 even if a scheduled item has a different individual delay time
3220 specified.
3222 Custom commands can set this variable in the options section."
3223 :group 'org-time
3224 :group 'org-agenda-daily/weekly
3225 :version "24.4"
3226 :package-version '(Org . "8.0")
3227 :type 'integer)
3229 (defcustom org-read-date-prefer-future t
3230 "Non-nil means assume future for incomplete date input from user.
3231 This affects the following situations:
3232 1. The user gives a month but not a year.
3233 For example, if it is April and you enter \"feb 2\", this will be read
3234 as Feb 2, *next* year. \"May 5\", however, will be this year.
3235 2. The user gives a day, but no month.
3236 For example, if today is the 15th, and you enter \"3\", Org will read
3237 this as the third of *next* month. However, if you enter \"17\",
3238 it will be considered as *this* month.
3240 If you set this variable to the symbol `time', then also the following
3241 will work:
3243 3. If the user gives a time.
3244 If the time is before now, it will be interpreted as tomorrow.
3246 Currently none of this works for ISO week specifications.
3248 When this option is nil, the current day, month and year will always be
3249 used as defaults.
3251 See also `org-agenda-jump-prefer-future'."
3252 :group 'org-time
3253 :type '(choice
3254 (const :tag "Never" nil)
3255 (const :tag "Check month and day" t)
3256 (const :tag "Check month, day, and time" time)))
3258 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3259 "Should the agenda jump command prefer the future for incomplete dates?
3260 The default is to do the same as configured in `org-read-date-prefer-future'.
3261 But you can also set a deviating value here.
3262 This may t or nil, or the symbol `org-read-date-prefer-future'."
3263 :group 'org-agenda
3264 :group 'org-time
3265 :version "24.1"
3266 :type '(choice
3267 (const :tag "Use org-read-date-prefer-future"
3268 org-read-date-prefer-future)
3269 (const :tag "Never" nil)
3270 (const :tag "Always" t)))
3272 (defcustom org-read-date-force-compatible-dates t
3273 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3275 Depending on the system Emacs is running on, certain dates cannot
3276 be represented with the type used internally to represent time.
3277 Dates between 1970-1-1 and 2038-1-1 can always be represented
3278 correctly. Some systems allow for earlier dates, some for later,
3279 some for both. One way to find out it to insert any date into an
3280 Org buffer, putting the cursor on the year and hitting S-up and
3281 S-down to test the range.
3283 When this variable is set to t, the date/time prompt will not let
3284 you specify dates outside the 1970-2037 range, so it is certain that
3285 these dates will work in whatever version of Emacs you are
3286 running, and also that you can move a file from one Emacs implementation
3287 to another. WHenever Org is forcing the year for you, it will display
3288 a message and beep.
3290 When this variable is nil, Org will check if the date is
3291 representable in the specific Emacs implementation you are using.
3292 If not, it will force a year, usually the current year, and beep
3293 to remind you. Currently this setting is not recommended because
3294 the likelihood that you will open your Org files in an Emacs that
3295 has limited date range is not negligible.
3297 A workaround for this problem is to use diary sexp dates for time
3298 stamps outside of this range."
3299 :group 'org-time
3300 :version "24.1"
3301 :type 'boolean)
3303 (defcustom org-read-date-display-live t
3304 "Non-nil means display current interpretation of date prompt live.
3305 This display will be in an overlay, in the minibuffer."
3306 :group 'org-time
3307 :type 'boolean)
3309 (defcustom org-read-date-popup-calendar t
3310 "Non-nil means pop up a calendar when prompting for a date.
3311 In the calendar, the date can be selected with mouse-1. However, the
3312 minibuffer will also be active, and you can simply enter the date as well.
3313 When nil, only the minibuffer will be available."
3314 :group 'org-time
3315 :type 'boolean)
3316 (defvaralias 'org-popup-calendar-for-date-prompt
3317 'org-read-date-popup-calendar)
3319 (defcustom org-extend-today-until 0
3320 "The hour when your day really ends. Must be an integer.
3321 This has influence for the following applications:
3322 - When switching the agenda to \"today\". It it is still earlier than
3323 the time given here, the day recognized as TODAY is actually yesterday.
3324 - When a date is read from the user and it is still before the time given
3325 here, the current date and time will be assumed to be yesterday, 23:59.
3326 Also, timestamps inserted in capture templates follow this rule.
3328 IMPORTANT: This is a feature whose implementation is and likely will
3329 remain incomplete. Really, it is only here because past midnight seems to
3330 be the favorite working time of John Wiegley :-)"
3331 :group 'org-time
3332 :type 'integer)
3334 (defcustom org-use-effective-time nil
3335 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3336 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3337 \"effective time\" of any timestamps between midnight and 8am will be
3338 23:59 of the previous day."
3339 :group 'org-time
3340 :version "24.1"
3341 :type 'boolean)
3343 (defcustom org-use-last-clock-out-time-as-effective-time nil
3344 "When non-nil, use the last clock out time for `org-todo'.
3345 Note that this option has precedence over the combined use of
3346 `org-use-effective-time' and `org-extend-today-until'."
3347 :group 'org-time
3348 :version "24.4"
3349 :package-version '(Org . "8.0")
3350 :type 'boolean)
3352 (defcustom org-edit-timestamp-down-means-later nil
3353 "Non-nil means S-down will increase the time in a time stamp.
3354 When nil, S-up will increase."
3355 :group 'org-time
3356 :type 'boolean)
3358 (defcustom org-calendar-follow-timestamp-change t
3359 "Non-nil means make the calendar window follow timestamp changes.
3360 When a timestamp is modified and the calendar window is visible, it will be
3361 moved to the new date."
3362 :group 'org-time
3363 :type 'boolean)
3365 (defgroup org-tags nil
3366 "Options concerning tags in Org mode."
3367 :tag "Org Tags"
3368 :group 'org)
3370 (defcustom org-tag-alist nil
3371 "Default tags available in Org files.
3373 The value of this variable is an alist. Associations either:
3375 (TAG)
3376 (TAG . SELECT)
3377 (SPECIAL)
3379 where TAG is a tag as a string, SELECT is character, used to
3380 select that tag through the fast tag selection interface, and
3381 SPECIAL is one of the following keywords: `:startgroup',
3382 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3383 `:newline'. These keywords are used to define a hierarchy of
3384 tags. See manual for details.
3386 When this variable is nil, Org mode bases tag input on what is
3387 already in the buffer. The value can be overridden locally by
3388 using a TAGS keyword, e.g.,
3390 #+TAGS: tag1 tag2
3392 See also `org-tag-persistent-alist' to sidestep this behavior."
3393 :group 'org-tags
3394 :type '(repeat
3395 (choice
3396 (cons :tag "Tag with key"
3397 (string :tag "Tag name")
3398 (character :tag "Access char"))
3399 (list :tag "Tag" (string :tag "Tag name"))
3400 (const :tag "Start radio group" (:startgroup))
3401 (const :tag "Start tag group, non distinct" (:startgrouptag))
3402 (const :tag "Group tags delimiter" (:grouptags))
3403 (const :tag "End radio group" (:endgroup))
3404 (const :tag "End tag group, non distinct" (:endgrouptag))
3405 (const :tag "New line" (:newline)))))
3407 (defcustom org-tag-persistent-alist nil
3408 "Tags always available in Org files.
3410 The value of this variable is an alist. Associations either:
3412 (TAG)
3413 (TAG . SELECT)
3414 (SPECIAL)
3416 where TAG is a tag as a string, SELECT is a character, used to
3417 select that tag through the fast tag selection interface, and
3418 SPECIAL is one of the following keywords: `:startgroup',
3419 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3420 `:newline'. These keywords are used to define a hierarchy of
3421 tags. See manual for details.
3423 Unlike to `org-tag-alist', tags defined in this variable do not
3424 depend on a local TAGS keyword. Instead, to disable these tags
3425 on a per-file basis, insert anywhere in the file:
3427 #+STARTUP: noptag"
3428 :group 'org-tags
3429 :type '(repeat
3430 (choice
3431 (cons :tag "Tag with key"
3432 (string :tag "Tag name")
3433 (character :tag "Access char"))
3434 (list :tag "Tag" (string :tag "Tag name"))
3435 (const :tag "Start radio group" (:startgroup))
3436 (const :tag "Start tag group, non distinct" (:startgrouptag))
3437 (const :tag "Group tags delimiter" (:grouptags))
3438 (const :tag "End radio group" (:endgroup))
3439 (const :tag "End tag group, non distinct" (:endgrouptag))
3440 (const :tag "New line" (:newline)))))
3442 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3443 "If non-nil, always offer completion for all tags of all agenda files.
3444 Instead of customizing this variable directly, you might want to
3445 set it locally for capture buffers, because there no list of
3446 tags in that file can be created dynamically (there are none).
3448 (add-hook \\='org-capture-mode-hook
3449 (lambda ()
3450 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3451 :group 'org-tags
3452 :version "24.1"
3453 :type 'boolean)
3455 (defvar org-file-tags nil
3456 "List of tags that can be inherited by all entries in the file.
3457 The tags will be inherited if the variable `org-use-tag-inheritance'
3458 says they should be.
3459 This variable is populated from #+FILETAGS lines.")
3461 (defcustom org-use-fast-tag-selection 'auto
3462 "Non-nil means use fast tag selection scheme.
3463 This is a special interface to select and deselect tags with single keys.
3464 When nil, fast selection is never used.
3465 When the symbol `auto', fast selection is used if and only if selection
3466 characters for tags have been configured, either through the variable
3467 `org-tag-alist' or through a #+TAGS line in the buffer.
3468 When t, fast selection is always used and selection keys are assigned
3469 automatically if necessary."
3470 :group 'org-tags
3471 :type '(choice
3472 (const :tag "Always" t)
3473 (const :tag "Never" nil)
3474 (const :tag "When selection characters are configured" auto)))
3476 (defcustom org-fast-tag-selection-single-key nil
3477 "Non-nil means fast tag selection exits after first change.
3478 When nil, you have to press RET to exit it.
3479 During fast tag selection, you can toggle this flag with `C-c'.
3480 This variable can also have the value `expert'. In this case, the window
3481 displaying the tags menu is not even shown, until you press C-c again."
3482 :group 'org-tags
3483 :type '(choice
3484 (const :tag "No" nil)
3485 (const :tag "Yes" t)
3486 (const :tag "Expert" expert)))
3488 (defvar org-fast-tag-selection-include-todo nil
3489 "Non-nil means fast tags selection interface will also offer TODO states.
3490 This is an undocumented feature, you should not rely on it.")
3492 (defcustom org-tags-column -77
3493 "The column to which tags should be indented in a headline.
3494 If this number is positive, it specifies the column. If it is negative,
3495 it means that the tags should be flushright to that column. For example,
3496 -80 works well for a normal 80 character screen.
3497 When 0, place tags directly after headline text, with only one space in
3498 between."
3499 :group 'org-tags
3500 :type 'integer)
3502 (defcustom org-auto-align-tags t
3503 "Non-nil keeps tags aligned when modifying headlines.
3504 Some operations (i.e. demoting) change the length of a headline and
3505 therefore shift the tags around. With this option turned on, after
3506 each such operation the tags are again aligned to `org-tags-column'."
3507 :group 'org-tags
3508 :type 'boolean)
3510 (defcustom org-use-tag-inheritance t
3511 "Non-nil means tags in levels apply also for sublevels.
3512 When nil, only the tags directly given in a specific line apply there.
3513 This may also be a list of tags that should be inherited, or a regexp that
3514 matches tags that should be inherited. Additional control is possible
3515 with the variable `org-tags-exclude-from-inheritance' which gives an
3516 explicit list of tags to be excluded from inheritance, even if the value of
3517 `org-use-tag-inheritance' would select it for inheritance.
3519 If this option is t, a match early-on in a tree can lead to a large
3520 number of matches in the subtree when constructing the agenda or creating
3521 a sparse tree. If you only want to see the first match in a tree during
3522 a search, check out the variable `org-tags-match-list-sublevels'."
3523 :group 'org-tags
3524 :type '(choice
3525 (const :tag "Not" nil)
3526 (const :tag "Always" t)
3527 (repeat :tag "Specific tags" (string :tag "Tag"))
3528 (regexp :tag "Tags matched by regexp")))
3530 (defcustom org-tags-exclude-from-inheritance nil
3531 "List of tags that should never be inherited.
3532 This is a way to exclude a few tags from inheritance. For way to do
3533 the opposite, to actively allow inheritance for selected tags,
3534 see the variable `org-use-tag-inheritance'."
3535 :group 'org-tags
3536 :type '(repeat (string :tag "Tag")))
3538 (defun org-tag-inherit-p (tag)
3539 "Check if TAG is one that should be inherited."
3540 (cond
3541 ((member tag org-tags-exclude-from-inheritance) nil)
3542 ((eq org-use-tag-inheritance t) t)
3543 ((not org-use-tag-inheritance) nil)
3544 ((stringp org-use-tag-inheritance)
3545 (string-match org-use-tag-inheritance tag))
3546 ((listp org-use-tag-inheritance)
3547 (member tag org-use-tag-inheritance))
3548 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3550 (defcustom org-tags-match-list-sublevels t
3551 "Non-nil means list also sublevels of headlines matching a search.
3552 This variable applies to tags/property searches, and also to stuck
3553 projects because this search is based on a tags match as well.
3555 When set to the symbol `indented', sublevels are indented with
3556 leading dots.
3558 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3559 the sublevels of a headline matching a tag search often also match
3560 the same search. Listing all of them can create very long lists.
3561 Setting this variable to nil causes subtrees of a match to be skipped.
3563 This variable is semi-obsolete and probably should always be true. It
3564 is better to limit inheritance to certain tags using the variables
3565 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3566 :group 'org-tags
3567 :type '(choice
3568 (const :tag "No, don't list them" nil)
3569 (const :tag "Yes, do list them" t)
3570 (const :tag "List them, indented with leading dots" indented)))
3572 (defcustom org-tags-sort-function nil
3573 "When set, tags are sorted using this function as a comparator."
3574 :group 'org-tags
3575 :type '(choice
3576 (const :tag "No sorting" nil)
3577 (const :tag "Alphabetical" org-string-collate-lessp)
3578 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3579 (function :tag "Custom function" nil)))
3581 (defvar org-tags-history nil
3582 "History of minibuffer reads for tags.")
3583 (defvar org-last-tags-completion-table nil
3584 "The last used completion table for tags.")
3585 (defvar org-after-tags-change-hook nil
3586 "Hook that is run after the tags in a line have changed.")
3588 (defgroup org-properties nil
3589 "Options concerning properties in Org mode."
3590 :tag "Org Properties"
3591 :group 'org)
3593 (defcustom org-property-format "%-10s %s"
3594 "How property key/value pairs should be formatted by `indent-line'.
3595 When `indent-line' hits a property definition, it will format the line
3596 according to this format, mainly to make sure that the values are
3597 lined-up with respect to each other."
3598 :group 'org-properties
3599 :type 'string)
3601 (defcustom org-properties-postprocess-alist nil
3602 "Alist of properties and functions to adjust inserted values.
3603 Elements of this alist must be of the form
3605 ([string] [function])
3607 where [string] must be a property name and [function] must be a
3608 lambda expression: this lambda expression must take one argument,
3609 the value to adjust, and return the new value as a string.
3611 For example, this element will allow the property \"Remaining\"
3612 to be updated wrt the relation between the \"Effort\" property
3613 and the clock summary:
3615 ((\"Remaining\" (lambda(value)
3616 (let ((clocksum (org-clock-sum-current-item))
3617 (effort (org-duration-to-minutes
3618 (org-entry-get (point) \"Effort\"))))
3619 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3620 :group 'org-properties
3621 :version "24.1"
3622 :type '(alist :key-type (string :tag "Property")
3623 :value-type (function :tag "Function")))
3625 (defcustom org-use-property-inheritance nil
3626 "Non-nil means properties apply also for sublevels.
3628 This setting is chiefly used during property searches. Turning it on can
3629 cause significant overhead when doing a search, which is why it is not
3630 on by default.
3632 When nil, only the properties directly given in the current entry count.
3633 When t, every property is inherited. The value may also be a list of
3634 properties that should have inheritance, or a regular expression matching
3635 properties that should be inherited.
3637 However, note that some special properties use inheritance under special
3638 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3639 and the properties ending in \"_ALL\" when they are used as descriptor
3640 for valid values of a property.
3642 Note for programmers:
3643 When querying an entry with `org-entry-get', you can control if inheritance
3644 should be used. By default, `org-entry-get' looks only at the local
3645 properties. You can request inheritance by setting the inherit argument
3646 to t (to force inheritance) or to `selective' (to respect the setting
3647 in this variable)."
3648 :group 'org-properties
3649 :type '(choice
3650 (const :tag "Not" nil)
3651 (const :tag "Always" t)
3652 (repeat :tag "Specific properties" (string :tag "Property"))
3653 (regexp :tag "Properties matched by regexp")))
3655 (defun org-property-inherit-p (property)
3656 "Return a non-nil value if PROPERTY should be inherited."
3657 (cond
3658 ((eq org-use-property-inheritance t) t)
3659 ((not org-use-property-inheritance) nil)
3660 ((stringp org-use-property-inheritance)
3661 (string-match org-use-property-inheritance property))
3662 ((listp org-use-property-inheritance)
3663 (member-ignore-case property org-use-property-inheritance))
3664 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3666 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3667 "The default column format, if no other format has been defined.
3668 This variable can be set on the per-file basis by inserting a line
3670 #+COLUMNS: %25ITEM ....."
3671 :group 'org-properties
3672 :type 'string)
3674 (defcustom org-columns-ellipses ".."
3675 "The ellipses to be used when a field in column view is truncated.
3676 When this is the empty string, as many characters as possible are shown,
3677 but then there will be no visual indication that the field has been truncated.
3678 When this is a string of length N, the last N characters of a truncated
3679 field are replaced by this string. If the column is narrower than the
3680 ellipses string, only part of the ellipses string will be shown."
3681 :group 'org-properties
3682 :type 'string)
3684 (defconst org-global-properties-fixed
3685 '(("VISIBILITY_ALL" . "folded children content all")
3686 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3687 "List of property/value pairs that can be inherited by any entry.
3689 These are fixed values, for the preset properties. The user variable
3690 that can be used to add to this list is `org-global-properties'.
3692 The entries in this list are cons cells where the car is a property
3693 name and cdr is a string with the value. If the value represents
3694 multiple items like an \"_ALL\" property, separate the items by
3695 spaces.")
3697 (defcustom org-global-properties nil
3698 "List of property/value pairs that can be inherited by any entry.
3700 This list will be combined with the constant `org-global-properties-fixed'.
3702 The entries in this list are cons cells where the car is a property
3703 name and cdr is a string with the value.
3705 You can set buffer-local values for the same purpose in the variable
3706 `org-file-properties' this by adding lines like
3708 #+PROPERTY: NAME VALUE"
3709 :group 'org-properties
3710 :type '(repeat
3711 (cons (string :tag "Property")
3712 (string :tag "Value"))))
3714 (defvar-local org-file-properties nil
3715 "List of property/value pairs that can be inherited by any entry.
3716 Valid for the current buffer.
3717 This variable is populated from #+PROPERTY lines.")
3719 (defgroup org-agenda nil
3720 "Options concerning agenda views in Org mode."
3721 :tag "Org Agenda"
3722 :group 'org)
3724 (defvar-local org-category nil
3725 "Variable used by Org files to set a category for agenda display.
3726 Such files should use a file variable to set it, for example
3728 # -*- mode: org; org-category: \"ELisp\"
3730 or contain a special line
3732 #+CATEGORY: ELisp
3734 If the file does not specify a category, then file's base name
3735 is used instead.")
3736 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3738 (defcustom org-agenda-files nil
3739 "The files to be used for agenda display.
3741 If an entry is a directory, all files in that directory that are matched
3742 by `org-agenda-file-regexp' will be part of the file list.
3744 If the value of the variable is not a list but a single file name, then
3745 the list of agenda files is actually stored and maintained in that file,
3746 one agenda file per line. In this file paths can be given relative to
3747 `org-directory'. Tilde expansion and environment variable substitution
3748 are also made.
3750 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3751 and removed with `\\[org-remove-file]'."
3752 :group 'org-agenda
3753 :type '(choice
3754 (repeat :tag "List of files and directories" file)
3755 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3757 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3758 "Regular expression to match files for `org-agenda-files'.
3759 If any element in the list in that variable contains a directory instead
3760 of a normal file, all files in that directory that are matched by this
3761 regular expression will be included."
3762 :group 'org-agenda
3763 :type 'regexp)
3765 (defcustom org-agenda-text-search-extra-files nil
3766 "List of extra files to be searched by text search commands.
3767 These files will be searched in addition to the agenda files by the
3768 commands `org-search-view' (`\\[org-agenda] s') \
3769 and `org-occur-in-agenda-files'.
3770 Note that these files will only be searched for text search commands,
3771 not for the other agenda views like todo lists, tag searches or the weekly
3772 agenda. This variable is intended to list notes and possibly archive files
3773 that should also be searched by these two commands.
3774 In fact, if the first element in the list is the symbol `agenda-archives',
3775 then all archive files of all agenda files will be added to the search
3776 scope."
3777 :group 'org-agenda
3778 :type '(set :greedy t
3779 (const :tag "Agenda Archives" agenda-archives)
3780 (repeat :inline t (file))))
3782 (defvaralias 'org-agenda-multi-occur-extra-files
3783 'org-agenda-text-search-extra-files)
3785 (defcustom org-agenda-skip-unavailable-files nil
3786 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3787 A nil value means to remove them, after a query, from the list."
3788 :group 'org-agenda
3789 :type 'boolean)
3791 (defcustom org-agenda-diary-file 'diary-file
3792 "File to which to add new entries with the `i' key in agenda and calendar.
3793 When this is the symbol `diary-file', the functionality in the Emacs
3794 calendar will be used to add entries to the `diary-file'. But when this
3795 points to a file, `org-agenda-diary-entry' will be used instead."
3796 :group 'org-agenda
3797 :type '(choice
3798 (const :tag "The standard Emacs diary file" diary-file)
3799 (file :tag "Special Org file diary entries")))
3801 (defgroup org-latex nil
3802 "Options for embedding LaTeX code into Org mode."
3803 :tag "Org LaTeX"
3804 :group 'org)
3806 (defcustom org-format-latex-options
3807 '(:foreground default :background default :scale 1.0
3808 :html-foreground "Black" :html-background "Transparent"
3809 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3810 "Options for creating images from LaTeX fragments.
3811 This is a property list with the following properties:
3812 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3813 `default' means use the foreground of the default face.
3814 `auto' means use the foreground from the text face.
3815 :background the background color, or \"Transparent\".
3816 `default' means use the background of the default face.
3817 `auto' means use the background from the text face.
3818 :scale a scaling factor for the size of the images, to get more pixels
3819 :html-foreground, :html-background, :html-scale
3820 the same numbers for HTML export.
3821 :matchers a list indicating which matchers should be used to
3822 find LaTeX fragments. Valid members of this list are:
3823 \"begin\" find environments
3824 \"$1\" find single characters surrounded by $.$
3825 \"$\" find math expressions surrounded by $...$
3826 \"$$\" find math expressions surrounded by $$....$$
3827 \"\\(\" find math expressions surrounded by \\(...\\)
3828 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3829 :group 'org-latex
3830 :type 'plist)
3832 (defcustom org-format-latex-signal-error t
3833 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3834 When nil, just push out a message."
3835 :group 'org-latex
3836 :version "24.1"
3837 :type 'boolean)
3839 (defcustom org-latex-to-mathml-jar-file nil
3840 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3841 Use this to specify additional executable file say a jar file.
3843 When using MathToWeb as the converter, specify the full-path to
3844 your mathtoweb.jar file."
3845 :group 'org-latex
3846 :version "24.1"
3847 :type '(choice
3848 (const :tag "None" nil)
3849 (file :tag "JAR file" :must-match t)))
3851 (defcustom org-latex-to-mathml-convert-command nil
3852 "Command to convert LaTeX fragments to MathML.
3853 Replace format-specifiers in the command as noted below and use
3854 `shell-command' to convert LaTeX to MathML.
3855 %j: Executable file in fully expanded form as specified by
3856 `org-latex-to-mathml-jar-file'.
3857 %I: Input LaTeX file in fully expanded form.
3858 %i: The latex fragment to be converted.
3859 %o: Output MathML file.
3861 This command is used by `org-create-math-formula'.
3863 When using MathToWeb as the converter, set this option to
3864 \"java -jar %j -unicode -force -df %o %I\".
3866 When using LaTeXML set this option to
3867 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3868 :group 'org-latex
3869 :version "24.1"
3870 :type '(choice
3871 (const :tag "None" nil)
3872 (string :tag "\nShell command")))
3874 (defcustom org-preview-latex-default-process 'dvipng
3875 "The default process to convert LaTeX fragments to image files.
3876 All available processes and theirs documents can be found in
3877 `org-preview-latex-process-alist', which see."
3878 :group 'org-latex
3879 :version "26.1"
3880 :package-version '(Org . "9.0")
3881 :type 'symbol)
3883 (defcustom org-preview-latex-process-alist
3884 '((dvipng
3885 :programs ("latex" "dvipng")
3886 :description "dvi > png"
3887 :message "you need to install the programs: latex and dvipng."
3888 :image-input-type "dvi"
3889 :image-output-type "png"
3890 :image-size-adjust (1.0 . 1.0)
3891 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3892 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3893 (dvisvgm
3894 :programs ("latex" "dvisvgm")
3895 :description "dvi > svg"
3896 :message "you need to install the programs: latex and dvisvgm."
3897 :use-xcolor t
3898 :image-input-type "dvi"
3899 :image-output-type "svg"
3900 :image-size-adjust (1.7 . 1.5)
3901 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3902 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3903 (imagemagick
3904 :programs ("latex" "convert")
3905 :description "pdf > png"
3906 :message "you need to install the programs: latex and imagemagick."
3907 :use-xcolor t
3908 :image-input-type "pdf"
3909 :image-output-type "png"
3910 :image-size-adjust (1.0 . 1.0)
3911 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3912 :image-converter
3913 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3914 "Definitions of external processes for LaTeX previewing.
3915 Org mode can use some external commands to generate TeX snippet's images for
3916 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3917 `org-create-formula-image' how to call them.
3919 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3920 PROPERTIES accepts the following attributes:
3922 :programs list of strings, required programs.
3923 :description string, describe the process.
3924 :message string, message it when required programs cannot be found.
3925 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3926 :image-output-type string, output file type of image converter (e.g., \"png\").
3927 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3928 deal with background and foreground color of image.
3929 Otherwise, dvipng style background and foreground color
3930 format are generated. You may then refer to them in
3931 command options with \"%F\" and \"%B\".
3932 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3933 image size showed in buffer and the cdr element is for
3934 HTML file. This option is only useful for process
3935 developers, users should use variable
3936 `org-format-latex-options' instead.
3937 :post-clean list of strings, files matched are to be cleaned up once
3938 the image is generated. When nil, the files with \".dvi\",
3939 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3940 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3941 be cleaned up.
3942 :latex-header list of strings, the LaTeX header of the snippet file.
3943 When nil, the fallback value is used instead, which is
3944 controlled by `org-format-latex-header',
3945 `org-latex-default-packages-alist' and
3946 `org-latex-packages-alist', which see.
3947 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3948 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3949 replaced with values defined below.
3950 :image-converter list of image converter commands strings. Each of them is
3951 given to the shell and supports any of the following
3952 place-holders defined below.
3954 Place-holders used by `:image-converter' and `:latex-compiler':
3956 %f input file name
3957 %b base name of input file
3958 %o base directory of input file
3959 %O absolute output file name
3961 Place-holders only used by `:image-converter':
3963 %F foreground of image
3964 %B background of image
3965 %D dpi, which is used to adjust image size by some processing commands.
3966 %S the image size scale ratio, which is used to adjust image size by some
3967 processing commands."
3968 :group 'org-latex
3969 :version "26.1"
3970 :package-version '(Org . "9.0")
3971 :type '(alist :tag "LaTeX to image backends"
3972 :value-type (plist)))
3974 (defcustom org-preview-latex-image-directory "ltximg/"
3975 "Path to store latex preview images.
3976 A relative path here creates many directories relative to the
3977 processed Org files paths. An absolute path puts all preview
3978 images at the same place."
3979 :group 'org-latex
3980 :version "26.1"
3981 :package-version '(Org . "9.0")
3982 :type 'string)
3984 (defun org-format-latex-mathml-available-p ()
3985 "Return t if `org-latex-to-mathml-convert-command' is usable."
3986 (save-match-data
3987 (when (and (boundp 'org-latex-to-mathml-convert-command)
3988 org-latex-to-mathml-convert-command)
3989 (let ((executable (car (split-string
3990 org-latex-to-mathml-convert-command))))
3991 (when (executable-find executable)
3992 (if (string-match
3993 "%j" org-latex-to-mathml-convert-command)
3994 (file-readable-p org-latex-to-mathml-jar-file)
3995 t))))))
3997 (defcustom org-format-latex-header "\\documentclass{article}
3998 \\usepackage[usenames]{color}
3999 \[PACKAGES]
4000 \[DEFAULT-PACKAGES]
4001 \\pagestyle{empty} % do not remove
4002 % The settings below are copied from fullpage.sty
4003 \\setlength{\\textwidth}{\\paperwidth}
4004 \\addtolength{\\textwidth}{-3cm}
4005 \\setlength{\\oddsidemargin}{1.5cm}
4006 \\addtolength{\\oddsidemargin}{-2.54cm}
4007 \\setlength{\\evensidemargin}{\\oddsidemargin}
4008 \\setlength{\\textheight}{\\paperheight}
4009 \\addtolength{\\textheight}{-\\headheight}
4010 \\addtolength{\\textheight}{-\\headsep}
4011 \\addtolength{\\textheight}{-\\footskip}
4012 \\addtolength{\\textheight}{-3cm}
4013 \\setlength{\\topmargin}{1.5cm}
4014 \\addtolength{\\topmargin}{-2.54cm}"
4015 "The document header used for processing LaTeX fragments.
4016 It is imperative that this header make sure that no page number
4017 appears on the page. The package defined in the variables
4018 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4019 will either replace the placeholder \"[PACKAGES]\" in this
4020 header, or they will be appended."
4021 :group 'org-latex
4022 :type 'string)
4024 (defun org-set-packages-alist (var val)
4025 "Set the packages alist and make sure it has 3 elements per entry."
4026 (set var (mapcar (lambda (x)
4027 (if (and (consp x) (= (length x) 2))
4028 (list (car x) (nth 1 x) t)
4030 val)))
4032 (defun org-get-packages-alist (var)
4033 "Get the packages alist and make sure it has 3 elements per entry."
4034 (mapcar (lambda (x)
4035 (if (and (consp x) (= (length x) 2))
4036 (list (car x) (nth 1 x) t)
4038 (default-value var)))
4040 (defcustom org-latex-default-packages-alist
4041 '(("AUTO" "inputenc" t ("pdflatex"))
4042 ("T1" "fontenc" t ("pdflatex"))
4043 ("" "graphicx" t)
4044 ("" "grffile" t)
4045 ("" "longtable" nil)
4046 ("" "wrapfig" nil)
4047 ("" "rotating" nil)
4048 ("normalem" "ulem" t)
4049 ("" "amsmath" t)
4050 ("" "textcomp" t)
4051 ("" "amssymb" t)
4052 ("" "capt-of" nil)
4053 ("" "hyperref" nil))
4054 "Alist of default packages to be inserted in the header.
4056 Change this only if one of the packages here causes an
4057 incompatibility with another package you are using.
4059 The packages in this list are needed by one part or another of
4060 Org mode to function properly:
4062 - inputenc, fontenc: for basic font and character selection
4063 - graphicx: for including images
4064 - grffile: allow periods and spaces in graphics file names
4065 - longtable: For multipage tables
4066 - wrapfig: for figure placement
4067 - rotating: for sideways figures and tables
4068 - ulem: for underline and strike-through
4069 - amsmath: for subscript and superscript and math environments
4070 - textcomp, amssymb: for various symbols used
4071 for interpreting the entities in `org-entities'. You can skip
4072 some of these packages if you don't use any of their symbols.
4073 - capt-of: for captions outside of floats
4074 - hyperref: for cross references
4076 Therefore you should not modify this variable unless you know
4077 what you are doing. The one reason to change it anyway is that
4078 you might be loading some other package that conflicts with one
4079 of the default packages. Each element is either a cell or
4080 a string.
4082 A cell is of the format
4084 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4086 If SNIPPET-FLAG is non-nil, the package also needs to be included
4087 when compiling LaTeX snippets into images for inclusion into
4088 non-LaTeX output. COMPILERS is a list of compilers that should
4089 include the package, see `org-latex-compiler'. If the document
4090 compiler is not in the list, and the list is non-nil, the package
4091 will not be inserted in the final document.
4093 A string will be inserted as-is in the header of the document."
4094 :group 'org-latex
4095 :group 'org-export-latex
4096 :set 'org-set-packages-alist
4097 :get 'org-get-packages-alist
4098 :version "26.1"
4099 :package-version '(Org . "8.3")
4100 :type '(repeat
4101 (choice
4102 (list :tag "options/package pair"
4103 (string :tag "options")
4104 (string :tag "package")
4105 (boolean :tag "Snippet")
4106 (choice
4107 (const :tag "For all compilers" nil)
4108 (repeat :tag "Allowed compiler" string)))
4109 (string :tag "A line of LaTeX"))))
4111 (defcustom org-latex-packages-alist nil
4112 "Alist of packages to be inserted in every LaTeX header.
4114 These will be inserted after `org-latex-default-packages-alist'.
4115 Each element is either a cell or a string.
4117 A cell is of the format:
4119 (\"options\" \"package\" SNIPPET-FLAG)
4121 SNIPPET-FLAG, when non-nil, indicates that this package is also
4122 needed when turning LaTeX snippets into images for inclusion into
4123 non-LaTeX output.
4125 A string will be inserted as-is in the header of the document.
4127 Make sure that you only list packages here which:
4129 - you want in every file;
4130 - do not conflict with the setup in `org-format-latex-header';
4131 - do not conflict with the default packages in
4132 `org-latex-default-packages-alist'."
4133 :group 'org-latex
4134 :group 'org-export-latex
4135 :set 'org-set-packages-alist
4136 :get 'org-get-packages-alist
4137 :type '(repeat
4138 (choice
4139 (list :tag "options/package pair"
4140 (string :tag "options")
4141 (string :tag "package")
4142 (boolean :tag "Snippet"))
4143 (string :tag "A line of LaTeX"))))
4145 (defgroup org-appearance nil
4146 "Settings for Org mode appearance."
4147 :tag "Org Appearance"
4148 :group 'org)
4150 (defcustom org-level-color-stars-only nil
4151 "Non-nil means fontify only the stars in each headline.
4152 When nil, the entire headline is fontified.
4153 Changing it requires restart of `font-lock-mode' to become effective
4154 also in regions already fontified."
4155 :group 'org-appearance
4156 :type 'boolean)
4158 (defcustom org-hide-leading-stars nil
4159 "Non-nil means hide the first N-1 stars in a headline.
4160 This works by using the face `org-hide' for these stars. This
4161 face is white for a light background, and black for a dark
4162 background. You may have to customize the face `org-hide' to
4163 make this work.
4164 Changing it requires restart of `font-lock-mode' to become effective
4165 also in regions already fontified.
4166 You may also set this on a per-file basis by adding one of the following
4167 lines to the buffer:
4169 #+STARTUP: hidestars
4170 #+STARTUP: showstars"
4171 :group 'org-appearance
4172 :type 'boolean)
4174 (defcustom org-hidden-keywords nil
4175 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4176 For example, a value \\='(title) for this list makes the document's title
4177 appear in the buffer without the initial \"#+TITLE:\" part."
4178 :group 'org-appearance
4179 :version "24.1"
4180 :type '(set (const :tag "#+AUTHOR" author)
4181 (const :tag "#+DATE" date)
4182 (const :tag "#+EMAIL" email)
4183 (const :tag "#+TITLE" title)))
4185 (defcustom org-custom-properties nil
4186 "List of properties (as strings) with a special meaning.
4187 The default use of these custom properties is to let the user
4188 hide them with `org-toggle-custom-properties-visibility'."
4189 :group 'org-properties
4190 :group 'org-appearance
4191 :version "24.3"
4192 :type '(repeat (string :tag "Property Name")))
4194 (defcustom org-fontify-done-headline nil
4195 "Non-nil means change the face of a headline if it is marked DONE.
4196 Normally, only the TODO/DONE keyword indicates the state of a headline.
4197 When this is non-nil, the headline after the keyword is set to the
4198 `org-headline-done' as an additional indication."
4199 :group 'org-appearance
4200 :type 'boolean)
4202 (defcustom org-fontify-emphasized-text t
4203 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4204 Changing this variable requires a restart of Emacs to take effect."
4205 :group 'org-appearance
4206 :type 'boolean)
4208 (defcustom org-fontify-whole-heading-line nil
4209 "Non-nil means fontify the whole line for headings.
4210 This is useful when setting a background color for the
4211 org-level-* faces."
4212 :group 'org-appearance
4213 :type 'boolean)
4215 (defcustom org-highlight-latex-and-related nil
4216 "Non-nil means highlight LaTeX related syntax in the buffer.
4217 When non nil, the value should be a list containing any of the
4218 following symbols:
4219 `latex' Highlight LaTeX snippets and environments.
4220 `script' Highlight subscript and superscript.
4221 `entities' Highlight entities."
4222 :group 'org-appearance
4223 :version "24.4"
4224 :package-version '(Org . "8.0")
4225 :type '(choice
4226 (const :tag "No highlighting" nil)
4227 (set :greedy t :tag "Highlight"
4228 (const :tag "LaTeX snippets and environments" latex)
4229 (const :tag "Subscript and superscript" script)
4230 (const :tag "Entities" entities))))
4232 (defcustom org-hide-emphasis-markers nil
4233 "Non-nil mean font-lock should hide the emphasis marker characters."
4234 :group 'org-appearance
4235 :type 'boolean)
4237 (defcustom org-hide-macro-markers nil
4238 "Non-nil mean font-lock should hide the brackets marking macro calls."
4239 :group 'org-appearance
4240 :type 'boolean)
4242 (defcustom org-pretty-entities nil
4243 "Non-nil means show entities as UTF8 characters.
4244 When nil, the \\name form remains in the buffer."
4245 :group 'org-appearance
4246 :version "24.1"
4247 :type 'boolean)
4249 (defcustom org-pretty-entities-include-sub-superscripts t
4250 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4251 :group 'org-appearance
4252 :version "24.1"
4253 :type 'boolean)
4255 (defvar org-emph-re nil
4256 "Regular expression for matching emphasis.
4257 After a match, the match groups contain these elements:
4258 0 The match of the full regular expression, including the characters
4259 before and after the proper match
4260 1 The character before the proper match, or empty at beginning of line
4261 2 The proper match, including the leading and trailing markers
4262 3 The leading marker like * or /, indicating the type of highlighting
4263 4 The text between the emphasis markers, not including the markers
4264 5 The character after the match, empty at the end of a line")
4266 (defvar org-verbatim-re nil
4267 "Regular expression for matching verbatim text.")
4269 (defvar org-emphasis-regexp-components) ; defined just below
4270 (defvar org-emphasis-alist) ; defined just below
4271 (defun org-set-emph-re (var val)
4272 "Set variable and compute the emphasis regular expression."
4273 (set var val)
4274 (when (and (boundp 'org-emphasis-alist)
4275 (boundp 'org-emphasis-regexp-components)
4276 org-emphasis-alist org-emphasis-regexp-components)
4277 (pcase-let*
4278 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4279 (body (if (<= nl 0) body
4280 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4281 (template
4282 (format (concat "\\([%s]\\|^\\)" ;before markers
4283 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4284 "\\([%s]\\|$\\)") ;after markers
4285 pre border border body border post)))
4286 (setq org-emph-re (format template "*/_+"))
4287 (setq org-verbatim-re (format template "=~")))))
4289 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4290 ;; set this option proved cumbersome. See this message/thread:
4291 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4292 (defvar org-emphasis-regexp-components
4293 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4294 "Components used to build the regular expression for emphasis.
4295 This is a list with five entries. Terminology: In an emphasis string
4296 like \" *strong word* \", we call the initial space PREMATCH, the final
4297 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4298 and \"trong wor\" is the body. The different components in this variable
4299 specify what is allowed/forbidden in each part:
4301 pre Chars allowed as prematch. Beginning of line will be allowed too.
4302 post Chars allowed as postmatch. End of line will be allowed too.
4303 border The chars *forbidden* as border characters.
4304 body-regexp A regexp like \".\" to match a body character. Don't use
4305 non-shy groups here, and don't allow newline here.
4306 newline The maximum number of newlines allowed in an emphasis exp.
4308 You need to reload Org or to restart Emacs after setting this.")
4310 (defcustom org-emphasis-alist
4311 '(("*" bold)
4312 ("/" italic)
4313 ("_" underline)
4314 ("=" org-verbatim verbatim)
4315 ("~" org-code verbatim)
4316 ("+" (:strike-through t)))
4317 "Alist of characters and faces to emphasize text.
4318 Text starting and ending with a special character will be emphasized,
4319 for example *bold*, _underlined_ and /italic/. This variable sets the
4320 marker characters and the face to be used by font-lock for highlighting
4321 in Org buffers.
4323 You need to reload Org or to restart Emacs after customizing this."
4324 :group 'org-appearance
4325 :set 'org-set-emph-re
4326 :version "24.4"
4327 :package-version '(Org . "8.0")
4328 :type '(repeat
4329 (list
4330 (string :tag "Marker character")
4331 (choice
4332 (face :tag "Font-lock-face")
4333 (plist :tag "Face property list"))
4334 (option (const verbatim)))))
4336 (defvar org-protecting-blocks '("src" "example" "export")
4337 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4338 This is needed for font-lock setup.")
4340 ;;; Functions and variables from their packages
4341 ;; Declared here to avoid compiler warnings
4342 (defvar mark-active)
4344 ;; Various packages
4345 (declare-function calc-eval "calc" (str &optional separator &rest args))
4346 (declare-function calendar-forward-day "cal-move" (arg))
4347 (declare-function calendar-goto-date "cal-move" (date))
4348 (declare-function calendar-goto-today "cal-move" ())
4349 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4350 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4351 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4352 (declare-function cdlatex-tab "ext:cdlatex" ())
4353 (declare-function dired-get-filename
4354 "dired"
4355 (&optional localp no-error-if-not-filep))
4356 (declare-function iswitchb-read-buffer
4357 "iswitchb"
4358 (prompt &optional
4359 default require-match _predicate start matches-set))
4360 (declare-function org-agenda-change-all-lines
4361 "org-agenda"
4362 (newhead hdmarker &optional fixface just-this))
4363 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4364 "org-agenda"
4365 (&optional end))
4366 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4367 (declare-function org-agenda-format-item
4368 "org-agenda"
4369 (extra txt &optional level category tags dotime
4370 remove-re habitp))
4371 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4372 (declare-function org-agenda-save-markers-for-cut-and-paste
4373 "org-agenda"
4374 (beg end))
4375 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4376 (declare-function org-agenda-skip "org-agenda" ())
4377 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4378 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4379 (declare-function org-indent-mode "org-indent" (&optional arg))
4380 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4381 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4382 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4383 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4384 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4385 (declare-function parse-time-string "parse-time" (string))
4387 (defvar align-mode-rules-list)
4388 (defvar calc-embedded-close-formula)
4389 (defvar calc-embedded-open-formula)
4390 (defvar calc-embedded-open-mode)
4391 (defvar font-lock-unfontify-region-function)
4392 (defvar iswitchb-temp-buflist)
4393 (defvar org-agenda-tags-todo-honor-ignore-options)
4394 (defvar remember-data-file)
4395 (defvar texmathp-why)
4397 ;;;###autoload
4398 (defun turn-on-orgtbl ()
4399 "Unconditionally turn on `orgtbl-mode'."
4400 (require 'org-table)
4401 (orgtbl-mode 1))
4403 (defun org-at-table-p (&optional table-type)
4404 "Non-nil if the cursor is inside an Org table.
4405 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4406 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4407 (or (not (derived-mode-p 'org-mode))
4408 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4409 (and e (or table-type
4410 (eq 'org (org-element-property :type e))))))))
4412 (defun org-at-table.el-p ()
4413 "Non-nil when point is at a table.el table."
4414 (and (org-match-line "[ \t]*[|+]")
4415 (let ((element (org-element-at-point)))
4416 (and (eq (org-element-type element) 'table)
4417 (eq (org-element-property :type element) 'table.el)))))
4419 (defun org-at-table-hline-p ()
4420 "Non-nil when point is inside a hline in a table.
4421 Assume point is already in a table."
4422 (org-match-line org-table-hline-regexp))
4424 (defun org-table-map-tables (function &optional quietly)
4425 "Apply FUNCTION to the start of all tables in the buffer."
4426 (org-with-wide-buffer
4427 (goto-char (point-min))
4428 (while (re-search-forward org-table-any-line-regexp nil t)
4429 (unless quietly
4430 (message "Mapping tables: %d%%"
4431 (floor (* 100.0 (point)) (buffer-size))))
4432 (beginning-of-line 1)
4433 (when (and (looking-at org-table-line-regexp)
4434 ;; Exclude tables in src/example/verbatim/clocktable blocks
4435 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4436 (save-excursion (funcall function))
4437 (or (looking-at org-table-line-regexp)
4438 (forward-char 1)))
4439 (re-search-forward org-table-any-border-regexp nil 1)))
4440 (unless quietly (message "Mapping tables: done")))
4442 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4443 (declare-function org-clock-update-mode-line "org-clock" ())
4444 (declare-function org-resolve-clocks "org-clock"
4445 (&optional also-non-dangling-p prompt last-valid))
4447 (defun org-at-TBLFM-p (&optional pos)
4448 "Non-nil when point (or POS) is in #+TBLFM line."
4449 (save-excursion
4450 (goto-char (or pos (point)))
4451 (beginning-of-line)
4452 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4453 (eq (org-element-type (org-element-at-point)) 'table))))
4455 (defvar org-clock-start-time)
4456 (defvar org-clock-marker (make-marker)
4457 "Marker recording the last clock-in.")
4458 (defvar org-clock-hd-marker (make-marker)
4459 "Marker recording the last clock-in, but the headline position.")
4460 (defvar org-clock-heading ""
4461 "The heading of the current clock entry.")
4462 (defun org-clock-is-active ()
4463 "Return the buffer where the clock is currently running.
4464 Return nil if no clock is running."
4465 (marker-buffer org-clock-marker))
4467 (defun org-check-running-clock ()
4468 "Check if the current buffer contains the running clock.
4469 If yes, offer to stop it and to save the buffer with the changes."
4470 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4471 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4472 (buffer-name))))
4473 (org-clock-out)
4474 (when (y-or-n-p "Save changed buffer?")
4475 (save-buffer))))
4477 (defun org-clocktable-try-shift (dir n)
4478 "Check if this line starts a clock table, if yes, shift the time block."
4479 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4480 (org-clocktable-shift dir n)))
4482 ;;;###autoload
4483 (defun org-clock-persistence-insinuate ()
4484 "Set up hooks for clock persistence."
4485 (require 'org-clock)
4486 (add-hook 'org-mode-hook 'org-clock-load)
4487 (add-hook 'kill-emacs-hook 'org-clock-save))
4489 (defgroup org-archive nil
4490 "Options concerning archiving in Org mode."
4491 :tag "Org Archive"
4492 :group 'org-structure)
4494 (defcustom org-archive-location "%s_archive::"
4495 "The location where subtrees should be archived.
4497 The value of this variable is a string, consisting of two parts,
4498 separated by a double-colon. The first part is a filename and
4499 the second part is a headline.
4501 When the filename is omitted, archiving happens in the same file.
4502 %s in the filename will be replaced by the current file
4503 name (without the directory part). Archiving to a different file
4504 is useful to keep archived entries from contributing to the
4505 Org Agenda.
4507 The archived entries will be filed as subtrees of the specified
4508 headline. When the headline is omitted, the subtrees are simply
4509 filed away at the end of the file, as top-level entries. Also in
4510 the heading you can use %s to represent the file name, this can be
4511 useful when using the same archive for a number of different files.
4513 Here are a few examples:
4514 \"%s_archive::\"
4515 If the current file is Projects.org, archive in file
4516 Projects.org_archive, as top-level trees. This is the default.
4518 \"::* Archived Tasks\"
4519 Archive in the current file, under the top-level headline
4520 \"* Archived Tasks\".
4522 \"~/org/archive.org::\"
4523 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4525 \"~/org/archive.org::* From %s\"
4526 Archive in file ~/org/archive.org (absolute path), under headlines
4527 \"From FILENAME\" where file name is the current file name.
4529 \"~/org/datetree.org::datetree/* Finished Tasks\"
4530 The \"datetree/\" string is special, signifying to archive
4531 items to the datetree. Items are placed in either the CLOSED
4532 date of the item, or the current date if there is no CLOSED date.
4533 The heading will be a subentry to the current date. There doesn't
4534 need to be a heading, but there always needs to be a slash after
4535 datetree. For example, to store archived items directly in the
4536 datetree, use \"~/org/datetree.org::datetree/\".
4538 \"basement::** Finished Tasks\"
4539 Archive in file ./basement (relative path), as level 3 trees
4540 below the level 2 heading \"** Finished Tasks\".
4542 You may set this option on a per-file basis by adding to the buffer a
4543 line like
4545 #+ARCHIVE: basement::** Finished Tasks
4547 You may also define it locally for a subtree by setting an ARCHIVE property
4548 in the entry. If such a property is found in an entry, or anywhere up
4549 the hierarchy, it will be used."
4550 :group 'org-archive
4551 :type 'string)
4553 (defcustom org-agenda-skip-archived-trees t
4554 "Non-nil means the agenda will skip any items located in archived trees.
4555 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4556 variable is no longer recommended, you should leave it at the value t.
4557 Instead, use the key `v' to cycle the archives-mode in the agenda."
4558 :group 'org-archive
4559 :group 'org-agenda-skip
4560 :type 'boolean)
4562 (defcustom org-columns-skip-archived-trees t
4563 "Non-nil means ignore archived trees when creating column view."
4564 :group 'org-archive
4565 :group 'org-properties
4566 :type 'boolean)
4568 (defcustom org-cycle-open-archived-trees nil
4569 "Non-nil means `org-cycle' will open archived trees.
4570 An archived tree is a tree marked with the tag ARCHIVE.
4571 When nil, archived trees will stay folded. You can still open them with
4572 normal outline commands like `show-all', but not with the cycling commands."
4573 :group 'org-archive
4574 :group 'org-cycle
4575 :type 'boolean)
4577 (defcustom org-sparse-tree-open-archived-trees nil
4578 "Non-nil means sparse tree construction shows matches in archived trees.
4579 When nil, matches in these trees are highlighted, but the trees are kept in
4580 collapsed state."
4581 :group 'org-archive
4582 :group 'org-sparse-trees
4583 :type 'boolean)
4585 (defcustom org-sparse-tree-default-date-type nil
4586 "The default date type when building a sparse tree.
4587 When this is nil, a date is a scheduled or a deadline timestamp.
4588 Otherwise, these types are allowed:
4590 all: all timestamps
4591 active: only active timestamps (<...>)
4592 inactive: only inactive timestamps ([...])
4593 scheduled: only scheduled timestamps
4594 deadline: only deadline timestamps"
4595 :type '(choice (const :tag "Scheduled or deadline" nil)
4596 (const :tag "All timestamps" all)
4597 (const :tag "Only active timestamps" active)
4598 (const :tag "Only inactive timestamps" inactive)
4599 (const :tag "Only scheduled timestamps" scheduled)
4600 (const :tag "Only deadline timestamps" deadline)
4601 (const :tag "Only closed timestamps" closed))
4602 :version "26.1"
4603 :package-version '(Org . "8.3")
4604 :group 'org-sparse-trees)
4606 (defun org-cycle-hide-archived-subtrees (state)
4607 "Re-hide all archived subtrees after a visibility state change.
4608 STATE should be one of the symbols listed in the docstring of
4609 `org-cycle-hook'."
4610 (when (and (not org-cycle-open-archived-trees)
4611 (not (memq state '(overview folded))))
4612 (save-excursion
4613 (let* ((globalp (memq state '(contents all)))
4614 (beg (if globalp (point-min) (point)))
4615 (end (if globalp (point-max) (org-end-of-subtree t))))
4616 (org-hide-archived-subtrees beg end)
4617 (goto-char beg)
4618 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4619 (message "%s" (substitute-command-keys
4620 "Subtree is archived and stays closed. Use \
4621 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4623 (defun org-force-cycle-archived ()
4624 "Cycle subtree even if it is archived."
4625 (interactive)
4626 (setq this-command 'org-cycle)
4627 (let ((org-cycle-open-archived-trees t))
4628 (call-interactively 'org-cycle)))
4630 (defun org-hide-archived-subtrees (beg end)
4631 "Re-hide all archived subtrees after a visibility state change."
4632 (org-with-wide-buffer
4633 (let ((case-fold-search nil)
4634 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4635 (goto-char beg)
4636 ;; Include headline point is currently on.
4637 (beginning-of-line)
4638 (while (and (< (point) end) (re-search-forward re end t))
4639 (when (member org-archive-tag (org-get-tags nil t))
4640 (org-flag-subtree t)
4641 (org-end-of-subtree t))))))
4643 (defun org-flag-subtree (flag)
4644 (save-excursion
4645 (org-back-to-heading t)
4646 (org-flag-region (line-end-position)
4647 (progn (org-end-of-subtree t) (point))
4648 flag
4649 'outline)))
4651 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4653 ;; Declare Column View Code
4655 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4656 (declare-function org-columns-compute "org-colview" (property))
4658 ;; Declare ID code
4660 (declare-function org-id-store-link "org-id")
4661 (declare-function org-id-locations-load "org-id")
4662 (declare-function org-id-locations-save "org-id")
4663 (defvar org-id-track-globally)
4665 ;;; Variables for pre-computed regular expressions, all buffer local
4667 (defvar-local org-todo-regexp nil
4668 "Matches any of the TODO state keywords.
4669 Since TODO keywords are case-sensitive, `case-fold-search' is
4670 expected to be bound to nil when matching against this regexp.")
4672 (defvar-local org-not-done-regexp nil
4673 "Matches any of the TODO state keywords except the last one.
4674 Since TODO keywords are case-sensitive, `case-fold-search' is
4675 expected to be bound to nil when matching against this regexp.")
4677 (defvar-local org-not-done-heading-regexp nil
4678 "Matches a TODO headline that is not done.
4679 Since TODO keywords are case-sensitive, `case-fold-search' is
4680 expected to be bound to nil when matching against this regexp.")
4682 (defvar-local org-todo-line-regexp nil
4683 "Matches a headline and puts TODO state into group 2 if present.
4684 Since TODO keywords are case-sensitive, `case-fold-search' is
4685 expected to be bound to nil when matching against this regexp.")
4687 (defvar-local org-complex-heading-regexp nil
4688 "Matches a headline and puts everything into groups:
4690 group 1: Stars
4691 group 2: The TODO keyword, maybe
4692 group 3: Priority cookie
4693 group 4: True headline
4694 group 5: Tags
4696 Since TODO keywords are case-sensitive, `case-fold-search' is
4697 expected to be bound to nil when matching against this regexp.")
4699 (defvar-local org-complex-heading-regexp-format nil
4700 "Printf format to make regexp to match an exact headline.
4701 This regexp will match the headline of any node which has the
4702 exact headline text that is put into the format, but may have any
4703 TODO state, priority and tags.")
4705 (defvar-local org-todo-line-tags-regexp nil
4706 "Matches a headline and puts TODO state into group 2 if present.
4707 Also put tags into group 4 if tags are present.")
4709 (defconst org-plain-time-of-day-regexp
4710 (concat
4711 "\\(\\<[012]?[0-9]"
4712 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4713 "\\(--?"
4714 "\\(\\<[012]?[0-9]"
4715 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4716 "\\)?")
4717 "Regular expression to match a plain time or time range.
4718 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4719 groups carry important information:
4720 0 the full match
4721 1 the first time, range or not
4722 8 the second time, if it is a range.")
4724 (defconst org-plain-time-extension-regexp
4725 (concat
4726 "\\(\\<[012]?[0-9]"
4727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4728 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4729 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4730 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4731 groups carry important information:
4732 0 the full match
4733 7 hours of duration
4734 9 minutes of duration")
4736 (defconst org-stamp-time-of-day-regexp
4737 (concat
4738 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4739 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4740 "\\(--?"
4741 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4742 "Regular expression to match a timestamp time or time range.
4743 After a match, the following groups carry important information:
4744 0 the full match
4745 1 date plus weekday, for back referencing to make sure both times are on the same day
4746 2 the first time, range or not
4747 4 the second time, if it is a range.")
4749 (defconst org-startup-options
4750 '(("fold" org-startup-folded t)
4751 ("overview" org-startup-folded t)
4752 ("nofold" org-startup-folded nil)
4753 ("showall" org-startup-folded nil)
4754 ("showeverything" org-startup-folded showeverything)
4755 ("content" org-startup-folded content)
4756 ("indent" org-startup-indented t)
4757 ("noindent" org-startup-indented nil)
4758 ("hidestars" org-hide-leading-stars t)
4759 ("showstars" org-hide-leading-stars nil)
4760 ("odd" org-odd-levels-only t)
4761 ("oddeven" org-odd-levels-only nil)
4762 ("align" org-startup-align-all-tables t)
4763 ("noalign" org-startup-align-all-tables nil)
4764 ("shrink" org-startup-shrink-all-tables t)
4765 ("inlineimages" org-startup-with-inline-images t)
4766 ("noinlineimages" org-startup-with-inline-images nil)
4767 ("latexpreview" org-startup-with-latex-preview t)
4768 ("nolatexpreview" org-startup-with-latex-preview nil)
4769 ("customtime" org-display-custom-times t)
4770 ("logdone" org-log-done time)
4771 ("lognotedone" org-log-done note)
4772 ("nologdone" org-log-done nil)
4773 ("lognoteclock-out" org-log-note-clock-out t)
4774 ("nolognoteclock-out" org-log-note-clock-out nil)
4775 ("logrepeat" org-log-repeat state)
4776 ("lognoterepeat" org-log-repeat note)
4777 ("logdrawer" org-log-into-drawer t)
4778 ("nologdrawer" org-log-into-drawer nil)
4779 ("logstatesreversed" org-log-states-order-reversed t)
4780 ("nologstatesreversed" org-log-states-order-reversed nil)
4781 ("nologrepeat" org-log-repeat nil)
4782 ("logreschedule" org-log-reschedule time)
4783 ("lognotereschedule" org-log-reschedule note)
4784 ("nologreschedule" org-log-reschedule nil)
4785 ("logredeadline" org-log-redeadline time)
4786 ("lognoteredeadline" org-log-redeadline note)
4787 ("nologredeadline" org-log-redeadline nil)
4788 ("logrefile" org-log-refile time)
4789 ("lognoterefile" org-log-refile note)
4790 ("nologrefile" org-log-refile nil)
4791 ("fninline" org-footnote-define-inline t)
4792 ("nofninline" org-footnote-define-inline nil)
4793 ("fnlocal" org-footnote-section nil)
4794 ("fnauto" org-footnote-auto-label t)
4795 ("fnprompt" org-footnote-auto-label nil)
4796 ("fnconfirm" org-footnote-auto-label confirm)
4797 ("fnplain" org-footnote-auto-label plain)
4798 ("fnadjust" org-footnote-auto-adjust t)
4799 ("nofnadjust" org-footnote-auto-adjust nil)
4800 ("constcgs" constants-unit-system cgs)
4801 ("constSI" constants-unit-system SI)
4802 ("noptag" org-tag-persistent-alist nil)
4803 ("hideblocks" org-hide-block-startup t)
4804 ("nohideblocks" org-hide-block-startup nil)
4805 ("beamer" org-startup-with-beamer-mode t)
4806 ("entitiespretty" org-pretty-entities t)
4807 ("entitiesplain" org-pretty-entities nil))
4808 "Variable associated with STARTUP options for Org.
4809 Each element is a list of three items: the startup options (as written
4810 in the #+STARTUP line), the corresponding variable, and the value to set
4811 this variable to if the option is found. An optional forth element PUSH
4812 means to push this value onto the list in the variable.")
4814 (defcustom org-group-tags t
4815 "When non-nil (the default), use group tags.
4816 This can be turned on/off through `org-toggle-tags-groups'."
4817 :group 'org-tags
4818 :group 'org-startup
4819 :type 'boolean)
4821 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4823 (defun org-toggle-tags-groups ()
4824 "Toggle support for group tags.
4825 Support for group tags is controlled by the option
4826 `org-group-tags', which is non-nil by default."
4827 (interactive)
4828 (setq org-group-tags (not org-group-tags))
4829 (cond ((and (derived-mode-p 'org-agenda-mode)
4830 org-group-tags)
4831 (org-agenda-redo))
4832 ((derived-mode-p 'org-mode)
4833 (let ((org-inhibit-startup t)) (org-mode))))
4834 (message "Groups tags support has been turned %s"
4835 (if org-group-tags "on" "off")))
4837 (defun org--tag-add-to-alist (alist1 alist2)
4838 "Merge tags from ALIST1 into ALIST2.
4840 Duplicates tags outside a group are removed. Keywords and order
4841 are preserved.
4843 The function assumes ALIST1 and ALIST2 are proper tag alists.
4844 See `org-tag-alist' for their structure."
4845 (cond
4846 ((null alist2) alist1)
4847 ((null alist1) alist2)
4849 (let ((to-add nil)
4850 (group-flag nil))
4851 (dolist (tag-pair alist1)
4852 (pcase tag-pair
4853 (`(,(or :startgrouptag :startgroup))
4854 (setq group-flag t)
4855 (push tag-pair to-add))
4856 (`(,(or :endgrouptag :endgroup))
4857 (setq group-flag nil)
4858 (push tag-pair to-add))
4859 (`(,(or :grouptags :newline))
4860 (push tag-pair to-add))
4861 (`(,tag . ,_)
4862 ;; Remove duplicates from ALIST1, unless they are in
4863 ;; a group. Indeed, it makes sense to have a tag appear in
4864 ;; multiple groups.
4865 (when (or group-flag (not (assoc tag alist2)))
4866 (push tag-pair to-add)))
4867 (_ (error "Invalid association in tag alist: %S" tag-pair))))
4868 ;; Preserve order of ALIST1.
4869 (append (nreverse to-add) alist2)))))
4871 (defun org-set-regexps-and-options (&optional tags-only)
4872 "Precompute regular expressions used in the current buffer.
4873 When optional argument TAGS-ONLY is non-nil, only compute tags
4874 related expressions."
4875 (when (derived-mode-p 'org-mode)
4876 (let ((alist (org--setup-collect-keywords
4877 (org-make-options-regexp
4878 (append '("FILETAGS" "TAGS" "SETUPFILE")
4879 (and (not tags-only)
4880 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4881 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4882 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4883 ;; Startup options. Get this early since it does change
4884 ;; behavior for other options (e.g., tags).
4885 (let ((startup (cdr (assq 'startup alist))))
4886 (dolist (option startup)
4887 (let ((entry (assoc-string option org-startup-options t)))
4888 (when entry
4889 (let ((var (nth 1 entry))
4890 (val (nth 2 entry)))
4891 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4892 (unless (listp (symbol-value var))
4893 (set (make-local-variable var) nil))
4894 (add-to-list var val)))))))
4895 (setq-local org-file-tags
4896 (mapcar #'org-add-prop-inherited
4897 (cdr (assq 'filetags alist))))
4898 (setq org-current-tag-alist
4899 (org--tag-add-to-alist
4900 org-tag-persistent-alist
4901 (let ((tags (cdr (assq 'tags alist))))
4902 (if tags (org-tag-string-to-alist tags)
4903 org-tag-alist))))
4904 (setq org-tag-groups-alist
4905 (org-tag-alist-to-groups org-current-tag-alist))
4906 (unless tags-only
4907 ;; File properties.
4908 (setq-local org-file-properties (cdr (assq 'property alist)))
4909 ;; Archive location.
4910 (let ((archive (cdr (assq 'archive alist))))
4911 (when archive (setq-local org-archive-location archive)))
4912 ;; Category.
4913 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4914 (when cat
4915 (setq-local org-category (intern cat))
4916 (setq-local org-file-properties
4917 (org--update-property-plist
4918 "CATEGORY" cat org-file-properties))))
4919 ;; Columns.
4920 (let ((column (cdr (assq 'columns alist))))
4921 (when column (setq-local org-columns-default-format column)))
4922 ;; Constants.
4923 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4924 ;; Link abbreviations.
4925 (let ((links (cdr (assq 'link alist))))
4926 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4927 ;; Priorities.
4928 (let ((priorities (cdr (assq 'priorities alist))))
4929 (when priorities
4930 (setq-local org-highest-priority (nth 0 priorities))
4931 (setq-local org-lowest-priority (nth 1 priorities))
4932 (setq-local org-default-priority (nth 2 priorities))))
4933 ;; Scripts.
4934 (let ((scripts (assq 'scripts alist)))
4935 (when scripts
4936 (setq-local org-use-sub-superscripts (cdr scripts))))
4937 ;; TODO keywords.
4938 (setq-local org-todo-kwd-alist nil)
4939 (setq-local org-todo-key-alist nil)
4940 (setq-local org-todo-key-trigger nil)
4941 (setq-local org-todo-keywords-1 nil)
4942 (setq-local org-done-keywords nil)
4943 (setq-local org-todo-heads nil)
4944 (setq-local org-todo-sets nil)
4945 (setq-local org-todo-log-states nil)
4946 (let ((todo-sequences
4947 (or (nreverse (cdr (assq 'todo alist)))
4948 (let ((d (default-value 'org-todo-keywords)))
4949 (if (not (stringp (car d))) d
4950 ;; XXX: Backward compatibility code.
4951 (list (cons org-todo-interpretation d)))))))
4952 (dolist (sequence todo-sequences)
4953 (let* ((sequence (or (run-hook-with-args-until-success
4954 'org-todo-setup-filter-hook sequence)
4955 sequence))
4956 (sequence-type (car sequence))
4957 (keywords (cdr sequence))
4958 (sep (member "|" keywords))
4959 names alist)
4960 (dolist (k (remove "|" keywords))
4961 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4963 (error "Invalid TODO keyword %s" k))
4964 (let ((name (match-string 1 k))
4965 (key (match-string 2 k))
4966 (log (org-extract-log-state-settings k)))
4967 (push name names)
4968 (push (cons name (and key (string-to-char key))) alist)
4969 (when log (push log org-todo-log-states))))
4970 (let* ((names (nreverse names))
4971 (done (if sep (org-remove-keyword-keys (cdr sep))
4972 (last names)))
4973 (head (car names))
4974 (tail (list sequence-type head (car done) (org-last done))))
4975 (add-to-list 'org-todo-heads head 'append)
4976 (push names org-todo-sets)
4977 (setq org-done-keywords (append org-done-keywords done nil))
4978 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4979 (setq org-todo-key-alist
4980 (append org-todo-key-alist
4981 (and alist
4982 (append '((:startgroup))
4983 (nreverse alist)
4984 '((:endgroup))))))
4985 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4986 (setq org-todo-sets (nreverse org-todo-sets)
4987 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4988 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4989 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4990 ;; Compute the regular expressions and other local variables.
4991 ;; Using `org-outline-regexp-bol' would complicate them much,
4992 ;; because of the fixed white space at the end of that string.
4993 (unless org-done-keywords
4994 (setq org-done-keywords
4995 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4996 (setq org-not-done-keywords
4997 (org-delete-all org-done-keywords
4998 (copy-sequence org-todo-keywords-1))
4999 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5000 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5001 org-not-done-heading-regexp
5002 (format org-heading-keyword-regexp-format org-not-done-regexp)
5003 org-todo-line-regexp
5004 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5005 org-complex-heading-regexp
5006 (concat "^\\(\\*+\\)"
5007 "\\(?: +" org-todo-regexp "\\)?"
5008 "\\(?: +\\(\\[#.\\]\\)\\)?"
5009 "\\(?: +\\(.*?\\)\\)??"
5010 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5011 "[ \t]*$")
5012 org-complex-heading-regexp-format
5013 (concat "^\\(\\*+\\)"
5014 "\\(?: +" org-todo-regexp "\\)?"
5015 "\\(?: +\\(\\[#.\\]\\)\\)?"
5016 "\\(?: +"
5017 ;; Stats cookies can be stuck to body.
5018 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5019 "\\(%s\\)"
5020 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5021 "\\)"
5022 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5023 "[ \t]*$")
5024 org-todo-line-tags-regexp
5025 (concat "^\\(\\*+\\)"
5026 "\\(?: +" org-todo-regexp "\\)?"
5027 "\\(?: +\\(.*?\\)\\)??"
5028 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5029 "[ \t]*$"))
5030 (org-compute-latex-and-related-regexp)))))
5032 (defun org--setup-collect-keywords (regexp &optional files alist)
5033 "Return setup keywords values as an alist.
5035 REGEXP matches a subset of setup keywords. FILES is a list of
5036 file names already visited. It is used to avoid circular setup
5037 files. ALIST, when non-nil, is the alist computed so far.
5039 Return value contains the following keys: `archive', `category',
5040 `columns', `constants', `filetags', `link', `priorities',
5041 `property', `scripts', `startup', `tags' and `todo'."
5042 (org-with-wide-buffer
5043 (goto-char (point-min))
5044 (let ((case-fold-search t))
5045 (while (re-search-forward regexp nil t)
5046 (let ((element (org-element-at-point)))
5047 (when (eq (org-element-type element) 'keyword)
5048 (let ((key (org-element-property :key element))
5049 (value (org-element-property :value element)))
5050 (cond
5051 ((equal key "ARCHIVE")
5052 (when (org-string-nw-p value)
5053 (push (cons 'archive value) alist)))
5054 ((equal key "CATEGORY") (push (cons 'category value) alist))
5055 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5056 ((equal key "CONSTANTS")
5057 (let* ((constants (assq 'constants alist))
5058 (store (cdr constants)))
5059 (dolist (pair (split-string value))
5060 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5061 pair)
5062 (let* ((name (match-string 1 pair))
5063 (value (match-string 2 pair))
5064 (old (assoc name store)))
5065 (if old (setcdr old value)
5066 (push (cons name value) store)))))
5067 (if constants (setcdr constants store)
5068 (push (cons 'constants store) alist))))
5069 ((equal key "FILETAGS")
5070 (when (org-string-nw-p value)
5071 (let ((old (assq 'filetags alist))
5072 (new (apply #'nconc
5073 (mapcar (lambda (x) (org-split-string x ":"))
5074 (split-string value)))))
5075 (if old (setcdr old (append new (cdr old)))
5076 (push (cons 'filetags new) alist)))))
5077 ((equal key "LINK")
5078 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5079 (let ((links (assq 'link alist))
5080 (pair (cons (match-string-no-properties 1 value)
5081 (match-string-no-properties 2 value))))
5082 (if links (push pair (cdr links))
5083 (push (list 'link pair) alist)))))
5084 ((equal key "OPTIONS")
5085 (when (and (org-string-nw-p value)
5086 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5087 (push (cons 'scripts (read (match-string 1 value))) alist)))
5088 ((equal key "PRIORITIES")
5089 (push (cons 'priorities
5090 (let ((prio (split-string value)))
5091 (if (< (length prio) 3) '(?A ?C ?B)
5092 (mapcar #'string-to-char prio))))
5093 alist))
5094 ((equal key "PROPERTY")
5095 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5096 (let* ((property (assq 'property alist))
5097 (value (org--update-property-plist
5098 (match-string-no-properties 1 value)
5099 (match-string-no-properties 2 value)
5100 (cdr property))))
5101 (if property (setcdr property value)
5102 (push (cons 'property value) alist)))))
5103 ((equal key "STARTUP")
5104 (let ((startup (assq 'startup alist)))
5105 (if startup
5106 (setcdr startup
5107 (append (cdr startup) (split-string value)))
5108 (push (cons 'startup (split-string value)) alist))))
5109 ((equal key "TAGS")
5110 (let ((tag-cell (assq 'tags alist)))
5111 (if tag-cell
5112 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5113 (push (cons 'tags value) alist))))
5114 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5115 (let ((todo (assq 'todo alist))
5116 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5117 (split-string value))))
5118 (if todo (push value (cdr todo))
5119 (push (list 'todo value) alist))))
5120 ((equal key "SETUPFILE")
5121 (unless buffer-read-only ; Do not check in Gnus messages.
5122 (let ((f (and (org-string-nw-p value)
5123 (expand-file-name
5124 (org-unbracket-string "\"" "\"" value)))))
5125 (when (and f (file-readable-p f) (not (member f files)))
5126 (with-temp-buffer
5127 (setq default-directory (file-name-directory f))
5128 (insert-file-contents f)
5129 (setq alist
5130 ;; Fake Org mode to benefit from cache
5131 ;; without recurring needlessly.
5132 (let ((major-mode 'org-mode))
5133 (org--setup-collect-keywords
5134 regexp (cons f files) alist)))))))))))))))
5135 alist)
5137 (defun org-tag-string-to-alist (s)
5138 "Return tag alist associated to string S.
5139 S is a value for TAGS keyword or produced with
5140 `org-tag-alist-to-string'. Return value is an alist suitable for
5141 `org-tag-alist' or `org-tag-persistent-alist'."
5142 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5143 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5144 "\\(?:(\\(.\\))\\)?\\'"))
5145 alist group-flag)
5146 (dolist (tokens lines (cdr (nreverse alist)))
5147 (push '(:newline) alist)
5148 (while tokens
5149 (let ((token (pop tokens)))
5150 (pcase token
5151 ("{"
5152 (push '(:startgroup) alist)
5153 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5154 ("}"
5155 (push '(:endgroup) alist)
5156 (setq group-flag nil))
5157 ("["
5158 (push '(:startgrouptag) alist)
5159 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5160 ("]"
5161 (push '(:endgrouptag) alist)
5162 (setq group-flag nil))
5163 (":"
5164 (push '(:grouptags) alist))
5165 ((guard (string-match tag-re token))
5166 (let ((tag (match-string 1 token))
5167 (key (and (match-beginning 2)
5168 (string-to-char (match-string 2 token)))))
5169 ;; Push all tags in groups, no matter if they already
5170 ;; appear somewhere else in the list.
5171 (when (or group-flag (not (assoc tag alist)))
5172 (push (cons tag key) alist))))))))))
5174 (defun org-tag-alist-to-string (alist &optional skip-key)
5175 "Return tag string associated to ALIST.
5177 ALIST is an alist, as defined in `org-tag-alist' or
5178 `org-tag-persistent-alist', or produced with
5179 `org-tag-string-to-alist'.
5181 Return value is a string suitable as a value for \"TAGS\"
5182 keyword.
5184 When optional argument SKIP-KEY is non-nil, skip selection keys
5185 next to tags."
5186 (mapconcat (lambda (token)
5187 (pcase token
5188 (`(:startgroup) "{")
5189 (`(:endgroup) "}")
5190 (`(:startgrouptag) "[")
5191 (`(:endgrouptag) "]")
5192 (`(:grouptags) ":")
5193 (`(:newline) "\\n")
5194 ((and
5195 (guard (not skip-key))
5196 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5197 (format "%s(%c)" tag key))
5198 (`(,(and tag (pred stringp)) . ,_) tag)
5199 (_ (user-error "Invalid tag token: %S" token))))
5200 alist
5201 " "))
5203 (defun org-tag-alist-to-groups (alist)
5204 "Return group alist from tag ALIST.
5205 ALIST is an alist, as defined in `org-tag-alist' or
5206 `org-tag-persistent-alist', or produced with
5207 `org-tag-string-to-alist'. Return value is an alist following
5208 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5209 a string, summarizing TAGS, as a list of strings."
5210 (let (groups group-status current-group)
5211 (dolist (token alist (nreverse groups))
5212 (pcase token
5213 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5214 (`(,(or :endgroup :endgrouptag))
5215 (when (eq group-status 'append)
5216 (push (nreverse current-group) groups))
5217 (setq group-status nil current-group nil))
5218 (`(:grouptags) (setq group-status 'append))
5219 ((and `(,tag . ,_) (guard group-status))
5220 (if (eq group-status 'append) (push tag current-group)
5221 (setq current-group (list tag))))
5222 (_ nil)))))
5224 (defvar org--file-cache (make-hash-table :test #'equal)
5225 "Hash table to store contents of files referenced via a URL.
5226 This is the cache of file URLs read using `org-file-contents'.")
5228 (defun org-reset-file-cache ()
5229 "Reset the cache of files downloaded by `org-file-contents'."
5230 (clrhash org--file-cache))
5232 (defun org-file-url-p (file)
5233 "Non-nil if FILE is a URL."
5234 (require 'ffap)
5235 (string-match-p ffap-url-regexp file))
5237 (defun org-file-contents (file &optional noerror nocache)
5238 "Return the contents of FILE, as a string.
5240 FILE can be a file name or URL.
5242 If FILE is a URL, download the contents. If the URL contents are
5243 already cached in the `org--file-cache' hash table, the download step
5244 is skipped.
5246 If NOERROR is non-nil, ignore the error when unable to read the FILE
5247 from file or URL.
5249 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5250 is available. This option applies only if FILE is a URL."
5251 (let* ((is-url (org-file-url-p file))
5252 (cache (and is-url
5253 (not nocache)
5254 (gethash file org--file-cache))))
5255 (cond
5256 (cache)
5257 (is-url
5258 (with-current-buffer (url-retrieve-synchronously file)
5259 (goto-char (point-min))
5260 ;; Move point to after the url-retrieve header.
5261 (search-forward "\n\n" nil :move)
5262 ;; Search for the success code only in the url-retrieve header.
5263 (if (save-excursion
5264 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5265 ;; Update the cache `org--file-cache' and return contents.
5266 (puthash file
5267 (buffer-substring-no-properties (point) (point-max))
5268 org--file-cache)
5269 (funcall (if noerror #'message #'user-error)
5270 "Unable to fetch file from %S"
5271 file))))
5273 (with-temp-buffer
5274 (condition-case nil
5275 (progn
5276 (insert-file-contents file)
5277 (buffer-string))
5278 (file-error
5279 (funcall (if noerror #'message #'user-error)
5280 "Unable to read file %S"
5281 file))))))))
5283 (defun org-extract-log-state-settings (x)
5284 "Extract the log state setting from a TODO keyword string.
5285 This will extract info from a string like \"WAIT(w@/!)\"."
5286 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5287 (let ((kw (match-string 1 x))
5288 (log1 (and (match-end 3) (match-string 3 x)))
5289 (log2 (and (match-end 4) (match-string 4 x))))
5290 (and (or log1 log2)
5291 (list kw
5292 (and log1 (if (equal log1 "!") 'time 'note))
5293 (and log2 (if (equal log2 "!") 'time 'note)))))))
5295 (defun org-remove-keyword-keys (list)
5296 "Remove a pair of parenthesis at the end of each string in LIST."
5297 (mapcar (lambda (x)
5298 (if (string-match "(.*)$" x)
5299 (substring x 0 (match-beginning 0))
5301 list))
5303 (defun org-assign-fast-keys (alist)
5304 "Assign fast keys to a keyword-key alist.
5305 Respect keys that are already there."
5306 (let (new e (alt ?0))
5307 (while (setq e (pop alist))
5308 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5309 (cdr e)) ;; Key already assigned.
5310 (push e new)
5311 (let ((clist (string-to-list (downcase (car e))))
5312 (used (append new alist)))
5313 (when (= (car clist) ?@)
5314 (pop clist))
5315 (while (and clist (rassoc (car clist) used))
5316 (pop clist))
5317 (unless clist
5318 (while (rassoc alt used)
5319 (cl-incf alt)))
5320 (push (cons (car e) (or (car clist) alt)) new))))
5321 (nreverse new)))
5323 ;;; Some variables used in various places
5325 (defvar org-window-configuration nil
5326 "Used in various places to store a window configuration.")
5327 (defvar org-selected-window nil
5328 "Used in various places to store a window configuration.")
5329 (defvar org-finish-function nil
5330 "Function to be called when `C-c C-c' is used.
5331 This is for getting out of special buffers like capture.")
5332 (defvar org-last-state)
5334 ;; Defined somewhere in this file, but used before definition.
5335 (defvar org-entities) ;; defined in org-entities.el
5336 (defvar org-struct-menu)
5337 (defvar org-org-menu)
5338 (defvar org-tbl-menu)
5340 ;;;; Define the Org mode
5342 ;; We use a before-change function to check if a table might need
5343 ;; an update.
5344 (defvar org-table-may-need-update t
5345 "Indicates that a table might need an update.
5346 This variable is set by `org-before-change-function'.
5347 `org-table-align' sets it back to nil.")
5348 (defun org-before-change-function (_beg _end)
5349 "Every change indicates that a table might need an update."
5350 (setq org-table-may-need-update t))
5351 (defvar org-mode-map)
5352 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5353 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5354 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5355 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5356 (defvar org-table-buffer-is-an nil)
5358 (defvar bidi-paragraph-direction)
5359 (defvar buffer-face-mode-face)
5361 (require 'outline)
5363 ;; Other stuff we need.
5364 (require 'time-date)
5365 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5366 (require 'easymenu)
5367 (autoload 'easy-menu-add "easymenu")
5368 (require 'overlay)
5370 ;; (require 'org-macs) moved higher up in the file before it is first used
5371 (require 'org-entities)
5372 ;; (require 'org-compat) moved higher up in the file before it is first used
5373 (require 'org-faces)
5374 (require 'org-list)
5375 (require 'org-pcomplete)
5376 (require 'org-src)
5377 (require 'org-footnote)
5378 (require 'org-macro)
5380 ;; babel
5381 (require 'ob)
5383 ;;;###autoload
5384 (define-derived-mode org-mode outline-mode "Org"
5385 "Outline-based notes management and organizer, alias
5386 \"Carsten's outline-mode for keeping track of everything.\"
5388 Org mode develops organizational tasks around a NOTES file which
5389 contains information about projects as plain text. Org mode is
5390 implemented on top of Outline mode, which is ideal to keep the content
5391 of large files well structured. It supports ToDo items, deadlines and
5392 time stamps, which magically appear in the diary listing of the Emacs
5393 calendar. Tables are easily created with a built-in table editor.
5394 Plain text URL-like links connect to websites, emails (VM), Usenet
5395 messages (Gnus), BBDB entries, and any files related to the project.
5396 For printing and sharing of notes, an Org file (or a part of it)
5397 can be exported as a structured ASCII or HTML file.
5399 The following commands are available:
5401 \\{org-mode-map}"
5403 ;; Get rid of Outline menus, they are not needed
5404 ;; Need to do this here because define-derived-mode sets up
5405 ;; the keymap so late. Still, it is a waste to call this each time
5406 ;; we switch another buffer into Org mode.
5407 (define-key org-mode-map [menu-bar headings] 'undefined)
5408 (define-key org-mode-map [menu-bar hide] 'undefined)
5409 (define-key org-mode-map [menu-bar show] 'undefined)
5411 (org-load-modules-maybe)
5412 (org-install-agenda-files-menu)
5413 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5414 (add-to-invisibility-spec '(org-hide-block . t))
5415 (add-to-invisibility-spec '(org-hide-drawer . t))
5416 (setq-local outline-regexp org-outline-regexp)
5417 (setq-local outline-level 'org-outline-level)
5418 (setq bidi-paragraph-direction 'left-to-right)
5419 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5420 (unless org-display-table
5421 (setq org-display-table (make-display-table)))
5422 (set-display-table-slot
5423 org-display-table 4
5424 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5425 org-ellipsis)))
5426 (setq buffer-display-table org-display-table))
5427 (org-set-regexps-and-options)
5428 (org-set-font-lock-defaults)
5429 (when (and org-tag-faces (not org-tags-special-faces-re))
5430 ;; tag faces set outside customize.... force initialization.
5431 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5432 ;; Calc embedded
5433 (setq-local calc-embedded-open-mode "# ")
5434 ;; Modify a few syntax entries
5435 (modify-syntax-entry ?\" "\"")
5436 (modify-syntax-entry ?\\ "_")
5437 (modify-syntax-entry ?~ "_")
5438 (modify-syntax-entry ?< "(>")
5439 (modify-syntax-entry ?> ")<")
5440 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5441 ;; Activate before-change-function
5442 (setq-local org-table-may-need-update t)
5443 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5444 ;; Check for running clock before killing a buffer
5445 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5446 ;; Initialize macros templates.
5447 (org-macro-initialize-templates)
5448 ;; Initialize radio targets.
5449 (org-update-radio-target-regexp)
5450 ;; Indentation.
5451 (setq-local indent-line-function 'org-indent-line)
5452 (setq-local indent-region-function 'org-indent-region)
5453 ;; Filling and auto-filling.
5454 (org-setup-filling)
5455 ;; Comments.
5456 (org-setup-comments-handling)
5457 ;; Initialize cache.
5458 (org-element-cache-reset)
5459 ;; Beginning/end of defun
5460 (setq-local beginning-of-defun-function 'org-backward-element)
5461 (setq-local end-of-defun-function
5462 (lambda ()
5463 (if (not (org-at-heading-p))
5464 (org-forward-element)
5465 (org-forward-element)
5466 (forward-char -1))))
5467 ;; Next error for sparse trees
5468 (setq-local next-error-function 'org-occur-next-match)
5469 ;; Make sure dependence stuff works reliably, even for users who set it
5470 ;; too late :-(
5471 (if org-enforce-todo-dependencies
5472 (add-hook 'org-blocker-hook
5473 'org-block-todo-from-children-or-siblings-or-parent)
5474 (remove-hook 'org-blocker-hook
5475 'org-block-todo-from-children-or-siblings-or-parent))
5476 (if org-enforce-todo-checkbox-dependencies
5477 (add-hook 'org-blocker-hook
5478 'org-block-todo-from-checkboxes)
5479 (remove-hook 'org-blocker-hook
5480 'org-block-todo-from-checkboxes))
5482 ;; Align options lines
5483 (setq-local
5484 align-mode-rules-list
5485 '((org-in-buffer-settings
5486 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5487 (modes . '(org-mode)))))
5489 ;; Imenu
5490 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5492 ;; Make isearch reveal context
5493 (setq-local outline-isearch-open-invisible-function
5494 (lambda (&rest _) (org-show-context 'isearch)))
5496 ;; Setup the pcomplete hooks
5497 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5498 (setq-local pcomplete-command-name-function 'org-command-at-point)
5499 (setq-local pcomplete-default-completion-function 'ignore)
5500 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5501 (setq-local pcomplete-termination-string "")
5502 (setq-local buffer-face-mode-face 'org-default)
5504 ;; If empty file that did not turn on Org mode automatically, make
5505 ;; it to.
5506 (when (and org-insert-mode-line-in-empty-file
5507 (called-interactively-p 'any)
5508 (= (point-min) (point-max)))
5509 (insert "# -*- mode: org -*-\n\n"))
5510 (unless org-inhibit-startup
5511 (org-unmodified
5512 (when org-startup-with-beamer-mode (org-beamer-mode))
5513 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5514 (org-table-map-tables
5515 (cond ((and org-startup-align-all-tables
5516 org-startup-shrink-all-tables)
5517 (lambda () (org-table-align) (org-table-shrink)))
5518 (org-startup-align-all-tables #'org-table-align)
5519 (t #'org-table-shrink))
5521 (when org-startup-with-inline-images (org-display-inline-images))
5522 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5523 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5524 (when org-startup-truncated (setq truncate-lines t))
5525 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5526 (org-refresh-effort-properties)))
5527 ;; Try to set `org-hide' face correctly.
5528 (let ((foreground (org-find-invisible-foreground)))
5529 (when foreground
5530 (set-face-foreground 'org-hide foreground))))
5532 ;; Update `customize-package-emacs-version-alist'
5533 (add-to-list 'customize-package-emacs-version-alist
5534 '(Org ("8.0" . "24.4")
5535 ("8.1" . "24.4")
5536 ("8.2" . "24.4")
5537 ("8.2.7" . "24.4")
5538 ("8.3" . "26.1")
5539 ("9.0" . "26.1")
5540 ("9.1" . "26.1")
5541 ("9.2" . "27.1")))
5543 (defvar org-mode-transpose-word-syntax-table
5544 (let ((st (make-syntax-table text-mode-syntax-table)))
5545 (dolist (c org-emphasis-alist st)
5546 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5548 (when (fboundp 'abbrev-table-put)
5549 (abbrev-table-put org-mode-abbrev-table
5550 :parents (list text-mode-abbrev-table)))
5552 (defun org-find-invisible-foreground ()
5553 (let ((candidates (remove
5554 "unspecified-bg"
5555 (nconc
5556 (list (face-background 'default)
5557 (face-background 'org-default))
5558 (mapcar
5559 (lambda (alist)
5560 (when (boundp alist)
5561 (cdr (assq 'background-color (symbol-value alist)))))
5562 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5563 (list (face-foreground 'org-hide))))))
5564 (car (remove nil candidates))))
5566 (defun org-current-time (&optional rounding-minutes past)
5567 "Current time, possibly rounded to ROUNDING-MINUTES.
5568 When ROUNDING-MINUTES is not an integer, fall back on the car of
5569 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5570 the rounding returns a past time."
5571 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5572 (car org-time-stamp-rounding-minutes)))
5573 (time (decode-time)) res)
5574 (if (< r 1)
5575 (current-time)
5576 (setq res
5577 (apply 'encode-time
5578 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5579 (nthcdr 2 time))))
5580 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5581 (seconds-to-time (- (float-time res) (* r 60)))
5582 res))))
5584 (defun org-today ()
5585 "Return today date, considering `org-extend-today-until'."
5586 (time-to-days
5587 (time-subtract (current-time)
5588 (list 0 (* 3600 org-extend-today-until) 0))))
5590 ;;;; Font-Lock stuff, including the activators
5592 (defvar org-mouse-map (make-sparse-keymap))
5593 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5594 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5595 (when org-mouse-1-follows-link
5596 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5597 (when org-tab-follows-link
5598 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5599 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5601 (require 'font-lock)
5603 (defconst org-non-link-chars "]\t\n\r<>")
5604 (defvar org-link-types-re nil
5605 "Matches a link that has a url-like prefix like \"http:\"")
5606 (defvar org-link-re-with-space nil
5607 "Matches a link with spaces, optional angular brackets around it.")
5608 (defvar org-link-re-with-space2 nil
5609 "Matches a link with spaces, optional angular brackets around it.")
5610 (defvar org-link-re-with-space3 nil
5611 "Matches a link with spaces, only for internal part in bracket links.")
5612 (defvar org-angle-link-re nil
5613 "Matches link with angular brackets, spaces are allowed.")
5614 (defvar org-plain-link-re nil
5615 "Matches plain link, without spaces.")
5616 (defvar org-bracket-link-regexp nil
5617 "Matches a link in double brackets.")
5618 (defvar org-bracket-link-analytic-regexp nil
5619 "Regular expression used to analyze links.
5620 Here is what the match groups contain after a match:
5621 1: http:
5622 2: http
5623 3: path
5624 4: [desc]
5625 5: desc")
5626 (defvar org-bracket-link-analytic-regexp++ nil
5627 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5628 (defvar org-any-link-re nil
5629 "Regular expression matching any link.")
5631 (defconst org-match-sexp-depth 3
5632 "Number of stacked braces for sub/superscript matching.")
5634 (defun org-create-multibrace-regexp (left right n)
5635 "Create a regular expression which will match a balanced sexp.
5636 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5637 as single character strings.
5638 The regexp returned will match the entire expression including the
5639 delimiters. It will also define a single group which contains the
5640 match except for the outermost delimiters. The maximum depth of
5641 stacked delimiters is N. Escaping delimiters is not possible."
5642 (let* ((nothing (concat "[^" left right "]*?"))
5643 (or "\\|")
5644 (re nothing)
5645 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5646 (while (> n 1)
5647 (setq n (1- n)
5648 re (concat re or next)
5649 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5650 (concat left "\\(" re "\\)" right)))
5652 (defconst org-match-substring-regexp
5653 (concat
5654 "\\(\\S-\\)\\([_^]\\)\\("
5655 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5656 "\\|"
5657 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5658 "\\|"
5659 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5660 "The regular expression matching a sub- or superscript.")
5662 (defconst org-match-substring-with-braces-regexp
5663 (concat
5664 "\\(\\S-\\)\\([_^]\\)"
5665 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5666 "The regular expression matching a sub- or superscript, forcing braces.")
5668 (defun org-make-link-regexps ()
5669 "Update the link regular expressions.
5670 This should be called after the variable `org-link-parameters' has changed."
5671 (let ((types-re (regexp-opt (org-link-types) t)))
5672 (setq org-link-types-re
5673 (concat "\\`" types-re ":")
5674 org-link-re-with-space
5675 (concat "<?" types-re ":"
5676 "\\([^" org-non-link-chars " ]"
5677 "[^" org-non-link-chars "]*"
5678 "[^" org-non-link-chars " ]\\)>?")
5679 org-link-re-with-space2
5680 (concat "<?" types-re ":"
5681 "\\([^" org-non-link-chars " ]"
5682 "[^\t\n\r]*"
5683 "[^" org-non-link-chars " ]\\)>?")
5684 org-link-re-with-space3
5685 (concat "<?" types-re ":"
5686 "\\([^" org-non-link-chars " ]"
5687 "[^\t\n\r]*\\)")
5688 org-angle-link-re
5689 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5690 types-re)
5691 org-plain-link-re
5692 (concat
5693 "\\<" types-re ":"
5694 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5695 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5696 org-bracket-link-regexp
5697 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5698 org-bracket-link-analytic-regexp
5699 (concat
5700 "\\[\\["
5701 "\\(" types-re ":\\)?"
5702 "\\([^]]+\\)"
5703 "\\]"
5704 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5705 "\\]")
5706 org-bracket-link-analytic-regexp++
5707 (concat
5708 "\\[\\["
5709 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5710 "\\([^]]+\\)"
5711 "\\]"
5712 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5713 "\\]")
5714 org-any-link-re
5715 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5716 org-angle-link-re "\\)\\|\\("
5717 org-plain-link-re "\\)"))))
5719 (org-make-link-regexps)
5721 (defvar org-emph-face nil)
5723 (defun org-do-emphasis-faces (limit)
5724 "Run through the buffer and emphasize strings."
5725 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5726 (car org-emphasis-regexp-components))))
5727 (catch :exit
5728 (while (re-search-forward quick-re limit t)
5729 (let* ((marker (match-string 2))
5730 (verbatim? (member marker '("~" "="))))
5731 (when (save-excursion
5732 (goto-char (match-beginning 0))
5733 (and
5734 ;; Do not match table hlines.
5735 (not (and (equal marker "+")
5736 (org-match-line
5737 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5738 ;; Do not match headline stars. Do not consider
5739 ;; stars of a headline as closing marker for bold
5740 ;; markup either.
5741 (not (and (equal marker "*")
5742 (save-excursion
5743 (forward-char)
5744 (skip-chars-backward "*")
5745 (looking-at-p org-outline-regexp-bol))))
5746 ;; Match full emphasis markup regexp.
5747 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5748 ;; Do not span over paragraph boundaries.
5749 (not (string-match-p org-element-paragraph-separate
5750 (match-string 2)))
5751 ;; Do not span over cells in table rows.
5752 (not (and (save-match-data (org-match-line "[ \t]*|"))
5753 (string-match-p "|" (match-string 4))))))
5754 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5755 (font-lock-prepend-text-property
5756 (match-beginning 2) (match-end 2) 'face face)
5757 (when verbatim?
5758 (org-remove-flyspell-overlays-in
5759 (match-beginning 0) (match-end 0)))
5760 (add-text-properties (match-beginning 2) (match-end 2)
5761 '(font-lock-multiline t org-emphasis t))
5762 (when org-hide-emphasis-markers
5763 (add-text-properties (match-end 4) (match-beginning 5)
5764 '(invisible org-link))
5765 (add-text-properties (match-beginning 3) (match-end 3)
5766 '(invisible org-link)))
5767 (throw :exit t))))))))
5769 (defun org-emphasize (&optional char)
5770 "Insert or change an emphasis, i.e. a font like bold or italic.
5771 If there is an active region, change that region to a new emphasis.
5772 If there is no region, just insert the marker characters and position
5773 the cursor between them.
5774 CHAR should be the marker character. If it is a space, it means to
5775 remove the emphasis of the selected region.
5776 If CHAR is not given (for example in an interactive call) it will be
5777 prompted for."
5778 (interactive)
5779 (let ((erc org-emphasis-regexp-components)
5780 (string "") beg end move s)
5781 (if (org-region-active-p)
5782 (setq beg (region-beginning)
5783 end (region-end)
5784 string (buffer-substring beg end))
5785 (setq move t))
5787 (unless char
5788 (message "Emphasis marker or tag: [%s]"
5789 (mapconcat #'car org-emphasis-alist ""))
5790 (setq char (read-char-exclusive)))
5791 (if (equal char ?\s)
5792 (setq s ""
5793 move nil)
5794 (unless (assoc (char-to-string char) org-emphasis-alist)
5795 (user-error "No such emphasis marker: \"%c\"" char))
5796 (setq s (char-to-string char)))
5797 (while (and (> (length string) 1)
5798 (equal (substring string 0 1) (substring string -1))
5799 (assoc (substring string 0 1) org-emphasis-alist))
5800 (setq string (substring string 1 -1)))
5801 (setq string (concat s string s))
5802 (when beg (delete-region beg end))
5803 (unless (or (bolp)
5804 (string-match (concat "[" (nth 0 erc) "\n]")
5805 (char-to-string (char-before (point)))))
5806 (insert " "))
5807 (unless (or (eobp)
5808 (string-match (concat "[" (nth 1 erc) "\n]")
5809 (char-to-string (char-after (point)))))
5810 (insert " ") (backward-char 1))
5811 (insert string)
5812 (and move (backward-char 1))))
5814 (defconst org-nonsticky-props
5815 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5817 (defsubst org-rear-nonsticky-at (pos)
5818 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5820 (defun org-activate-links (limit)
5821 "Add link properties to links.
5822 This includes angle, plain, and bracket links."
5823 (catch :exit
5824 (while (re-search-forward org-any-link-re limit t)
5825 (let* ((start (match-beginning 0))
5826 (end (match-end 0))
5827 (style (cond ((eq ?< (char-after start)) 'angle)
5828 ((eq ?\[ (char-after (1+ start))) 'bracket)
5829 (t 'plain))))
5830 (when (and (memq style org-highlight-links)
5831 ;; Do not confuse plain links with tags.
5832 (not (and (eq style 'plain)
5833 (let ((face (get-text-property
5834 (max (1- start) (point-min)) 'face)))
5835 (if (consp face) (memq 'org-tag face)
5836 (eq 'org-tag face))))))
5837 (let* ((link-object (save-excursion
5838 (goto-char start)
5839 (save-match-data (org-element-link-parser))))
5840 (link (org-element-property :raw-link link-object))
5841 (type (org-element-property :type link-object))
5842 (path (org-element-property :path link-object))
5843 (properties ;for link's visible part
5844 (list
5845 'face (pcase (org-link-get-parameter type :face)
5846 ((and (pred functionp) face) (funcall face path))
5847 ((and (pred facep) face) face)
5848 ((and (pred consp) face) face) ;anonymous
5849 (_ 'org-link))
5850 'mouse-face (or (org-link-get-parameter type :mouse-face)
5851 'highlight)
5852 'keymap (or (org-link-get-parameter type :keymap)
5853 org-mouse-map)
5854 'help-echo (pcase (org-link-get-parameter type :help-echo)
5855 ((and (pred stringp) echo) echo)
5856 ((and (pred functionp) echo) echo)
5857 (_ (concat "LINK: " link)))
5858 'htmlize-link (pcase (org-link-get-parameter type
5859 :htmlize-link)
5860 ((and (pred functionp) f) (funcall f))
5861 (_ `(:uri ,link)))
5862 'font-lock-multiline t)))
5863 (org-remove-flyspell-overlays-in start end)
5864 (org-rear-nonsticky-at end)
5865 (if (not (eq 'bracket style))
5866 (add-text-properties start end properties)
5867 ;; Handle invisible parts in bracket links.
5868 (remove-text-properties start end '(invisible nil))
5869 (let ((hidden
5870 (append `(invisible
5871 ,(or (org-link-get-parameter type :display)
5872 'org-link))
5873 properties))
5874 (visible-start (or (match-beginning 4) (match-beginning 2)))
5875 (visible-end (or (match-end 4) (match-end 2))))
5876 (add-text-properties start visible-start hidden)
5877 (add-text-properties visible-start visible-end properties)
5878 (add-text-properties visible-end end hidden)
5879 (org-rear-nonsticky-at visible-start)
5880 (org-rear-nonsticky-at visible-end)))
5881 (let ((f (org-link-get-parameter type :activate-func)))
5882 (when (functionp f)
5883 (funcall f start end path (eq style 'bracket))))
5884 (throw :exit t))))) ;signal success
5885 nil))
5887 (defun org-activate-code (limit)
5888 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5889 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5890 (remove-text-properties (match-beginning 0) (match-end 0)
5891 '(display t invisible t intangible t))
5894 (defcustom org-src-fontify-natively t
5895 "When non-nil, fontify code in code blocks.
5896 See also the `org-block' face."
5897 :type 'boolean
5898 :version "26.1"
5899 :package-version '(Org . "8.3")
5900 :group 'org-appearance
5901 :group 'org-babel)
5903 (defcustom org-allow-promoting-top-level-subtree nil
5904 "When non-nil, allow promoting a top level subtree.
5905 The leading star of the top level headline will be replaced
5906 by a #."
5907 :type 'boolean
5908 :version "24.1"
5909 :group 'org-appearance)
5911 (defun org-fontify-meta-lines-and-blocks (limit)
5912 (condition-case nil
5913 (org-fontify-meta-lines-and-blocks-1 limit)
5914 (error (message "Org mode fontification error in %S at %d"
5915 (current-buffer)
5916 (line-number-at-pos)))))
5918 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5919 "Fontify #+ lines and blocks."
5920 (let ((case-fold-search t))
5921 (when (re-search-forward
5922 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5923 limit t)
5924 (let ((beg (match-beginning 0))
5925 (block-start (match-end 0))
5926 (block-end nil)
5927 (lang (match-string 7))
5928 (beg1 (line-beginning-position 2))
5929 (dc1 (downcase (match-string 2)))
5930 (dc3 (downcase (match-string 3)))
5931 end end1 quoting block-type)
5932 (cond
5933 ((and (match-end 4) (equal dc3 "+begin"))
5934 ;; Truly a block
5935 (setq block-type (downcase (match-string 5))
5936 quoting (member block-type org-protecting-blocks))
5937 (when (re-search-forward
5938 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5939 nil t) ;; on purpose, we look further than LIMIT
5940 (setq end (min (point-max) (match-end 0))
5941 end1 (min (point-max) (1- (match-beginning 0))))
5942 (setq block-end (match-beginning 0))
5943 (when quoting
5944 (org-remove-flyspell-overlays-in beg1 end1)
5945 (remove-text-properties beg end
5946 '(display t invisible t intangible t)))
5947 (add-text-properties
5948 beg end '(font-lock-fontified t font-lock-multiline t))
5949 (add-text-properties beg beg1 '(face org-meta-line))
5950 (org-remove-flyspell-overlays-in beg beg1)
5951 (add-text-properties ; For end_src
5952 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5953 (org-remove-flyspell-overlays-in end1 end)
5954 (cond
5955 ((and lang (not (string= lang "")) org-src-fontify-natively)
5956 (org-src-font-lock-fontify-block lang block-start block-end)
5957 (add-text-properties beg1 block-end '(src-block t)))
5958 (quoting
5959 (add-text-properties beg1 (min (point-max) (1+ end1))
5960 (list 'face
5961 (list :inherit
5962 (let ((face-name
5963 (intern (format "org-block-%s" lang))))
5964 (append (and (facep face-name) (list face-name))
5965 '(org-block))))))) ; end of source block
5966 ((not org-fontify-quote-and-verse-blocks))
5967 ((string= block-type "quote")
5968 (add-face-text-property
5969 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5970 ((string= block-type "verse")
5971 (add-face-text-property
5972 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5973 (add-text-properties beg beg1 '(face org-block-begin-line))
5974 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5975 '(face org-block-end-line))
5977 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5978 (org-remove-flyspell-overlays-in
5979 (match-beginning 0)
5980 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5981 (add-text-properties
5982 beg (match-end 3)
5983 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5984 '(font-lock-fontified t invisible t)
5985 '(font-lock-fontified t face org-document-info-keyword)))
5986 (add-text-properties
5987 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5988 (if (string-equal dc1 "+title:")
5989 '(font-lock-fontified t face org-document-title)
5990 '(font-lock-fontified t face org-document-info))))
5991 ((string-prefix-p "+caption" dc1)
5992 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5993 (remove-text-properties (match-beginning 0) (match-end 0)
5994 '(display t invisible t intangible t))
5995 ;; Handle short captions.
5996 (save-excursion
5997 (beginning-of-line)
5998 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5999 (add-text-properties (line-beginning-position) (match-end 1)
6000 '(font-lock-fontified t face org-meta-line))
6001 (add-text-properties (match-end 0) (line-end-position)
6002 '(font-lock-fontified t face org-block))
6004 ((member dc3 '(" " ""))
6005 (org-remove-flyspell-overlays-in beg (match-end 0))
6006 (add-text-properties
6007 beg (match-end 0)
6008 '(font-lock-fontified t face font-lock-comment-face)))
6009 (t ;; just any other in-buffer setting, but not indented
6010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6011 (remove-text-properties (match-beginning 0) (match-end 0)
6012 '(display t invisible t intangible t))
6013 (add-text-properties beg (match-end 0)
6014 '(font-lock-fontified t face org-meta-line))
6015 t))))))
6017 (defun org-fontify-drawers (limit)
6018 "Fontify drawers."
6019 (when (re-search-forward org-drawer-regexp limit t)
6020 (add-text-properties
6021 (match-beginning 0) (match-end 0)
6022 '(font-lock-fontified t face org-special-keyword))
6023 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6026 (defun org-fontify-macros (limit)
6027 "Fontify macros."
6028 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6029 (let ((begin (match-beginning 0))
6030 (opening-end (match-beginning 1)))
6031 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6032 (match-string 1))
6033 (let ((end (match-end 1))
6034 (closing-start (match-beginning 1)))
6035 (add-text-properties
6036 begin end
6037 '(font-lock-multiline t font-lock-fontified t face org-macro))
6038 (org-remove-flyspell-overlays-in begin end)
6039 (when org-hide-macro-markers
6040 (add-text-properties begin opening-end '(invisible t))
6041 (add-text-properties closing-start end '(invisible t)))
6042 t)))))
6044 (defun org-activate-footnote-links (limit)
6045 "Add text properties for footnotes."
6046 (let ((fn (org-footnote-next-reference-or-definition limit)))
6047 (when fn
6048 (let* ((beg (nth 1 fn))
6049 (end (nth 2 fn))
6050 (label (car fn))
6051 (referencep (/= (line-beginning-position) beg)))
6052 (when (and referencep (nth 3 fn))
6053 (save-excursion
6054 (goto-char beg)
6055 (search-forward (or label "fn:"))
6056 (org-remove-flyspell-overlays-in beg (match-end 0))))
6057 (add-text-properties beg end
6058 (list 'mouse-face 'highlight
6059 'keymap org-mouse-map
6060 'help-echo
6061 (if referencep "Footnote reference"
6062 "Footnote definition")
6063 'font-lock-fontified t
6064 'font-lock-multiline t
6065 'face 'org-footnote))))))
6067 (defun org-activate-dates (limit)
6068 "Add text properties for dates."
6069 (when (and (re-search-forward org-tsr-regexp-both limit t)
6070 (not (equal (char-before (match-beginning 0)) 91)))
6071 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6072 (add-text-properties (match-beginning 0) (match-end 0)
6073 (list 'mouse-face 'highlight
6074 'keymap org-mouse-map))
6075 (org-rear-nonsticky-at (match-end 0))
6076 (when org-display-custom-times
6077 ;; If it's a date range, activate custom time for second date.
6078 (when (match-end 3)
6079 (org-display-custom-time (match-beginning 3) (match-end 3)))
6080 (org-display-custom-time (match-beginning 1) (match-end 1)))
6083 (defvar-local org-target-link-regexp nil
6084 "Regular expression matching radio targets in plain text.")
6086 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6087 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6088 border border border))
6089 "Regular expression matching a link target.")
6091 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6092 "Regular expression matching a radio target.")
6094 (defconst org-any-target-regexp
6095 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6096 "Regular expression matching any target.")
6098 (defun org-activate-target-links (limit)
6099 "Add text properties for target matches."
6100 (when org-target-link-regexp
6101 (let ((case-fold-search t))
6102 (when (re-search-forward org-target-link-regexp limit t)
6103 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6104 (add-text-properties (match-beginning 1) (match-end 1)
6105 (list 'mouse-face 'highlight
6106 'keymap org-mouse-map
6107 'help-echo "Radio target link"
6108 'org-linked-text t))
6109 (org-rear-nonsticky-at (match-end 1))
6110 t))))
6112 (defun org-update-radio-target-regexp ()
6113 "Find all radio targets in this file and update the regular expression.
6114 Also refresh fontification if needed."
6115 (interactive)
6116 (let ((old-regexp org-target-link-regexp)
6117 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6118 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6119 (targets
6120 (org-with-wide-buffer
6121 (goto-char (point-min))
6122 (let (rtn)
6123 (while (re-search-forward org-radio-target-regexp nil t)
6124 ;; Make sure point is really within the object.
6125 (backward-char)
6126 (let ((obj (org-element-context)))
6127 (when (eq (org-element-type obj) 'radio-target)
6128 (cl-pushnew (org-element-property :value obj) rtn
6129 :test #'equal))))
6130 rtn))))
6131 (setq org-target-link-regexp
6132 (and targets
6133 (concat before-re
6134 (mapconcat
6135 (lambda (x)
6136 (replace-regexp-in-string
6137 " +" "\\s-+" (regexp-quote x) t t))
6138 targets
6139 "\\|")
6140 after-re)))
6141 (unless (equal old-regexp org-target-link-regexp)
6142 ;; Clean-up cache.
6143 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6144 ((not org-target-link-regexp) old-regexp)
6146 (concat before-re
6147 (mapconcat
6148 (lambda (re)
6149 (substring re (length before-re)
6150 (- (length after-re))))
6151 (list old-regexp org-target-link-regexp)
6152 "\\|")
6153 after-re)))))
6154 (org-with-wide-buffer
6155 (goto-char (point-min))
6156 (while (re-search-forward regexp nil t)
6157 (org-element-cache-refresh (match-beginning 1)))))
6158 ;; Re fontify buffer.
6159 (when (memq 'radio org-highlight-links)
6160 (org-restart-font-lock)))))
6162 (defvar org-latex-and-related-regexp nil
6163 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6165 (defun org-compute-latex-and-related-regexp ()
6166 "Compute regular expression for LaTeX, entities and sub/superscript.
6167 Result depends on variable `org-highlight-latex-and-related'."
6168 (setq-local
6169 org-latex-and-related-regexp
6170 (let* ((re-sub
6171 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6172 ((eq org-use-sub-superscripts '{})
6173 (list org-match-substring-with-braces-regexp))
6174 (org-use-sub-superscripts (list org-match-substring-regexp))))
6175 (re-latex
6176 (when (memq 'latex org-highlight-latex-and-related)
6177 (let ((matchers (plist-get org-format-latex-options :matchers)))
6178 (delq nil
6179 (mapcar (lambda (x)
6180 (and (member (car x) matchers) (nth 1 x)))
6181 org-latex-regexps)))))
6182 (re-entities
6183 (when (memq 'entities org-highlight-latex-and-related)
6184 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6185 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6187 (defun org-do-latex-and-related (limit)
6188 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6189 LIMIT bounds the search for syntax to highlight. Stop at first
6190 highlighted object, if any. Return t if some highlighting was
6191 done, nil otherwise."
6192 (when (org-string-nw-p org-latex-and-related-regexp)
6193 (catch 'found
6194 (while (re-search-forward org-latex-and-related-regexp limit t)
6195 (unless
6196 (cl-some
6197 (lambda (f)
6198 (memq f '(org-code org-verbatim underline org-special-keyword)))
6199 (save-excursion
6200 (goto-char (1+ (match-beginning 0)))
6201 (face-at-point nil t)))
6202 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6203 '(?_ ?^))
6205 0)))
6206 (font-lock-prepend-text-property
6207 (+ offset (match-beginning 0)) (match-end 0)
6208 'face 'org-latex-and-related)
6209 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6210 '(font-lock-multiline t)))
6211 (throw 'found t)))
6212 nil)))
6214 (defun org-restart-font-lock ()
6215 "Restart `font-lock-mode', to force refontification."
6216 (when (and (boundp 'font-lock-mode) font-lock-mode)
6217 (font-lock-mode -1)
6218 (font-lock-mode 1)))
6220 (defun org-activate-tags (limit)
6221 (when (re-search-forward org-tag-line-re limit t)
6222 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6223 (add-text-properties (match-beginning 1) (match-end 1)
6224 (list 'mouse-face 'highlight
6225 'keymap org-mouse-map))
6226 (org-rear-nonsticky-at (match-end 1))
6229 (defun org-outline-level ()
6230 "Compute the outline level of the heading at point.
6232 If this is called at a normal headline, the level is the number
6233 of stars. Use `org-reduced-level' to remove the effect of
6234 `org-odd-levels'. Unlike to `org-current-level', this function
6235 takes into consideration inlinetasks."
6236 (org-with-wide-buffer
6237 (end-of-line)
6238 (if (re-search-backward org-outline-regexp-bol nil t)
6239 (1- (- (match-end 0) (match-beginning 0)))
6240 0)))
6242 (defvar org-font-lock-keywords nil)
6244 (defsubst org-re-property (property &optional literal allow-null value)
6245 "Return a regexp matching a PROPERTY line.
6247 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6248 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6249 non-nil, match properties even without a value.
6251 Match group 3 is set to the value when it exists. If there is no
6252 value and ALLOW-NULL is non-nil, it is set to the empty string.
6254 With optional argument VALUE, match only property lines with
6255 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6256 unless LITERAL is non-nil."
6257 (concat
6258 "^\\(?4:[ \t]*\\)"
6259 (format "\\(?1::\\(?2:%s\\):\\)"
6260 (if literal property (regexp-quote property)))
6261 (cond (value
6262 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6263 (if literal value (regexp-quote value))))
6264 (allow-null
6265 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6267 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6269 (defconst org-property-re
6270 (org-re-property "\\S-+" 'literal t)
6271 "Regular expression matching a property line.
6272 There are four matching groups:
6273 1: :PROPKEY: including the leading and trailing colon,
6274 2: PROPKEY without the leading and trailing colon,
6275 3: PROPVAL without leading or trailing spaces,
6276 4: the indentation of the current line,
6277 5: trailing whitespace.")
6279 (defvar org-font-lock-hook nil
6280 "Functions to be called for special font lock stuff.")
6282 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6284 (defvar org-font-lock-set-keywords-hook nil
6285 "Functions that can manipulate `org-font-lock-extra-keywords'.
6286 This is called after `org-font-lock-extra-keywords' is defined, but before
6287 it is installed to be used by font lock. This can be useful if something
6288 needs to be inserted at a specific position in the font-lock sequence.")
6290 (defun org-font-lock-hook (limit)
6291 "Run `org-font-lock-hook' within LIMIT."
6292 (run-hook-with-args 'org-font-lock-hook limit))
6294 (defun org-set-font-lock-defaults ()
6295 "Set font lock defaults for the current buffer."
6296 (let* ((em org-fontify-emphasized-text)
6297 (lk org-highlight-links)
6298 (org-font-lock-extra-keywords
6299 (list
6300 ;; Call the hook
6301 '(org-font-lock-hook)
6302 ;; Headlines
6303 `(,(if org-fontify-whole-heading-line
6304 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6305 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6306 (1 (org-get-level-face 1))
6307 (2 (org-get-level-face 2))
6308 (3 (org-get-level-face 3)))
6309 ;; Table lines
6310 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6311 (1 'org-table t))
6312 ;; Table internals
6313 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6314 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6315 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6316 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6317 ;; Drawers
6318 '(org-fontify-drawers)
6319 ;; Properties
6320 (list org-property-re
6321 '(1 'org-special-keyword t)
6322 '(3 'org-property-value t))
6323 ;; Link related fontification.
6324 '(org-activate-links)
6325 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6326 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6327 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6328 (when (memq 'footnote lk) '(org-activate-footnote-links))
6329 ;; Targets.
6330 (list org-any-target-regexp '(0 'org-target t))
6331 ;; Diary sexps.
6332 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6333 ;; Macro
6334 '(org-fontify-macros)
6335 ;; TODO keyword
6336 (list (format org-heading-keyword-regexp-format
6337 org-todo-regexp)
6338 '(2 (org-get-todo-face 2) t))
6339 ;; DONE
6340 (if org-fontify-done-headline
6341 (list (format org-heading-keyword-regexp-format
6342 (concat
6343 "\\(?:"
6344 (mapconcat 'regexp-quote org-done-keywords "\\|")
6345 "\\)"))
6346 '(2 'org-headline-done t))
6347 nil)
6348 ;; Priorities
6349 '(org-font-lock-add-priority-faces)
6350 ;; Tags
6351 '(org-font-lock-add-tag-faces)
6352 ;; Tags groups
6353 (when (and org-group-tags org-tag-groups-alist)
6354 (list (concat org-outline-regexp-bol ".+\\(:"
6355 (regexp-opt (mapcar 'car org-tag-groups-alist))
6356 ":\\).*$")
6357 '(1 'org-tag-group prepend)))
6358 ;; Special keywords
6359 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6360 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6361 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6362 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6363 ;; Emphasis
6364 (when em '(org-do-emphasis-faces))
6365 ;; Checkboxes
6366 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6367 1 'org-checkbox prepend)
6368 (when (cdr (assq 'checkbox org-list-automatic-rules))
6369 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6370 (0 (org-get-checkbox-statistics-face) t)))
6371 ;; Description list items
6372 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6373 1 'org-list-dt prepend)
6374 ;; ARCHIVEd headings
6375 (list (concat
6376 org-outline-regexp-bol
6377 "\\(.*:" org-archive-tag ":.*\\)")
6378 '(1 'org-archived prepend))
6379 ;; Specials
6380 '(org-do-latex-and-related)
6381 '(org-fontify-entities)
6382 '(org-raise-scripts)
6383 ;; Code
6384 '(org-activate-code (1 'org-code t))
6385 ;; COMMENT
6386 (list (format
6387 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6388 org-todo-regexp
6389 org-comment-string)
6390 '(9 'org-special-keyword t))
6391 ;; Blocks and meta lines
6392 '(org-fontify-meta-lines-and-blocks))))
6393 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6394 (run-hooks 'org-font-lock-set-keywords-hook)
6395 ;; Now set the full font-lock-keywords
6396 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6397 (setq-local font-lock-defaults
6398 '(org-font-lock-keywords t nil nil backward-paragraph))
6399 (kill-local-variable 'font-lock-keywords)
6400 nil))
6402 (defun org-toggle-pretty-entities ()
6403 "Toggle the composition display of entities as UTF8 characters."
6404 (interactive)
6405 (setq-local org-pretty-entities (not org-pretty-entities))
6406 (org-restart-font-lock)
6407 (if org-pretty-entities
6408 (message "Entities are now displayed as UTF8 characters")
6409 (save-restriction
6410 (widen)
6411 (decompose-region (point-min) (point-max))
6412 (message "Entities are now displayed as plain text"))))
6414 (defvar-local org-custom-properties-overlays nil
6415 "List of overlays used for custom properties.")
6417 (defun org-toggle-custom-properties-visibility ()
6418 "Display or hide properties in `org-custom-properties'."
6419 (interactive)
6420 (if org-custom-properties-overlays
6421 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6422 (setq org-custom-properties-overlays nil))
6423 (when org-custom-properties
6424 (org-with-wide-buffer
6425 (goto-char (point-min))
6426 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6427 (while (re-search-forward regexp nil t)
6428 (let ((end (cdr (save-match-data (org-get-property-block)))))
6429 (when (and end (< (point) end))
6430 ;; Hide first custom property in current drawer.
6431 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6432 (overlay-put o 'invisible t)
6433 (overlay-put o 'org-custom-property t)
6434 (push o org-custom-properties-overlays))
6435 ;; Hide additional custom properties in the same drawer.
6436 (while (re-search-forward regexp end t)
6437 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6438 (overlay-put o 'invisible t)
6439 (overlay-put o 'org-custom-property t)
6440 (push o org-custom-properties-overlays)))))
6441 ;; Each entry is limited to a single property drawer.
6442 (outline-next-heading)))))))
6444 (defun org-fontify-entities (limit)
6445 "Find an entity to fontify."
6446 (let (ee)
6447 (when org-pretty-entities
6448 (catch 'match
6449 ;; "\_ "-family is left out on purpose. Only the first one,
6450 ;; i.e., "\_ ", could be fontified anyway, and it would be
6451 ;; confusing when adding a second white space character.
6452 (while (re-search-forward
6453 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6454 limit t)
6455 (when (and (not (org-at-comment-p))
6456 (setq ee (org-entity-get (match-string 1)))
6457 (= (length (nth 6 ee)) 1))
6458 (let* ((end (if (equal (match-string 2) "{}")
6459 (match-end 2)
6460 (match-end 1))))
6461 (add-text-properties
6462 (match-beginning 0) end
6463 (list 'font-lock-fontified t))
6464 (compose-region (match-beginning 0) end
6465 (nth 6 ee) nil)
6466 (backward-char 1)
6467 (throw 'match t))))
6468 nil))))
6470 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6471 "Fontify string S like in Org mode."
6472 (with-temp-buffer
6473 (insert s)
6474 (let ((org-odd-levels-only odd-levels))
6475 (org-mode)
6476 (org-font-lock-ensure)
6477 (buffer-string))))
6479 (defvar org-m nil)
6480 (defvar org-l nil)
6481 (defvar org-f nil)
6482 (defun org-get-level-face (n)
6483 "Get the right face for match N in font-lock matching of headlines."
6484 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6485 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6486 (if org-cycle-level-faces
6487 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6488 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6489 (cond
6490 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6491 ((eq n 2) org-f)
6492 (t (unless org-level-color-stars-only org-f))))
6494 (defun org-face-from-face-or-color (context inherit face-or-color)
6495 "Create a face list that inherits INHERIT, but sets the foreground color.
6496 When FACE-OR-COLOR is not a string, just return it."
6497 (if (stringp face-or-color)
6498 (list :inherit inherit
6499 (cdr (assoc context org-faces-easy-properties))
6500 face-or-color)
6501 face-or-color))
6503 (defun org-get-todo-face (kwd)
6504 "Get the right face for a TODO keyword KWD.
6505 If KWD is a number, get the corresponding match group."
6506 (when (numberp kwd) (setq kwd (match-string kwd)))
6507 (or (org-face-from-face-or-color
6508 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6509 (and (member kwd org-done-keywords) 'org-done)
6510 'org-todo))
6512 (defun org-get-priority-face (priority)
6513 "Get the right face for PRIORITY.
6514 PRIORITY is a character."
6515 (or (org-face-from-face-or-color
6516 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6517 'org-priority))
6519 (defun org-get-tag-face (tag)
6520 "Get the right face for TAG.
6521 If TAG is a number, get the corresponding match group."
6522 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6523 (or (org-face-from-face-or-color
6524 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6525 'org-tag)))
6527 (defun org-font-lock-add-priority-faces (limit)
6528 "Add the special priority faces."
6529 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6530 (add-text-properties
6531 (match-beginning 1) (match-end 1)
6532 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6533 'font-lock-fontified t))))
6535 (defun org-font-lock-add-tag-faces (limit)
6536 "Add the special tag faces."
6537 (when (and org-tag-faces org-tags-special-faces-re)
6538 (while (re-search-forward org-tags-special-faces-re limit t)
6539 (add-text-properties (match-beginning 1) (match-end 1)
6540 (list 'face (org-get-tag-face 1)
6541 'font-lock-fontified t))
6542 (backward-char 1))))
6544 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6545 "Remove fontification and activation overlays from links."
6546 (font-lock-default-unfontify-region beg end)
6547 (let* ((buffer-undo-list t)
6548 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6549 (inhibit-modification-hooks t)
6550 deactivate-mark buffer-file-name buffer-file-truename)
6551 (decompose-region beg end)
6552 (remove-text-properties beg end
6553 '(mouse-face t keymap t org-linked-text t
6554 invisible t intangible t
6555 org-emphasis t))
6556 (org-remove-font-lock-display-properties beg end)))
6558 (defconst org-script-display '(((raise -0.3) (height 0.7))
6559 ((raise 0.3) (height 0.7))
6560 ((raise -0.5))
6561 ((raise 0.5)))
6562 "Display properties for showing superscripts and subscripts.")
6564 (defun org-remove-font-lock-display-properties (beg end)
6565 "Remove specific display properties that have been added by font lock.
6566 The will remove the raise properties that are used to show superscripts
6567 and subscripts."
6568 (let (next prop)
6569 (while (< beg end)
6570 (setq next (next-single-property-change beg 'display nil end)
6571 prop (get-text-property beg 'display))
6572 (when (member prop org-script-display)
6573 (put-text-property beg next 'display nil))
6574 (setq beg next))))
6576 (defun org-raise-scripts (limit)
6577 "Add raise properties to sub/superscripts."
6578 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6579 (re-search-forward
6580 (if (eq org-use-sub-superscripts t)
6581 org-match-substring-regexp
6582 org-match-substring-with-braces-regexp)
6583 limit t))
6584 (let* ((pos (point)) table-p comment-p
6585 (mpos (match-beginning 3))
6586 (emph-p (get-text-property mpos 'org-emphasis))
6587 (link-p (get-text-property mpos 'mouse-face))
6588 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6589 (goto-char (point-at-bol))
6590 (setq table-p (looking-at-p org-table-dataline-regexp)
6591 comment-p (looking-at-p "^[ \t]*#[ +]"))
6592 (goto-char pos)
6593 ;; Handle a_b^c
6594 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6595 (unless (or comment-p emph-p link-p keyw-p)
6596 (put-text-property (match-beginning 3) (match-end 0)
6597 'display
6598 (if (equal (char-after (match-beginning 2)) ?^)
6599 (nth (if table-p 3 1) org-script-display)
6600 (nth (if table-p 2 0) org-script-display)))
6601 (add-text-properties (match-beginning 2) (match-end 2)
6602 (list 'invisible t))
6603 (when (and (eq (char-after (match-beginning 3)) ?{)
6604 (eq (char-before (match-end 3)) ?}))
6605 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6606 (list 'invisible t))
6607 (add-text-properties (1- (match-end 3)) (match-end 3)
6608 (list 'invisible t))))
6609 t)))
6611 (defun org-remove-empty-overlays-at (pos)
6612 "Remove outline overlays that do not contain non-white stuff."
6613 (dolist (o (overlays-at pos))
6614 (and (eq 'outline (overlay-get o 'invisible))
6615 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6616 (overlay-end o))))
6617 (delete-overlay o))))
6619 (defun org-show-empty-lines-in-parent ()
6620 "Move to the parent and re-show empty lines before visible headlines."
6621 (save-excursion
6622 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6623 (org-cycle-show-empty-lines context))))
6625 (defun org-files-list ()
6626 "Return `org-agenda-files' list, plus all open Org files.
6627 This is useful for operations that need to scan all of a user's
6628 open and agenda-wise Org files."
6629 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6630 (dolist (buf (buffer-list))
6631 (with-current-buffer buf
6632 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6633 (cl-pushnew (expand-file-name (buffer-file-name)) files
6634 :test #'equal))))
6635 files))
6637 (defsubst org-entry-beginning-position ()
6638 "Return the beginning position of the current entry."
6639 (save-excursion (org-back-to-heading t) (point)))
6641 (defsubst org-entry-end-position ()
6642 "Return the end position of the current entry."
6643 (save-excursion (outline-next-heading) (point)))
6645 (defun org-subtree-end-visible-p ()
6646 "Is the end of the current subtree visible?"
6647 (pos-visible-in-window-p
6648 (save-excursion (org-end-of-subtree t) (point))))
6650 (defun org-first-headline-recenter ()
6651 "Move cursor to the first headline and recenter the headline."
6652 (let ((window (get-buffer-window)))
6653 (when window
6654 (goto-char (point-min))
6655 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6656 (set-window-start window (line-beginning-position))))))
6659 ;;; Visibility (headlines, blocks, drawers)
6661 ;;;; Headlines visibility
6663 (defun org-show-entry ()
6664 "Show the body directly following this heading.
6665 Show the heading too, if it is currently invisible."
6666 (interactive)
6667 (save-excursion
6668 (ignore-errors
6669 (org-back-to-heading t)
6670 (org-flag-region
6671 (line-end-position 0)
6672 (save-excursion
6673 (if (re-search-forward
6674 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6675 (match-beginning 1)
6676 (point-max)))
6678 'outline))))
6680 (defun org-show-children (&optional level)
6681 "Show all direct subheadings of this heading.
6682 Prefix arg LEVEL is how many levels below the current level
6683 should be shown. Default is enough to cause the following
6684 heading to appear."
6685 (interactive "p")
6686 (save-excursion
6687 (org-back-to-heading t)
6688 (let* ((current-level (funcall outline-level))
6689 (max-level (org-get-valid-level
6690 current-level
6691 (if level (prefix-numeric-value level) 1)))
6692 (end (save-excursion (org-end-of-subtree t t)))
6693 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6694 (past-first-child nil)
6695 ;; Make sure to skip inlinetasks.
6696 (re (format regexp-fmt
6697 current-level
6698 (cond
6699 ((not (featurep 'org-inlinetask)) "")
6700 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6702 (t (1- org-inlinetask-min-level))))))
6703 ;; Display parent heading.
6704 (org-flag-heading nil)
6705 (forward-line)
6706 ;; Display children. First child may be deeper than expected
6707 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6708 ;; MAX-LEVEL accordingly.
6709 (while (re-search-forward re end t)
6710 (unless past-first-child
6711 (setq re (format regexp-fmt
6712 current-level
6713 (max (funcall outline-level) max-level)))
6714 (setq past-first-child t))
6715 (org-flag-heading nil)))))
6717 (defun org-show-subtree ()
6718 "Show everything after this heading at deeper levels."
6719 (interactive)
6720 (org-flag-region
6721 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6723 ;;;; Blocks visibility
6725 (defun org-hide-block-toggle-maybe ()
6726 "Toggle visibility of block at point.
6727 Unlike to `org-hide-block-toggle', this function does not throw
6728 an error. Return a non-nil value when toggling is successful."
6729 (interactive)
6730 (ignore-errors (org-hide-block-toggle)))
6732 (defun org-hide-block-toggle (&optional force)
6733 "Toggle the visibility of the current block.
6734 When optional argument FORCE is `off', make block visible. If it
6735 is non-nil, hide it unconditionally. Throw an error when not at
6736 a block. Return a non-nil value when toggling is successful."
6737 (interactive)
6738 (let ((element (org-element-at-point)))
6739 (unless (memq (org-element-type element)
6740 '(center-block comment-block dynamic-block example-block
6741 export-block quote-block special-block
6742 src-block verse-block))
6743 (user-error "Not at a block"))
6744 (let* ((post (org-element-property :post-affiliated element))
6745 (start (save-excursion
6746 (goto-char post)
6747 (line-end-position)))
6748 (end (save-excursion
6749 (goto-char (org-element-property :end element))
6750 (skip-chars-backward " \t\n")
6751 (line-end-position))))
6752 ;; Do nothing when not before or at the block opening line or at
6753 ;; the block closing line.
6754 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6755 (cond ((eq force 'off)
6756 (org-flag-region start end nil 'org-hide-block))
6757 (force
6758 (org-flag-region start end t 'org-hide-block))
6759 ((eq (get-char-property start 'invisible) 'org-hide-block)
6760 (org-flag-region start end nil 'org-hide-block))
6762 (org-flag-region start end t 'org-hide-block)))
6763 ;; When the block is hidden away, make sure point is left in
6764 ;; a visible part of the buffer.
6765 (when (invisible-p (max (1- (point)) (point-min)))
6766 (goto-char post))
6767 ;; Signal success.
6768 t))))
6770 (defun org-hide-block-toggle-all ()
6771 "Toggle the visibility of all blocks in the current buffer."
6772 (org-block-map 'org-hide-block-toggle))
6774 (defun org-hide-block-all ()
6775 "Fold all blocks in the current buffer."
6776 (interactive)
6777 (org-show-all '(blocks))
6778 (org-block-map 'org-hide-block-toggle-maybe))
6780 ;;;; Drawers visibility
6782 (defun org-cycle-hide-drawers (state &optional exceptions)
6783 "Re-hide all drawers after a visibility state change.
6784 STATE should be one of the symbols listed in the docstring of
6785 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6786 a list of strings specifying which drawers should not be hidden."
6787 (when (and (derived-mode-p 'org-mode)
6788 (not (memq state '(overview folded contents))))
6789 (save-excursion
6790 (let* ((globalp (eq state 'all))
6791 (beg (if globalp (point-min) (point)))
6792 (end (if globalp (point-max)
6793 (if (eq state 'children)
6794 (save-excursion (outline-next-heading) (point))
6795 (org-end-of-subtree t)))))
6796 (goto-char beg)
6797 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6798 (unless (member-ignore-case (match-string 1) exceptions)
6799 (let ((drawer (org-element-at-point)))
6800 (when (memq (org-element-type drawer) '(drawer property-drawer))
6801 (org-flag-drawer t drawer)
6802 ;; Make sure to skip drawer entirely or we might flag
6803 ;; it another time when matching its ending line with
6804 ;; `org-drawer-regexp'.
6805 (goto-char (org-element-property :end drawer))))))))))
6807 (defun org-flag-drawer (flag &optional element)
6808 "When FLAG is non-nil, hide the drawer we are at.
6809 Otherwise make it visible. When optional argument ELEMENT is
6810 a parsed drawer, as returned by `org-element-at-point', hide or
6811 show that drawer instead."
6812 (let ((drawer (or element
6813 (and (save-excursion
6814 (beginning-of-line)
6815 (looking-at-p org-drawer-regexp))
6816 (org-element-at-point)))))
6817 (when (memq (org-element-type drawer) '(drawer property-drawer))
6818 (let ((post (org-element-property :post-affiliated drawer)))
6819 (org-flag-region
6820 (save-excursion (goto-char post) (line-end-position))
6821 (save-excursion (goto-char (org-element-property :end drawer))
6822 (skip-chars-backward " \t\n")
6823 (line-end-position))
6824 flag 'org-hide-drawer)
6825 ;; When the drawer is hidden away, make sure point lies in
6826 ;; a visible part of the buffer.
6827 (when (invisible-p (max (1- (point)) (point-min)))
6828 (goto-char post))))))
6830 ;;;; Visibility cycling
6832 (defvar-local org-cycle-global-status nil)
6833 (put 'org-cycle-global-status 'org-state t)
6834 (defvar-local org-cycle-subtree-status nil)
6835 (put 'org-cycle-subtree-status 'org-state t)
6837 (defun org-show-all (&optional types)
6838 "Show all contents in the visible part of the buffer.
6839 By default, the function expands headings, blocks and drawers.
6840 When optional argument TYPE is a list of symbols among `blocks',
6841 `drawers' and `headings', to only expand one specific type."
6842 (dolist (type (or types '(blocks drawers headings)))
6843 (org-flag-region (point-min) (point-max) nil
6844 (pcase type
6845 (`blocks 'org-hide-block)
6846 (`drawers 'org-hide-drawer)
6847 (`headings 'outline)
6848 (_ (error "Invalid type: %S" type))))))
6850 ;;;###autoload
6851 (defun org-cycle (&optional arg)
6852 "TAB-action and visibility cycling for Org mode.
6854 This is the command invoked in Org mode by the `TAB' key. Its main
6855 purpose is outline visibility cycling, but it also invokes other actions
6856 in special contexts.
6858 When this function is called with a `\\[universal-argument]' prefix, rotate \
6859 the entire
6860 buffer through 3 states (global cycling)
6861 1. OVERVIEW: Show only top-level headlines.
6862 2. CONTENTS: Show all headlines of all levels, but no body text.
6863 3. SHOW ALL: Show everything.
6865 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6866 switch to the startup visibility,
6867 determined by the variable `org-startup-folded', and by any VISIBILITY
6868 properties in the buffer.
6870 With a `\\[universal-argument] \\[universal-argument] \
6871 \\[universal-argument]' prefix argument, show the entire buffer, including
6872 any drawers.
6874 When inside a table, re-align the table and move to the next field.
6876 When point is at the beginning of a headline, rotate the subtree started
6877 by this line through 3 different states (local cycling)
6878 1. FOLDED: Only the main headline is shown.
6879 2. CHILDREN: The main headline and the direct children are shown.
6880 From this state, you can move to one of the children
6881 and zoom in further.
6882 3. SUBTREE: Show the entire subtree, including body text.
6883 If there is no subtree, switch directly from CHILDREN to FOLDED.
6885 When point is at the beginning of an empty headline and the variable
6886 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6887 of the headline by demoting and promoting it to likely levels. This
6888 speeds up creation document structure by pressing `TAB' once or several
6889 times right after creating a new headline.
6891 When there is a numeric prefix, go up to a heading with level ARG, do
6892 a `show-subtree' and return to the previous cursor position. If ARG
6893 is negative, go up that many levels.
6895 When point is not at the beginning of a headline, execute the global
6896 binding for `TAB', which is re-indenting the line. See the option
6897 `org-cycle-emulate-tab' for details.
6899 As a special case, if point is at the beginning of the buffer and there is
6900 no headline in line 1, this function will act as if called with prefix arg
6901 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6902 prefix arg, but only
6903 if the variable `org-cycle-global-at-bob' is t."
6904 (interactive "P")
6905 (org-load-modules-maybe)
6906 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6907 (and org-cycle-level-after-item/entry-creation
6908 (or (org-cycle-level)
6909 (org-cycle-item-indentation))))
6910 (let* ((limit-level
6911 (or org-cycle-max-level
6912 (and (boundp 'org-inlinetask-min-level)
6913 org-inlinetask-min-level
6914 (1- org-inlinetask-min-level))))
6915 (nstars (and limit-level
6916 (if org-odd-levels-only
6917 (and limit-level (1- (* limit-level 2)))
6918 limit-level)))
6919 (org-outline-regexp
6920 (if (not (derived-mode-p 'org-mode))
6921 outline-regexp
6922 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6923 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6924 (not (looking-at org-outline-regexp))))
6925 (org-cycle-hook
6926 (if bob-special
6927 (delq 'org-optimize-window-after-visibility-change
6928 (copy-sequence org-cycle-hook))
6929 org-cycle-hook))
6930 (pos (point)))
6932 (cond
6934 ((equal arg '(16))
6935 (setq last-command 'dummy)
6936 (org-set-startup-visibility)
6937 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6939 ((equal arg '(64))
6940 (org-show-all)
6941 (org-unlogged-message "Entire buffer visible, including drawers"))
6943 ((equal arg '(4)) (org-cycle-internal-global))
6945 ;; Try hiding block at point.
6946 ((org-hide-block-toggle-maybe))
6948 ;; Try cdlatex TAB completion
6949 ((org-try-cdlatex-tab))
6951 ;; Table: enter it or move to the next field.
6952 ((org-at-table-p 'any)
6953 (if (org-at-table.el-p)
6954 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6955 Use `\\[org-edit-special]' to edit table.el tables"))
6956 (if arg (org-table-edit-field t)
6957 (org-table-justify-field-maybe)
6958 (call-interactively 'org-table-next-field))))
6960 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6962 ;; Global cycling: delegate to `org-cycle-internal-global'.
6963 (bob-special (org-cycle-internal-global))
6965 ;; Drawers: delegate to `org-flag-drawer'.
6966 ((save-excursion
6967 (beginning-of-line 1)
6968 (looking-at org-drawer-regexp))
6969 (org-flag-drawer ; toggle block visibility
6970 (not (get-char-property (match-end 0) 'invisible))))
6972 ;; Show-subtree, ARG levels up from here.
6973 ((integerp arg)
6974 (save-excursion
6975 (org-back-to-heading)
6976 (outline-up-heading (if (< arg 0) (- arg)
6977 (- (funcall outline-level) arg)))
6978 (org-show-subtree)))
6980 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6981 ((and (featurep 'org-inlinetask)
6982 (org-inlinetask-at-task-p)
6983 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6984 (org-inlinetask-toggle-visibility))
6986 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6987 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6988 (save-excursion (move-beginning-of-line 1)
6989 (looking-at org-outline-regexp)))
6990 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6991 (org-cycle-internal-local))
6993 ;; From there: TAB emulation and template completion.
6994 (buffer-read-only (org-back-to-heading))
6996 ((run-hook-with-args-until-success
6997 'org-tab-after-check-for-cycling-hook))
6999 ((run-hook-with-args-until-success
7000 'org-tab-before-tab-emulation-hook))
7002 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7003 (or (not (bolp))
7004 (not (looking-at org-outline-regexp))))
7005 (call-interactively (global-key-binding "\t")))
7007 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7008 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7009 (or (and (eq org-cycle-emulate-tab 'white)
7010 (= (match-end 0) (point-at-eol)))
7011 (and (eq org-cycle-emulate-tab 'whitestart)
7012 (>= (match-end 0) pos))))
7014 (eq org-cycle-emulate-tab t))
7015 (call-interactively (global-key-binding "\t")))
7017 (t (save-excursion
7018 (org-back-to-heading)
7019 (org-cycle)))))))
7021 (defun org-cycle-internal-global ()
7022 "Do the global cycling action."
7023 ;; Hack to avoid display of messages for .org attachments in Gnus
7024 (let ((ga (string-match "\\*fontification" (buffer-name))))
7025 (cond
7026 ((and (eq last-command this-command)
7027 (eq org-cycle-global-status 'overview))
7028 ;; We just created the overview - now do table of contents
7029 ;; This can be slow in very large buffers, so indicate action
7030 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7031 (unless ga (org-unlogged-message "CONTENTS..."))
7032 (org-content)
7033 (unless ga (org-unlogged-message "CONTENTS...done"))
7034 (setq org-cycle-global-status 'contents)
7035 (run-hook-with-args 'org-cycle-hook 'contents))
7037 ((and (eq last-command this-command)
7038 (eq org-cycle-global-status 'contents))
7039 ;; We just showed the table of contents - now show everything
7040 (run-hook-with-args 'org-pre-cycle-hook 'all)
7041 (org-show-all '(headings blocks))
7042 (unless ga (org-unlogged-message "SHOW ALL"))
7043 (setq org-cycle-global-status 'all)
7044 (run-hook-with-args 'org-cycle-hook 'all))
7047 ;; Default action: go to overview
7048 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7049 (org-overview)
7050 (unless ga (org-unlogged-message "OVERVIEW"))
7051 (setq org-cycle-global-status 'overview)
7052 (run-hook-with-args 'org-cycle-hook 'overview)))))
7054 (defvar org-called-with-limited-levels nil
7055 "Non-nil when `org-with-limited-levels' is currently active.")
7057 (defun org-cycle-internal-local ()
7058 "Do the local cycling action."
7059 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7060 ;; First, determine end of headline (EOH), end of subtree or item
7061 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7062 (save-excursion
7063 (if (org-at-item-p)
7064 (progn
7065 (beginning-of-line)
7066 (setq struct (org-list-struct))
7067 (setq eoh (point-at-eol))
7068 (setq eos (org-list-get-item-end-before-blank (point) struct))
7069 (setq has-children (org-list-has-child-p (point) struct)))
7070 (org-back-to-heading)
7071 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7072 (setq eos (save-excursion (org-end-of-subtree t t)
7073 (when (bolp) (backward-char)) (point)))
7074 (setq has-children
7075 (or (save-excursion
7076 (let ((level (funcall outline-level)))
7077 (outline-next-heading)
7078 (and (org-at-heading-p t)
7079 (> (funcall outline-level) level))))
7080 (save-excursion
7081 (org-list-search-forward (org-item-beginning-re) eos t)))))
7082 ;; Determine end invisible part of buffer (EOL)
7083 (beginning-of-line 2)
7084 (while (and (not (eobp)) ;This is like `next-line'.
7085 (get-char-property (1- (point)) 'invisible))
7086 (goto-char (next-single-char-property-change (point) 'invisible))
7087 (and (eolp) (beginning-of-line 2)))
7088 (setq eol (point)))
7089 ;; Find out what to do next and set `this-command'
7090 (cond
7091 ((= eos eoh)
7092 ;; Nothing is hidden behind this heading
7093 (unless (org-before-first-heading-p)
7094 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7095 (org-unlogged-message "EMPTY ENTRY")
7096 (setq org-cycle-subtree-status nil)
7097 (save-excursion
7098 (goto-char eos)
7099 (outline-next-heading)
7100 (when (org-invisible-p) (org-flag-heading nil))))
7101 ((and (or (>= eol eos)
7102 (not (string-match "\\S-" (buffer-substring eol eos))))
7103 (or has-children
7104 (not (setq children-skipped
7105 org-cycle-skip-children-state-if-no-children))))
7106 ;; Entire subtree is hidden in one line: children view
7107 (unless (org-before-first-heading-p)
7108 (run-hook-with-args 'org-pre-cycle-hook 'children))
7109 (if (org-at-item-p)
7110 (org-list-set-item-visibility (point-at-bol) struct 'children)
7111 (org-show-entry)
7112 (org-with-limited-levels (org-show-children))
7113 (org-show-set-visibility 'canonical)
7114 ;; Fold every list in subtree to top-level items.
7115 (when (eq org-cycle-include-plain-lists 'integrate)
7116 (save-excursion
7117 (org-back-to-heading)
7118 (while (org-list-search-forward (org-item-beginning-re) eos t)
7119 (beginning-of-line 1)
7120 (let* ((struct (org-list-struct))
7121 (prevs (org-list-prevs-alist struct))
7122 (end (org-list-get-bottom-point struct)))
7123 (dolist (e (org-list-get-all-items (point) struct prevs))
7124 (org-list-set-item-visibility e struct 'folded))
7125 (goto-char (if (< end eos) end eos)))))))
7126 (org-unlogged-message "CHILDREN")
7127 (save-excursion
7128 (goto-char eos)
7129 (outline-next-heading)
7130 (when (org-invisible-p) (org-flag-heading nil)))
7131 (setq org-cycle-subtree-status 'children)
7132 (unless (org-before-first-heading-p)
7133 (run-hook-with-args 'org-cycle-hook 'children)))
7134 ((or children-skipped
7135 (and (eq last-command this-command)
7136 (eq org-cycle-subtree-status 'children)))
7137 ;; We just showed the children, or no children are there,
7138 ;; now show everything.
7139 (unless (org-before-first-heading-p)
7140 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7141 (org-flag-region eoh eos nil 'outline)
7142 (org-unlogged-message
7143 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7144 (setq org-cycle-subtree-status 'subtree)
7145 (unless (org-before-first-heading-p)
7146 (run-hook-with-args 'org-cycle-hook 'subtree)))
7148 ;; Default action: hide the subtree.
7149 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7150 (org-flag-region eoh eos t 'outline)
7151 (org-unlogged-message "FOLDED")
7152 (setq org-cycle-subtree-status 'folded)
7153 (unless (org-before-first-heading-p)
7154 (run-hook-with-args 'org-cycle-hook 'folded))))))
7156 ;;;###autoload
7157 (defun org-global-cycle (&optional arg)
7158 "Cycle the global visibility. For details see `org-cycle'.
7159 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7160 With a numeric prefix, show all headlines up to that level."
7161 (interactive "P")
7162 (let ((org-cycle-include-plain-lists
7163 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7164 (cond
7165 ((integerp arg)
7166 (org-show-all '(headings blocks))
7167 (outline-hide-sublevels arg)
7168 (setq org-cycle-global-status 'contents))
7169 ((equal arg '(4))
7170 (org-set-startup-visibility)
7171 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7173 (org-cycle '(4))))))
7175 (defun org-set-startup-visibility ()
7176 "Set the visibility required by startup options and properties."
7177 (cond
7178 ((eq org-startup-folded t)
7179 (org-overview))
7180 ((eq org-startup-folded 'content)
7181 (org-content))
7182 ((or (eq org-startup-folded 'showeverything)
7183 (eq org-startup-folded nil))
7184 (org-show-all)))
7185 (unless (eq org-startup-folded 'showeverything)
7186 (when org-hide-block-startup (org-hide-block-all))
7187 (org-set-visibility-according-to-property)
7188 (org-cycle-hide-archived-subtrees 'all)
7189 (org-cycle-hide-drawers 'all)
7190 (org-cycle-show-empty-lines t)))
7192 (defun org-set-visibility-according-to-property ()
7193 "Switch subtree visibilities according to :VISIBILITY: property."
7194 (interactive)
7195 (org-with-wide-buffer
7196 (goto-char (point-min))
7197 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7198 (if (not (org-at-property-p)) (outline-next-heading)
7199 (let ((state (match-string 3)))
7200 (save-excursion
7201 (org-back-to-heading t)
7202 (outline-hide-subtree)
7203 (org-reveal)
7204 (cond
7205 ((equal state "folded")
7206 (outline-hide-subtree))
7207 ((equal state "children")
7208 (org-show-hidden-entry)
7209 (org-show-children))
7210 ((equal state "content")
7211 (save-excursion
7212 (save-restriction
7213 (org-narrow-to-subtree)
7214 (org-content))))
7215 ((member state '("all" "showall"))
7216 (outline-show-subtree)))))))))
7218 (defun org-overview ()
7219 "Switch to overview mode, showing only top-level headlines.
7220 This shows all headlines with a level equal or greater than the level
7221 of the first headline in the buffer. This is important, because if the
7222 first headline is not level one, then (hide-sublevels 1) gives confusing
7223 results."
7224 (interactive)
7225 (save-excursion
7226 (let ((level
7227 (save-excursion
7228 (goto-char (point-min))
7229 (when (re-search-forward org-outline-regexp-bol nil t)
7230 (goto-char (match-beginning 0))
7231 (funcall outline-level)))))
7232 (and level (outline-hide-sublevels level)))))
7234 (defun org-content (&optional arg)
7235 "Show all headlines in the buffer, like a table of contents.
7236 With numerical argument N, show content up to level N."
7237 (interactive "P")
7238 (org-overview)
7239 (save-excursion
7240 ;; Visit all headings and show their offspring
7241 (and (integerp arg) (org-overview))
7242 (goto-char (point-max))
7243 (catch 'exit
7244 (while (and (progn (condition-case nil
7245 (outline-previous-visible-heading 1)
7246 (error (goto-char (point-min))))
7248 (looking-at org-outline-regexp))
7249 (if (integerp arg)
7250 (org-show-children (1- arg))
7251 (outline-show-branches))
7252 (when (bobp) (throw 'exit nil))))))
7254 (defun org-optimize-window-after-visibility-change (state)
7255 "Adjust the window after a change in outline visibility.
7256 This function is the default value of the hook `org-cycle-hook'."
7257 (when (get-buffer-window (current-buffer))
7258 (cond
7259 ((eq state 'content) nil)
7260 ((eq state 'all) nil)
7261 ((eq state 'folded) nil)
7262 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7263 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7265 (defun org-clean-visibility-after-subtree-move ()
7266 "Fix visibility issues after moving a subtree."
7267 ;; First, find a reasonable region to look at:
7268 ;; Start two siblings above, end three below
7269 (let* ((beg (save-excursion
7270 (and (org-get-last-sibling)
7271 (org-get-last-sibling))
7272 (point)))
7273 (end (save-excursion
7274 (and (org-get-next-sibling)
7275 (org-get-next-sibling)
7276 (org-get-next-sibling))
7277 (if (org-at-heading-p)
7278 (point-at-eol)
7279 (point))))
7280 (level (looking-at "\\*+"))
7281 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7282 (save-excursion
7283 (save-restriction
7284 (narrow-to-region beg end)
7285 (when re
7286 ;; Properly fold already folded siblings
7287 (goto-char (point-min))
7288 (while (re-search-forward re nil t)
7289 (when (and (not (org-invisible-p))
7290 (org-invisible-p (line-end-position)))
7291 (outline-hide-entry))))
7292 (org-cycle-hide-drawers 'all)
7293 (org-cycle-show-empty-lines 'overview)))))
7295 (defun org-cycle-show-empty-lines (state)
7296 "Show empty lines above all visible headlines.
7297 The region to be covered depends on STATE when called through
7298 `org-cycle-hook'. Lisp program can use t for STATE to get the
7299 entire buffer covered. Note that an empty line is only shown if there
7300 are at least `org-cycle-separator-lines' empty lines before the headline."
7301 (when (/= org-cycle-separator-lines 0)
7302 (save-excursion
7303 (let* ((n (abs org-cycle-separator-lines))
7304 (re (cond
7305 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7306 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7307 (t (let ((ns (number-to-string (- n 2))))
7308 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7309 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7310 beg end)
7311 (cond
7312 ((memq state '(overview contents t))
7313 (setq beg (point-min) end (point-max)))
7314 ((memq state '(children folded))
7315 (setq beg (point)
7316 end (progn (org-end-of-subtree t t)
7317 (line-beginning-position 2)))))
7318 (when beg
7319 (goto-char beg)
7320 (while (re-search-forward re end t)
7321 (unless (get-char-property (match-end 1) 'invisible)
7322 (let ((e (match-end 1))
7323 (b (if (>= org-cycle-separator-lines 0)
7324 (match-beginning 1)
7325 (save-excursion
7326 (goto-char (match-beginning 0))
7327 (skip-chars-backward " \t\n")
7328 (line-end-position)))))
7329 (org-flag-region b e nil 'outline))))))))
7330 ;; Never hide empty lines at the end of the file.
7331 (save-excursion
7332 (goto-char (point-max))
7333 (outline-previous-heading)
7334 (outline-end-of-heading)
7335 (when (and (looking-at "[ \t\n]+")
7336 (= (match-end 0) (point-max)))
7337 (org-flag-region (point) (match-end 0) nil 'outline))))
7339 ;;;; Reveal point location
7341 (defun org-show-context (&optional key)
7342 "Make sure point and context are visible.
7343 Optional argument KEY, when non-nil, is a symbol. See
7344 `org-show-context-detail' for allowed values and how much is to
7345 be shown."
7346 (org-show-set-visibility
7347 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7348 ((cdr (assq key org-show-context-detail)))
7349 (t (cdr (assq 'default org-show-context-detail))))))
7351 (defun org-show-set-visibility (detail)
7352 "Set visibility around point according to DETAIL.
7353 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7354 `tree', `canonical' or t. See `org-show-context-detail' for more
7355 information."
7356 ;; Show current heading and possibly its entry, following headline
7357 ;; or all children.
7358 (if (and (org-at-heading-p) (not (eq detail 'local)))
7359 (org-flag-heading nil)
7360 (org-show-entry)
7361 ;; If point is hidden within a drawer or a block, make sure to
7362 ;; expose it.
7363 (dolist (o (overlays-at (point)))
7364 (when (memq (overlay-get o 'invisible)
7365 '(org-hide-block org-hide-drawer outline))
7366 (delete-overlay o)))
7367 (unless (org-before-first-heading-p)
7368 (org-with-limited-levels
7369 (cl-case detail
7370 ((tree canonical t) (org-show-children))
7371 ((nil minimal ancestors))
7372 (t (save-excursion
7373 (outline-next-heading)
7374 (org-flag-heading nil)))))))
7375 ;; Show all siblings.
7376 (when (eq detail 'lineage) (org-show-siblings))
7377 ;; Show ancestors, possibly with their children.
7378 (when (memq detail '(ancestors lineage tree canonical t))
7379 (save-excursion
7380 (while (org-up-heading-safe)
7381 (org-flag-heading nil)
7382 (when (memq detail '(canonical t)) (org-show-entry))
7383 (when (memq detail '(tree canonical t)) (org-show-children))))))
7385 (defvar org-reveal-start-hook nil
7386 "Hook run before revealing a location.")
7388 (defun org-reveal (&optional siblings)
7389 "Show current entry, hierarchy above it, and the following headline.
7391 This can be used to show a consistent set of context around
7392 locations exposed with `org-show-context'.
7394 With optional argument SIBLINGS, on each level of the hierarchy all
7395 siblings are shown. This repairs the tree structure to what it would
7396 look like when opened with hierarchical calls to `org-cycle'.
7398 With a \\[universal-argument] \\[universal-argument] prefix, \
7399 go to the parent and show the entire tree."
7400 (interactive "P")
7401 (run-hooks 'org-reveal-start-hook)
7402 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7403 ((equal siblings '(16))
7404 (save-excursion
7405 (when (org-up-heading-safe)
7406 (org-show-subtree)
7407 (run-hook-with-args 'org-cycle-hook 'subtree))))
7408 (t (org-show-set-visibility 'lineage))))
7411 ;;; Indirect buffer display of subtrees
7413 (defvar org-indirect-dedicated-frame nil
7414 "This is the frame being used for indirect tree display.")
7415 (defvar org-last-indirect-buffer nil)
7417 (defun org-tree-to-indirect-buffer (&optional arg)
7418 "Create indirect buffer and narrow it to current subtree.
7420 With a numerical prefix ARG, go up to this level and then take that tree.
7421 If ARG is negative, go up that many levels.
7423 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7424 indirect buffer previously made with this command, to avoid proliferation of
7425 indirect buffers. However, when you call the command with a \
7426 `\\[universal-argument]' prefix, or
7427 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7428 so that you can work with several indirect buffers at the same time. If
7429 `org-indirect-buffer-display' is `dedicated-frame', the \
7430 `\\[universal-argument]' prefix also
7431 requests that a new frame be made for the new buffer, so that the dedicated
7432 frame is not changed."
7433 (interactive "P")
7434 (let ((cbuf (current-buffer))
7435 (cwin (selected-window))
7436 (pos (point))
7437 beg end level heading ibuf)
7438 (save-excursion
7439 (org-back-to-heading t)
7440 (when (numberp arg)
7441 (setq level (org-outline-level))
7442 (when (< arg 0) (setq arg (+ level arg)))
7443 (while (> (setq level (org-outline-level)) arg)
7444 (org-up-heading-safe)))
7445 (setq beg (point)
7446 heading (org-get-heading 'no-tags))
7447 (org-end-of-subtree t t)
7448 (when (org-at-heading-p) (backward-char 1))
7449 (setq end (point)))
7450 (when (and (buffer-live-p org-last-indirect-buffer)
7451 (not (eq org-indirect-buffer-display 'new-frame))
7452 (not arg))
7453 (kill-buffer org-last-indirect-buffer))
7454 (setq ibuf (org-get-indirect-buffer cbuf heading)
7455 org-last-indirect-buffer ibuf)
7456 (cond
7457 ((or (eq org-indirect-buffer-display 'new-frame)
7458 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7459 (select-frame (make-frame))
7460 (delete-other-windows)
7461 (pop-to-buffer-same-window ibuf)
7462 (org-set-frame-title heading))
7463 ((eq org-indirect-buffer-display 'dedicated-frame)
7464 (raise-frame
7465 (select-frame (or (and org-indirect-dedicated-frame
7466 (frame-live-p org-indirect-dedicated-frame)
7467 org-indirect-dedicated-frame)
7468 (setq org-indirect-dedicated-frame (make-frame)))))
7469 (delete-other-windows)
7470 (pop-to-buffer-same-window ibuf)
7471 (org-set-frame-title (concat "Indirect: " heading)))
7472 ((eq org-indirect-buffer-display 'current-window)
7473 (pop-to-buffer-same-window ibuf))
7474 ((eq org-indirect-buffer-display 'other-window)
7475 (pop-to-buffer ibuf))
7476 (t (error "Invalid value")))
7477 (narrow-to-region beg end)
7478 (org-show-all '(headings blocks))
7479 (goto-char pos)
7480 (run-hook-with-args 'org-cycle-hook 'all)
7481 (and (window-live-p cwin) (select-window cwin))))
7483 (defun org-get-indirect-buffer (&optional buffer heading)
7484 (setq buffer (or buffer (current-buffer)))
7485 (let ((n 1) (base (buffer-name buffer)) bname)
7486 (while (buffer-live-p
7487 (get-buffer
7488 (setq bname
7489 (concat base "-"
7490 (if heading (concat heading "-" (number-to-string n))
7491 (number-to-string n))))))
7492 (setq n (1+ n)))
7493 (condition-case nil
7494 (make-indirect-buffer buffer bname 'clone)
7495 (error (make-indirect-buffer buffer bname)))))
7497 (defun org-set-frame-title (title)
7498 "Set the title of the current frame to the string TITLE."
7499 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7501 ;;;; Structure editing
7503 ;;; Inserting headlines
7505 (defun org--line-empty-p (n)
7506 "Is the Nth next line empty?
7508 Counts the current line as N = 1 and the previous line as N = 0;
7509 see `beginning-of-line'."
7510 (save-excursion
7511 (and (not (bobp))
7512 (or (beginning-of-line n) t)
7513 (save-match-data
7514 (looking-at "[ \t]*$")))))
7516 (defun org-previous-line-empty-p ()
7517 "Is the previous line a blank line?
7518 When NEXT is non-nil, check the next line instead."
7519 (org--line-empty-p 0))
7521 (defun org-next-line-empty-p ()
7522 "Is the previous line a blank line?
7523 When NEXT is non-nil, check the next line instead."
7524 (org--line-empty-p 2))
7526 (defun org--blank-before-heading-p (&optional parent)
7527 "Non-nil when an empty line should precede a new heading here.
7528 When optional argument PARENT is non-nil, consider parent
7529 headline instead of current one."
7530 (pcase (assq 'heading org-blank-before-new-entry)
7531 (`(heading . auto)
7532 (save-excursion
7533 (org-with-limited-levels
7534 (unless (and (org-before-first-heading-p)
7535 (not (outline-next-heading)))
7536 (org-back-to-heading t)
7537 (when parent (org-up-heading-safe))
7538 (cond ((not (bobp))
7539 (org-previous-line-empty-p))
7540 ((outline-next-heading)
7541 (org-previous-line-empty-p))
7542 ;; Ignore trailing spaces on last buffer line.
7543 ((progn (skip-chars-backward " \t") (bolp))
7544 (org-previous-line-empty-p))
7545 (t nil))))))
7546 (`(heading . ,value) value)
7547 (_ nil)))
7549 (defun org-insert-heading (&optional arg invisible-ok top)
7550 "Insert a new heading or an item with the same depth at point.
7552 If point is at the beginning of a heading, insert a new heading
7553 or a new headline above the current one. When at the beginning
7554 of a regular line of text, turn it into a heading.
7556 If point is in the middle of a line, split it and create a new
7557 headline with the text in the current line after point (see
7558 `org-M-RET-may-split-line' on how to modify this behavior). As
7559 a special case, on a headline, splitting can only happen on the
7560 title itself. E.g., this excludes breaking stars or tags.
7562 With a `\\[universal-argument]' prefix, set \
7563 `org-insert-heading-respect-content' to
7564 a non-nil value for the duration of the command. This forces the
7565 insertion of a heading after the current subtree, independently
7566 on the location of point.
7568 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7569 insert the heading at the end of the tree
7570 above the current heading. For example, if point is within a
7571 2nd-level heading, then it will insert a 2nd-level heading at
7572 the end of the 1st-level parent subtree.
7574 When INVISIBLE-OK is set, stop at invisible headlines when going
7575 back. This is important for non-interactive uses of the
7576 command.
7578 When optional argument TOP is non-nil, insert a level 1 heading,
7579 unconditionally."
7580 (interactive "P")
7581 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7582 (level (org-current-level))
7583 (stars (make-string (if (and level (not top)) level 1) ?*)))
7584 (cond
7585 ((or org-insert-heading-respect-content
7586 (member arg '((4) (16)))
7587 (and (not invisible-ok)
7588 (invisible-p (max (1- (point)) (point-min)))))
7589 ;; Position point at the location of insertion.
7590 (if (not level) ;before first headline
7591 (org-with-limited-levels (outline-next-heading))
7592 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7593 ;; is nil.
7594 (org-with-limited-levels (org-back-to-heading invisible-ok))
7595 (cond ((equal arg '(16))
7596 (org-up-heading-safe)
7597 (org-end-of-subtree t t))
7599 (org-end-of-subtree t t))))
7600 (unless (bolp) (insert "\n")) ;ensure final newline
7601 (unless (and blank? (org-previous-line-empty-p))
7602 (org-N-empty-lines-before-current (if blank? 1 0)))
7603 (insert stars " \n")
7604 (forward-char -1))
7605 ;; At a headline...
7606 ((org-at-heading-p)
7607 (cond ((bolp)
7608 (when blank? (save-excursion (insert "\n")))
7609 (save-excursion (insert stars " \n"))
7610 (unless (and blank? (org-previous-line-empty-p))
7611 (org-N-empty-lines-before-current (if blank? 1 0)))
7612 (end-of-line))
7613 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7614 (org-match-line org-complex-heading-regexp)
7615 (org-pos-in-match-range (point) 4))
7616 ;; Grab the text that should moved to the new headline.
7617 ;; Preserve tags.
7618 (let ((split (delete-and-extract-region (point) (match-end 4))))
7619 (if (looking-at "[ \t]*$") (replace-match "")
7620 (org-align-tags))
7621 (end-of-line)
7622 (when blank? (insert "\n"))
7623 (insert "\n" stars " ")
7624 (when (org-string-nw-p split) (insert split))
7625 (when (eobp) (save-excursion (insert "\n")))))
7627 (end-of-line)
7628 (when blank? (insert "\n"))
7629 (insert "\n" stars " ")
7630 (when (eobp) (save-excursion (insert "\n"))))))
7631 ;; On regular text, turn line into a headline or split, if
7632 ;; appropriate.
7633 ((bolp)
7634 (insert stars " ")
7635 (unless (and blank? (org-previous-line-empty-p))
7636 (org-N-empty-lines-before-current (if blank? 1 0))))
7638 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7639 (end-of-line))
7640 (insert "\n" stars " ")
7641 (unless (and blank? (org-previous-line-empty-p))
7642 (org-N-empty-lines-before-current (if blank? 1 0))))))
7643 (run-hooks 'org-insert-heading-hook))
7645 (defun org-N-empty-lines-before-current (n)
7646 "Make the number of empty lines before current exactly N.
7647 So this will delete or add empty lines."
7648 (let ((column (current-column)))
7649 (beginning-of-line)
7650 (unless (bobp)
7651 (let ((start (save-excursion
7652 (skip-chars-backward " \r\t\n")
7653 (line-end-position))))
7654 (delete-region start (line-end-position 0))))
7655 (insert (make-string n ?\n))
7656 (move-to-column column)))
7658 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7659 "Return the heading of the current entry, without the stars.
7660 When NO-TAGS is non-nil, don't include tags.
7661 When NO-TODO is non-nil, don't include TODO keywords.
7662 When NO-PRIORITY is non-nil, don't include priority cookie.
7663 When NO-COMMENT is non-nil, don't include COMMENT string."
7664 (save-excursion
7665 (org-back-to-heading t)
7666 (let ((case-fold-search nil))
7667 (looking-at org-complex-heading-regexp)
7668 (let ((todo (and (not no-todo) (match-string 2)))
7669 (priority (and (not no-priority) (match-string 3)))
7670 (headline (pcase (match-string 4)
7671 (`nil "")
7672 ((and (guard no-comment) h)
7673 (replace-regexp-in-string
7674 (eval-when-compile
7675 (format "\\`%s[ \t]+" org-comment-string))
7676 "" h))
7677 (h h)))
7678 (tags (and (not no-tags) (match-string 5))))
7679 (mapconcat #'identity
7680 (delq nil (list todo priority headline tags))
7681 " ")))))
7683 (defun org-heading-components ()
7684 "Return the components of the current heading.
7685 This is a list with the following elements:
7686 - the level as an integer
7687 - the reduced level, different if `org-odd-levels-only' is set.
7688 - the TODO keyword, or nil
7689 - the priority character, like ?A, or nil if no priority is given
7690 - the headline text itself, or the tags string if no headline text
7691 - the tags string, or nil."
7692 (save-excursion
7693 (org-back-to-heading t)
7694 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7695 (list (length (match-string 1))
7696 (org-reduced-level (length (match-string 1)))
7697 (match-string-no-properties 2)
7698 (and (match-end 3) (aref (match-string 3) 2))
7699 (match-string-no-properties 4)
7700 (match-string-no-properties 5)))))
7702 (defun org-get-entry ()
7703 "Get the entry text, after heading, entire subtree."
7704 (save-excursion
7705 (org-back-to-heading t)
7706 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7708 (defun org-edit-headline (&optional heading)
7709 "Edit the current headline.
7710 Set it to HEADING when provided."
7711 (interactive)
7712 (org-with-wide-buffer
7713 (org-back-to-heading t)
7714 (let ((case-fold-search nil))
7715 (when (looking-at org-complex-heading-regexp)
7716 (let* ((old (match-string-no-properties 4))
7717 (new (save-match-data
7718 (org-trim (or heading (read-string "Edit: " old))))))
7719 (unless (equal old new)
7720 (if old (replace-match new t t nil 4)
7721 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7722 (insert " " new))
7723 (org-align-tags)
7724 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7726 (defun org-insert-heading-after-current ()
7727 "Insert a new heading with same level as current, after current subtree."
7728 (interactive)
7729 (org-back-to-heading)
7730 (org-insert-heading)
7731 (org-move-subtree-down)
7732 (end-of-line 1))
7734 (defun org-insert-heading-respect-content (&optional invisible-ok)
7735 "Insert heading with `org-insert-heading-respect-content' set to t."
7736 (interactive)
7737 (org-insert-heading '(4) invisible-ok))
7739 (defun org-insert-todo-heading-respect-content (&optional force-state)
7740 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7741 (interactive)
7742 (org-insert-todo-heading force-state '(4)))
7744 (defun org-insert-todo-heading (arg &optional force-heading)
7745 "Insert a new heading with the same level and TODO state as current heading.
7747 If the heading has no TODO state, or if the state is DONE, use
7748 the first state (TODO by default). Also with one prefix arg,
7749 force first state. With two prefix args, force inserting at the
7750 end of the parent subtree.
7752 When called at a plain list item, insert a new item with an
7753 unchecked check box."
7754 (interactive "P")
7755 (when (or force-heading (not (org-insert-item 'checkbox)))
7756 (org-insert-heading (or (and (equal arg '(16)) '(16))
7757 force-heading))
7758 (save-excursion
7759 (org-forward-heading-same-level -1)
7760 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7761 (let* ((new-mark-x
7762 (if (or (equal arg '(4))
7763 (not (match-beginning 2))
7764 (member (match-string 2) org-done-keywords))
7765 (car org-todo-keywords-1)
7766 (match-string 2)))
7767 (new-mark
7769 (run-hook-with-args-until-success
7770 'org-todo-get-default-hook new-mark-x nil)
7771 new-mark-x)))
7772 (beginning-of-line 1)
7773 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7774 (if org-treat-insert-todo-heading-as-state-change
7775 (org-todo new-mark)
7776 (insert new-mark " "))))
7777 (when org-provide-todo-statistics
7778 (org-update-parent-todo-statistics))))
7780 (defun org-insert-subheading (arg)
7781 "Insert a new subheading and demote it.
7782 Works for outline headings and for plain lists alike."
7783 (interactive "P")
7784 (org-insert-heading arg)
7785 (cond
7786 ((org-at-heading-p) (org-do-demote))
7787 ((org-at-item-p) (org-indent-item))))
7789 (defun org-insert-todo-subheading (arg)
7790 "Insert a new subheading with TODO keyword or checkbox and demote it.
7791 Works for outline headings and for plain lists alike."
7792 (interactive "P")
7793 (org-insert-todo-heading arg)
7794 (cond
7795 ((org-at-heading-p) (org-do-demote))
7796 ((org-at-item-p) (org-indent-item))))
7798 ;;; Promotion and Demotion
7800 (defvar org-after-demote-entry-hook nil
7801 "Hook run after an entry has been demoted.
7802 The cursor will be at the beginning of the entry.
7803 When a subtree is being demoted, the hook will be called for each node.")
7805 (defvar org-after-promote-entry-hook nil
7806 "Hook run after an entry has been promoted.
7807 The cursor will be at the beginning of the entry.
7808 When a subtree is being promoted, the hook will be called for each node.")
7810 (defun org-promote-subtree ()
7811 "Promote the entire subtree.
7812 See also `org-promote'."
7813 (interactive)
7814 (save-excursion
7815 (org-with-limited-levels (org-map-tree 'org-promote)))
7816 (org-fix-position-after-promote))
7818 (defun org-demote-subtree ()
7819 "Demote the entire subtree.
7820 See `org-demote' and `org-promote'."
7821 (interactive)
7822 (save-excursion
7823 (org-with-limited-levels (org-map-tree 'org-demote)))
7824 (org-fix-position-after-promote))
7826 (defun org-do-promote ()
7827 "Promote the current heading higher up the tree.
7828 If the region is active in `transient-mark-mode', promote all
7829 headings in the region."
7830 (interactive)
7831 (save-excursion
7832 (if (org-region-active-p)
7833 (org-map-region 'org-promote (region-beginning) (region-end))
7834 (org-promote)))
7835 (org-fix-position-after-promote))
7837 (defun org-do-demote ()
7838 "Demote the current heading lower down the tree.
7839 If the region is active in `transient-mark-mode', demote all
7840 headings in the region."
7841 (interactive)
7842 (save-excursion
7843 (if (org-region-active-p)
7844 (org-map-region 'org-demote (region-beginning) (region-end))
7845 (org-demote)))
7846 (org-fix-position-after-promote))
7848 (defun org-fix-position-after-promote ()
7849 "Fix cursor position and indentation after demoting/promoting."
7850 (let ((pos (point)))
7851 (when (save-excursion
7852 (beginning-of-line)
7853 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7854 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7855 (cond ((eobp) (insert " "))
7856 ((eolp) (insert " "))
7857 ((equal (char-after) ?\s) (forward-char 1))))))
7859 (defun org-current-level ()
7860 "Return the level of the current entry, or nil if before the first headline.
7861 The level is the number of stars at the beginning of the
7862 headline. Use `org-reduced-level' to remove the effect of
7863 `org-odd-levels'. Unlike to `org-outline-level', this function
7864 ignores inlinetasks."
7865 (let ((level (org-with-limited-levels (org-outline-level))))
7866 (and (> level 0) level)))
7868 (defun org-get-previous-line-level ()
7869 "Return the outline depth of the last headline before the current line.
7870 Returns 0 for the first headline in the buffer, and nil if before the
7871 first headline."
7872 (and (org-current-level)
7873 (or (and (/= (line-beginning-position) (point-min))
7874 (save-excursion (beginning-of-line 0) (org-current-level)))
7875 0)))
7877 (defun org-reduced-level (l)
7878 "Compute the effective level of a heading.
7879 This takes into account the setting of `org-odd-levels-only'."
7880 (cond
7881 ((zerop l) 0)
7882 (org-odd-levels-only (1+ (floor (/ l 2))))
7883 (t l)))
7885 (defun org-level-increment ()
7886 "Return the number of stars that will be added or removed at a
7887 time to headlines when structure editing, based on the value of
7888 `org-odd-levels-only'."
7889 (if org-odd-levels-only 2 1))
7891 (defun org-get-valid-level (level &optional change)
7892 "Rectify a level change under the influence of `org-odd-levels-only'.
7893 LEVEL is a current level, CHANGE is by how much the level should
7894 be modified. Even if CHANGE is nil, LEVEL may be returned
7895 modified because even level numbers will become the next higher
7896 odd number. Returns values greater than 0."
7897 (if org-odd-levels-only
7898 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7899 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7900 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7901 (max 1 (+ level (or change 0)))))
7903 (defun org-promote ()
7904 "Promote the current heading higher up the tree."
7905 (org-with-wide-buffer
7906 (org-back-to-heading t)
7907 (let* ((after-change-functions (remq 'flyspell-after-change-function
7908 after-change-functions))
7909 (level (save-match-data (funcall outline-level)))
7910 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7911 (diff (abs (- level (length up-head) -1))))
7912 (cond
7913 ((and (= level 1) org-allow-promoting-top-level-subtree)
7914 (replace-match "# " nil t))
7915 ((= level 1)
7916 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7917 (t (replace-match up-head nil t)))
7918 (unless (= level 1)
7919 (when org-auto-align-tags (org-align-tags))
7920 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7921 (run-hooks 'org-after-promote-entry-hook))))
7923 (defun org-demote ()
7924 "Demote the current heading lower down the tree."
7925 (org-with-wide-buffer
7926 (org-back-to-heading t)
7927 (let* ((after-change-functions (remq 'flyspell-after-change-function
7928 after-change-functions))
7929 (level (save-match-data (funcall outline-level)))
7930 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7931 (diff (abs (- level (length down-head) -1))))
7932 (replace-match down-head nil t)
7933 (when org-auto-align-tags (org-align-tags))
7934 (when org-adapt-indentation (org-fixup-indentation diff))
7935 (run-hooks 'org-after-demote-entry-hook))))
7937 (defun org-cycle-level ()
7938 "Cycle the level of an empty headline through possible states.
7939 This goes first to child, then to parent, level, then up the hierarchy.
7940 After top level, it switches back to sibling level."
7941 (interactive)
7942 (let ((org-adapt-indentation nil))
7943 (when (org-point-at-end-of-empty-headline)
7944 (setq this-command 'org-cycle-level) ; Only needed for caching
7945 (let ((cur-level (org-current-level))
7946 (prev-level (org-get-previous-line-level)))
7947 (cond
7948 ;; If first headline in file, promote to top-level.
7949 ((= prev-level 0)
7950 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7951 do (org-do-promote)))
7952 ;; If same level as prev, demote one.
7953 ((= prev-level cur-level)
7954 (org-do-demote))
7955 ;; If parent is top-level, promote to top level if not already.
7956 ((= prev-level 1)
7957 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7958 do (org-do-promote)))
7959 ;; If top-level, return to prev-level.
7960 ((= cur-level 1)
7961 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7962 do (org-do-demote)))
7963 ;; If less than prev-level, promote one.
7964 ((< cur-level prev-level)
7965 (org-do-promote))
7966 ;; If deeper than prev-level, promote until higher than
7967 ;; prev-level.
7968 ((> cur-level prev-level)
7969 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7970 do (org-do-promote))))
7971 t))))
7973 (defun org-map-tree (fun)
7974 "Call FUN for every heading underneath the current one."
7975 (org-back-to-heading t)
7976 (let ((level (funcall outline-level)))
7977 (save-excursion
7978 (funcall fun)
7979 (while (and (progn
7980 (outline-next-heading)
7981 (> (funcall outline-level) level))
7982 (not (eobp)))
7983 (funcall fun)))))
7985 (defun org-map-region (fun beg end)
7986 "Call FUN for every heading between BEG and END."
7987 (let ((org-ignore-region t))
7988 (save-excursion
7989 (setq end (copy-marker end))
7990 (goto-char beg)
7991 (when (and (re-search-forward org-outline-regexp-bol nil t)
7992 (< (point) end))
7993 (funcall fun))
7994 (while (and (progn
7995 (outline-next-heading)
7996 (< (point) end))
7997 (not (eobp)))
7998 (funcall fun)))))
8000 (defun org-fixup-indentation (diff)
8001 "Change the indentation in the current entry by DIFF.
8003 DIFF is an integer. Indentation is done according to the
8004 following rules:
8006 - Planning information and property drawers are always indented
8007 according to the new level of the headline;
8009 - Footnote definitions and their contents are ignored;
8011 - Inlinetasks' boundaries are not shifted;
8013 - Empty lines are ignored;
8015 - Other lines' indentation are shifted by DIFF columns, unless
8016 it would introduce a structural change in the document, in
8017 which case no shifting is done at all.
8019 Assume point is at a heading or an inlinetask beginning."
8020 (org-with-wide-buffer
8021 (narrow-to-region (line-beginning-position)
8022 (save-excursion
8023 (if (org-with-limited-levels (org-at-heading-p))
8024 (org-with-limited-levels (outline-next-heading))
8025 (org-inlinetask-goto-end))
8026 (point)))
8027 (forward-line)
8028 ;; Indent properly planning info and property drawer.
8029 (when (looking-at-p org-planning-line-re)
8030 (org-indent-line)
8031 (forward-line))
8032 (when (looking-at org-property-drawer-re)
8033 (goto-char (match-end 0))
8034 (forward-line)
8035 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8036 (catch 'no-shift
8037 (when (zerop diff) (throw 'no-shift nil))
8038 ;; If DIFF is negative, first check if a shift is possible at all
8039 ;; (e.g., it doesn't break structure). This can only happen if
8040 ;; some contents are not properly indented.
8041 (let ((case-fold-search t))
8042 (when (< diff 0)
8043 (let ((diff (- diff))
8044 (forbidden-re (concat org-outline-regexp
8045 "\\|"
8046 (substring org-footnote-definition-re 1))))
8047 (save-excursion
8048 (while (not (eobp))
8049 (cond
8050 ((looking-at-p "[ \t]*$") (forward-line))
8051 ((and (looking-at-p org-footnote-definition-re)
8052 (let ((e (org-element-at-point)))
8053 (and (eq (org-element-type e) 'footnote-definition)
8054 (goto-char (org-element-property :end e))))))
8055 ((looking-at-p org-outline-regexp) (forward-line))
8056 ;; Give up if shifting would move before column 0 or
8057 ;; if it would introduce a headline or a footnote
8058 ;; definition.
8060 (skip-chars-forward " \t")
8061 (let ((ind (current-column)))
8062 (when (or (< ind diff)
8063 (and (= ind diff) (looking-at-p forbidden-re)))
8064 (throw 'no-shift nil)))
8065 ;; Ignore contents of example blocks and source
8066 ;; blocks if their indentation is meant to be
8067 ;; preserved. Jump to block's closing line.
8068 (beginning-of-line)
8069 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8070 (let ((e (org-element-at-point)))
8071 (and (memq (org-element-type e)
8072 '(example-block src-block))
8073 (or org-src-preserve-indentation
8074 (org-element-property :preserve-indent e))
8075 (goto-char (org-element-property :end e))
8076 (progn (skip-chars-backward " \r\t\n")
8077 (beginning-of-line)
8078 t))))
8079 (forward-line))))))))
8080 ;; Shift lines but footnote definitions, inlinetasks boundaries
8081 ;; by DIFF. Also skip contents of source or example blocks
8082 ;; when indentation is meant to be preserved.
8083 (while (not (eobp))
8084 (cond
8085 ((and (looking-at-p org-footnote-definition-re)
8086 (let ((e (org-element-at-point)))
8087 (and (eq (org-element-type e) 'footnote-definition)
8088 (goto-char (org-element-property :end e))))))
8089 ((looking-at-p org-outline-regexp) (forward-line))
8090 ((looking-at-p "[ \t]*$") (forward-line))
8092 (indent-line-to (+ (org-get-indentation) diff))
8093 (beginning-of-line)
8094 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8095 (let ((e (org-element-at-point)))
8096 (and (memq (org-element-type e)
8097 '(example-block src-block))
8098 (or org-src-preserve-indentation
8099 (org-element-property :preserve-indent e))
8100 (goto-char (org-element-property :end e))
8101 (progn (skip-chars-backward " \r\t\n")
8102 (beginning-of-line)
8103 t))))
8104 (forward-line)))))))))
8106 (defun org-convert-to-odd-levels ()
8107 "Convert an Org file with all levels allowed to one with odd levels.
8108 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8109 level 5 etc."
8110 (interactive)
8111 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8112 (let ((outline-level 'org-outline-level)
8113 (org-odd-levels-only nil) n)
8114 (save-excursion
8115 (goto-char (point-min))
8116 (while (re-search-forward "^\\*\\*+ " nil t)
8117 (setq n (- (length (match-string 0)) 2))
8118 (while (>= (setq n (1- n)) 0)
8119 (org-demote))
8120 (end-of-line 1))))))
8122 (defun org-convert-to-oddeven-levels ()
8123 "Convert an Org file with only odd levels to one with odd/even levels.
8124 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8125 file contains a section with an even level, conversion would
8126 destroy the structure of the file. An error is signaled in this
8127 case."
8128 (interactive)
8129 (goto-char (point-min))
8130 ;; First check if there are no even levels
8131 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8132 (org-show-set-visibility 'canonical)
8133 (error "Not all levels are odd in this file. Conversion not possible"))
8134 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8135 (let ((outline-regexp org-outline-regexp)
8136 (outline-level 'org-outline-level)
8137 (org-odd-levels-only nil) n)
8138 (save-excursion
8139 (goto-char (point-min))
8140 (while (re-search-forward "^\\*\\*+ " nil t)
8141 (setq n (/ (1- (length (match-string 0))) 2))
8142 (while (>= (setq n (1- n)) 0)
8143 (org-promote))
8144 (end-of-line 1))))))
8146 (defun org-tr-level (n)
8147 "Make N odd if required."
8148 (if org-odd-levels-only (1+ (/ n 2)) n))
8150 ;;; Vertical tree motion, cutting and pasting of subtrees
8152 (defun org-move-subtree-up (&optional arg)
8153 "Move the current subtree up past ARG headlines of the same level."
8154 (interactive "p")
8155 (org-move-subtree-down (- (prefix-numeric-value arg))))
8157 (defun org-move-subtree-down (&optional arg)
8158 "Move the current subtree down past ARG headlines of the same level."
8159 (interactive "p")
8160 (setq arg (prefix-numeric-value arg))
8161 (org-preserve-local-variables
8162 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8163 'org-get-last-sibling))
8164 (ins-point (make-marker))
8165 (cnt (abs arg))
8166 (col (current-column))
8167 beg end txt folded)
8168 ;; Select the tree
8169 (org-back-to-heading)
8170 (setq beg (point))
8171 (save-match-data
8172 (save-excursion (outline-end-of-heading)
8173 (setq folded (org-invisible-p)))
8174 (progn (org-end-of-subtree nil t)
8175 (unless (eobp) (backward-char))))
8176 (outline-next-heading)
8177 (setq end (point))
8178 (goto-char beg)
8179 ;; Find insertion point, with error handling
8180 (while (> cnt 0)
8181 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8182 (goto-char beg)
8183 (user-error "Cannot move past superior level or buffer limit"))
8184 (setq cnt (1- cnt)))
8185 (when (> arg 0)
8186 ;; Moving forward - still need to move over subtree
8187 (org-end-of-subtree t t)
8188 (save-excursion
8189 (org-back-over-empty-lines)
8190 (or (bolp) (newline))))
8191 (move-marker ins-point (point))
8192 (setq txt (buffer-substring beg end))
8193 (org-save-markers-in-region beg end)
8194 (delete-region beg end)
8195 (org-remove-empty-overlays-at beg)
8196 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8197 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8198 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8199 (let ((bbb (point)))
8200 (insert-before-markers txt)
8201 (org-reinstall-markers-in-region bbb)
8202 (move-marker ins-point bbb))
8203 (or (bolp) (insert "\n"))
8204 (goto-char ins-point)
8205 (org-skip-whitespace)
8206 (move-marker ins-point nil)
8207 (if folded
8208 (outline-hide-subtree)
8209 (org-show-entry)
8210 (org-show-children))
8211 (org-clean-visibility-after-subtree-move)
8212 ;; move back to the initial column we were at
8213 (move-to-column col))))
8215 (defvar org-subtree-clip ""
8216 "Clipboard for cut and paste of subtrees.
8217 This is actually only a copy of the kill, because we use the normal kill
8218 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8220 (defvar org-subtree-clip-folded nil
8221 "Was the last copied subtree folded?
8222 This is used to fold the tree back after pasting.")
8224 (defun org-cut-subtree (&optional n)
8225 "Cut the current subtree into the clipboard.
8226 With prefix arg N, cut this many sequential subtrees.
8227 This is a short-hand for marking the subtree and then cutting it."
8228 (interactive "p")
8229 (org-copy-subtree n 'cut))
8231 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8232 "Copy the current subtree into the clipboard.
8233 With prefix arg N, copy this many sequential subtrees.
8234 This is a short-hand for marking the subtree and then copying it.
8235 If CUT is non-nil, actually cut the subtree.
8236 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8237 of some markers in the region, even if CUT is non-nil. This is
8238 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8239 (interactive "p")
8240 (org-preserve-local-variables
8241 (let (beg end folded (beg0 (point)))
8242 (if (called-interactively-p 'any)
8243 (org-back-to-heading nil) ; take what looks like a subtree
8244 (org-back-to-heading t)) ; take what is really there
8245 (setq beg (point))
8246 (skip-chars-forward " \t\r\n")
8247 (save-match-data
8248 (if nosubtrees
8249 (outline-next-heading)
8250 (save-excursion (outline-end-of-heading)
8251 (setq folded (org-invisible-p)))
8252 (ignore-errors (org-forward-heading-same-level (1- n) t))
8253 (org-end-of-subtree t t)))
8254 ;; Include the end of an inlinetask
8255 (when (and (featurep 'org-inlinetask)
8256 (looking-at-p (concat (org-inlinetask-outline-regexp)
8257 "END[ \t]*$")))
8258 (end-of-line))
8259 (setq end (point))
8260 (goto-char beg0)
8261 (when (> end beg)
8262 (setq org-subtree-clip-folded folded)
8263 (when (or cut force-store-markers)
8264 (org-save-markers-in-region beg end))
8265 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8266 (setq org-subtree-clip (current-kill 0))
8267 (message "%s: Subtree(s) with %d characters"
8268 (if cut "Cut" "Copied")
8269 (length org-subtree-clip))))))
8271 (defun org-paste-subtree (&optional level tree for-yank remove)
8272 "Paste the clipboard as a subtree, with modification of headline level.
8274 The entire subtree is promoted or demoted in order to match a new headline
8275 level.
8277 If the cursor is at the beginning of a headline, the same level as
8278 that headline is used to paste the tree.
8280 If not, the new level is derived from the *visible* headings
8281 before and after the insertion point, and taken to be the inferior headline
8282 level of the two. So if the previous visible heading is level 3 and the
8283 next is level 4 (or vice versa), level 4 will be used for insertion.
8284 This makes sure that the subtree remains an independent subtree and does
8285 not swallow low level entries.
8287 You can also force a different level, either by using a numeric prefix
8288 argument, or by inserting the heading marker by hand. For example, if the
8289 cursor is after \"*****\", then the tree will be shifted to level 5.
8291 If optional TREE is given, use this text instead of the kill ring.
8293 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8294 move back over whitespace before inserting, and move point to the end of
8295 the inserted text when done.
8297 When REMOVE is non-nil, remove the subtree from the clipboard."
8298 (interactive "P")
8299 (setq tree (or tree (and kill-ring (current-kill 0))))
8300 (unless (org-kill-is-subtree-p tree)
8301 (user-error
8302 (substitute-command-keys
8303 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8304 (org-with-limited-levels
8305 (let* ((visp (not (org-invisible-p)))
8306 (txt tree)
8307 (old-level (if (string-match org-outline-regexp-bol txt)
8308 (- (match-end 0) (match-beginning 0) 1)
8309 -1))
8310 (force-level
8311 (cond
8312 (level (prefix-numeric-value level))
8313 ;; When point is right after the stars in an otherwise
8314 ;; empty headline, use stars as the forced level.
8315 ((and (looking-at-p "[ \t]*$")
8316 (string-match-p "^\\*+ *"
8317 (buffer-substring (line-beginning-position)
8318 (point))))
8319 (org-outline-level))
8320 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8321 (previous-level
8322 (save-excursion
8323 (org-previous-visible-heading 1)
8324 (if (org-at-heading-p) (org-outline-level) 1)))
8325 (next-level
8326 (save-excursion
8327 (if (org-at-heading-p) (org-outline-level)
8328 (org-next-visible-heading 1)
8329 (if (org-at-heading-p) (org-outline-level) 1))))
8330 (new-level (or force-level (max previous-level next-level)))
8331 (shift (if (or (= old-level -1)
8332 (= new-level -1)
8333 (= old-level new-level))
8335 (- new-level old-level)))
8336 (delta (if (> shift 0) -1 1))
8337 (func (if (> shift 0) #'org-demote #'org-promote))
8338 (org-odd-levels-only nil)
8339 beg end newend)
8340 ;; Remove the forced level indicator.
8341 (when (and force-level (not level))
8342 (delete-region (line-beginning-position) (point)))
8343 ;; Paste before the next visible heading or at end of buffer,
8344 ;; unless point is at the beginning of a headline.
8345 (unless (and (bolp) (org-at-heading-p))
8346 (org-next-visible-heading 1)
8347 (unless (bolp) (insert "\n")))
8348 (setq beg (point))
8349 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8350 (insert-before-markers txt)
8351 (unless (string-suffix-p "\n" txt) (insert "\n"))
8352 (setq newend (point))
8353 (org-reinstall-markers-in-region beg)
8354 (setq end (point))
8355 (goto-char beg)
8356 (skip-chars-forward " \t\n\r")
8357 (setq beg (point))
8358 (when (and (org-invisible-p) visp)
8359 (save-excursion (outline-show-heading)))
8360 ;; Shift if necessary.
8361 (unless (= shift 0)
8362 (save-restriction
8363 (narrow-to-region beg end)
8364 (while (not (= shift 0))
8365 (org-map-region func (point-min) (point-max))
8366 (setq shift (+ delta shift)))
8367 (goto-char (point-min))
8368 (setq newend (point-max))))
8369 (when (or for-yank (called-interactively-p 'interactive))
8370 (message "Clipboard pasted as level %d subtree" new-level))
8371 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8372 kill-ring
8373 (equal org-subtree-clip (current-kill 0))
8374 org-subtree-clip-folded)
8375 ;; The tree was folded before it was killed/copied
8376 (outline-hide-subtree))
8377 (when for-yank (goto-char newend))
8378 (when remove (pop kill-ring)))))
8380 (defun org-kill-is-subtree-p (&optional txt)
8381 "Check if the current kill is an outline subtree, or a set of trees.
8382 Returns nil if kill does not start with a headline, or if the first
8383 headline level is not the largest headline level in the tree.
8384 So this will actually accept several entries of equal levels as well,
8385 which is OK for `org-paste-subtree'.
8386 If optional TXT is given, check this string instead of the current kill."
8387 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8388 (re (org-get-limited-outline-regexp))
8389 (^re (concat "^" re))
8390 (start-level (and kill
8391 (string-match
8392 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8393 kill)
8394 (- (match-end 2) (match-beginning 2) 1)))
8395 (start (1+ (or (match-beginning 2) -1))))
8396 (if (not start-level)
8397 (progn
8398 nil) ;; does not even start with a heading
8399 (catch 'exit
8400 (while (setq start (string-match ^re kill (1+ start)))
8401 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8402 (throw 'exit nil)))
8403 t))))
8405 (defvar org-markers-to-move nil
8406 "Markers that should be moved with a cut-and-paste operation.
8407 Those markers are stored together with their positions relative to
8408 the start of the region.")
8410 (defun org-save-markers-in-region (beg end)
8411 "Check markers in region.
8412 If these markers are between BEG and END, record their position relative
8413 to BEG, so that after moving the block of text, we can put the markers back
8414 into place.
8415 This function gets called just before an entry or tree gets cut from the
8416 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8417 called immediately, to move the markers with the entries."
8418 (setq org-markers-to-move nil)
8419 (when (featurep 'org-clock)
8420 (org-clock-save-markers-for-cut-and-paste beg end))
8421 (when (featurep 'org-agenda)
8422 (org-agenda-save-markers-for-cut-and-paste beg end)))
8424 (defun org-check-and-save-marker (marker beg end)
8425 "Check if MARKER is between BEG and END.
8426 If yes, remember the marker and the distance to BEG."
8427 (when (and (marker-buffer marker)
8428 (equal (marker-buffer marker) (current-buffer))
8429 (>= marker beg) (< marker end))
8430 (push (cons marker (- marker beg)) org-markers-to-move)))
8432 (defun org-reinstall-markers-in-region (beg)
8433 "Move all remembered markers to their position relative to BEG."
8434 (dolist (x org-markers-to-move)
8435 (move-marker (car x) (+ beg (cdr x))))
8436 (setq org-markers-to-move nil))
8438 (defun org-narrow-to-subtree ()
8439 "Narrow buffer to the current subtree."
8440 (interactive)
8441 (save-excursion
8442 (save-match-data
8443 (org-with-limited-levels
8444 (narrow-to-region
8445 (progn (org-back-to-heading t) (point))
8446 (progn (org-end-of-subtree t t)
8447 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8448 (point)))))))
8450 (defun org-toggle-narrow-to-subtree ()
8451 "Narrow to the subtree at point or widen a narrowed buffer."
8452 (interactive)
8453 (if (buffer-narrowed-p)
8454 (widen)
8455 (org-narrow-to-subtree)))
8457 (defun org-narrow-to-block ()
8458 "Narrow buffer to the current block."
8459 (interactive)
8460 (let* ((case-fold-search t)
8461 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8462 "^[ \t]*#\\+end_.*")))
8463 (if blockp
8464 (narrow-to-region (car blockp) (cdr blockp))
8465 (user-error "Not in a block"))))
8467 (defun org-clone-subtree-with-time-shift (n &optional shift)
8468 "Clone the task (subtree) at point N times.
8469 The clones will be inserted as siblings.
8471 In interactive use, the user will be prompted for the number of
8472 clones to be produced. If the entry has a timestamp, the user
8473 will also be prompted for a time shift, which may be a repeater
8474 as used in time stamps, for example `+3d'. To disable this,
8475 you can call the function with a universal prefix argument.
8477 When a valid repeater is given and the entry contains any time
8478 stamps, the clones will become a sequence in time, with time
8479 stamps in the subtree shifted for each clone produced. If SHIFT
8480 is nil or the empty string, time stamps will be left alone. The
8481 ID property of the original subtree is removed.
8483 In each clone, all the CLOCK entries will be removed. This
8484 prevents Org from considering that the clocked times overlap.
8486 If the original subtree did contain time stamps with a repeater,
8487 the following will happen:
8488 - the repeater will be removed in each clone
8489 - an additional clone will be produced, with the current, unshifted
8490 date(s) in the entry.
8491 - the original entry will be placed *after* all the clones, with
8492 repeater intact.
8493 - the start days in the repeater in the original entry will be shifted
8494 to past the last clone.
8495 In this way you can spell out a number of instances of a repeating task,
8496 and still retain the repeater to cover future instances of the task.
8498 As described above, N+1 clones are produced when the original
8499 subtree has a repeater. Setting N to 0, then, can be used to
8500 remove the repeater from a subtree and create a shifted clone
8501 with the original repeater."
8502 (interactive "nNumber of clones to produce: ")
8503 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8504 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8505 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8506 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8507 (shift
8508 (or shift
8509 (if (and (not (equal current-prefix-arg '(4)))
8510 (save-excursion
8511 (goto-char beg)
8512 (re-search-forward org-ts-regexp-both end-of-tree t)))
8513 (read-from-minibuffer
8514 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8515 ""))) ;No time shift
8516 (doshift
8517 (and (org-string-nw-p shift)
8518 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8519 shift)
8520 (user-error "Invalid shift specification %s" shift)))))
8521 (goto-char end-of-tree)
8522 (unless (bolp) (insert "\n"))
8523 (let* ((end (point))
8524 (template (buffer-substring beg end))
8525 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8526 (shift-what (pcase (and doshift (match-string 2 shift))
8527 (`nil nil)
8528 ("d" 'day)
8529 ("w" (setq shift-n (* 7 shift-n)) 'day)
8530 ("m" 'month)
8531 ("y" 'year)
8532 (_ (error "Unsupported time unit"))))
8533 (nmin 1)
8534 (nmax n)
8535 (n-no-remove -1)
8536 (idprop (org-entry-get nil "ID")))
8537 (when (and doshift
8538 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8539 template))
8540 (delete-region beg end)
8541 (setq end beg)
8542 (setq nmin 0)
8543 (setq nmax (1+ nmax))
8544 (setq n-no-remove nmax))
8545 (goto-char end)
8546 (cl-loop for n from nmin to nmax do
8547 (insert
8548 ;; Prepare clone.
8549 (with-temp-buffer
8550 (insert template)
8551 (org-mode)
8552 (goto-char (point-min))
8553 (org-show-subtree)
8554 (and idprop (if org-clone-delete-id
8555 (org-entry-delete nil "ID")
8556 (org-id-get-create t)))
8557 (unless (= n 0)
8558 (while (re-search-forward org-clock-line-re nil t)
8559 (delete-region (line-beginning-position)
8560 (line-beginning-position 2)))
8561 (goto-char (point-min))
8562 (while (re-search-forward org-drawer-regexp nil t)
8563 (org-remove-empty-drawer-at (point))))
8564 (goto-char (point-min))
8565 (when doshift
8566 (while (re-search-forward org-ts-regexp-both nil t)
8567 (org-timestamp-change (* n shift-n) shift-what))
8568 (unless (= n n-no-remove)
8569 (goto-char (point-min))
8570 (while (re-search-forward org-ts-regexp nil t)
8571 (save-excursion
8572 (goto-char (match-beginning 0))
8573 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8574 (delete-region (match-beginning 1) (match-end 1)))))))
8575 (buffer-string)))))
8576 (goto-char beg)))
8578 ;;; Outline Sorting
8580 (defun org-sort (&optional with-case)
8581 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8582 Optional argument WITH-CASE means sort case-sensitively."
8583 (interactive "P")
8584 (org-call-with-arg
8585 (cond ((org-at-table-p) #'org-table-sort-lines)
8586 ((org-at-item-p) #'org-sort-list)
8587 (t #'org-sort-entries))
8588 with-case))
8590 (defun org-sort-remove-invisible (s)
8591 "Remove invisible part of links and emphasis markers from string S."
8592 (remove-text-properties 0 (length s) org-rm-props s)
8593 (replace-regexp-in-string
8594 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8595 (replace-regexp-in-string
8596 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8597 (org-link-display-format s)
8598 t t) t t))
8600 (defvar org-priority-regexp) ; defined later in the file
8602 (defvar org-after-sorting-entries-or-items-hook nil
8603 "Hook that is run after a bunch of entries or items have been sorted.
8604 When children are sorted, the cursor is in the parent line when this
8605 hook gets called. When a region or a plain list is sorted, the cursor
8606 will be in the first entry of the sorted region/list.")
8608 (defun org-sort-entries
8609 (&optional with-case sorting-type getkey-func compare-func property
8610 interactive?)
8611 "Sort entries on a certain level of an outline tree.
8612 If there is an active region, the entries in the region are sorted.
8613 Else, if the cursor is before the first entry, sort the top-level items.
8614 Else, the children of the entry at point are sorted.
8616 Sorting can be alphabetically, numerically, by date/time as given by
8617 a time stamp, by a property, by priority order, or by a custom function.
8619 The command prompts for the sorting type unless it has been given to the
8620 function through the SORTING-TYPE argument, which needs to be a character,
8621 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8622 the precise meaning of each character:
8624 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8625 c By creation time, which is assumed to be the first inactive time stamp
8626 at the beginning of a line.
8627 d By deadline date/time.
8628 k By clocking time.
8629 n Numerically, by converting the beginning of the entry/item to a number.
8630 o By order of TODO keywords.
8631 p By priority according to the cookie.
8632 r By the value of a property.
8633 s By scheduled date/time.
8634 t By date/time, either the first active time stamp in the entry, or, if
8635 none exist, by the first inactive one.
8637 Capital letters will reverse the sort order.
8639 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8640 called with point at the beginning of the record. It must return a
8641 value that is compatible with COMPARE-FUNC, the function used to
8642 compare entries.
8644 Comparing entries ignores case by default. However, with an optional argument
8645 WITH-CASE, the sorting considers case as well.
8647 Sorting is done against the visible part of the headlines, it ignores hidden
8648 links.
8650 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8652 A non-nil value for INTERACTIVE? is used to signal that this
8653 function is being called interactively."
8654 (interactive (list current-prefix-arg nil nil nil nil t))
8655 (let ((case-func (if with-case 'identity 'downcase))
8656 start beg end stars re re2
8657 txt what tmp)
8658 ;; Find beginning and end of region to sort
8659 (cond
8660 ((org-region-active-p)
8661 ;; we will sort the region
8662 (setq end (region-end)
8663 what "region")
8664 (goto-char (region-beginning))
8665 (unless (org-at-heading-p) (outline-next-heading))
8666 (setq start (point)))
8667 ((or (org-at-heading-p)
8668 (ignore-errors (progn (org-back-to-heading) t)))
8669 ;; we will sort the children of the current headline
8670 (org-back-to-heading)
8671 (setq start (point)
8672 end (progn (org-end-of-subtree t t)
8673 (or (bolp) (insert "\n"))
8674 (when (>= (org-back-over-empty-lines) 1)
8675 (forward-line 1))
8676 (point))
8677 what "children")
8678 (goto-char start)
8679 (outline-show-subtree)
8680 (outline-next-heading))
8682 ;; we will sort the top-level entries in this file
8683 (goto-char (point-min))
8684 (or (org-at-heading-p) (outline-next-heading))
8685 (setq start (point))
8686 (goto-char (point-max))
8687 (beginning-of-line 1)
8688 (when (looking-at ".*?\\S-")
8689 ;; File ends in a non-white line
8690 (end-of-line 1)
8691 (insert "\n"))
8692 (setq end (point-max))
8693 (setq what "top-level")
8694 (goto-char start)
8695 (org-show-all '(headings blocks))))
8697 (setq beg (point))
8698 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8700 (looking-at "\\(\\*+\\)")
8701 (setq stars (match-string 1)
8702 re (concat "^" (regexp-quote stars) " +")
8703 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8704 txt (buffer-substring beg end))
8705 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8706 (when (and (not (equal stars "*")) (string-match re2 txt))
8707 (user-error "Region to sort contains a level above the first entry"))
8709 (unless sorting-type
8710 (message
8711 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8712 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8713 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8714 what)
8715 (setq sorting-type (read-char-exclusive)))
8717 (unless getkey-func
8718 (and (= (downcase sorting-type) ?f)
8719 (setq getkey-func
8720 (or (and interactive?
8721 (org-read-function
8722 "Function for extracting keys: "))
8723 (error "Missing key extractor")))))
8725 (and (= (downcase sorting-type) ?r)
8726 (not property)
8727 (setq property
8728 (completing-read "Property: "
8729 (mapcar #'list (org-buffer-property-keys t))
8730 nil t)))
8732 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8733 (message "Sorting entries...")
8735 (save-restriction
8736 (narrow-to-region start end)
8737 (let ((restore-clock?
8738 ;; The clock marker is lost when using `sort-subr'; mark
8739 ;; the clock with temporary `:org-clock-marker-backup'
8740 ;; text property.
8741 (when (and (eq (org-clock-is-active) (current-buffer))
8742 (<= start (marker-position org-clock-marker))
8743 (>= end (marker-position org-clock-marker)))
8744 (org-with-silent-modifications
8745 (put-text-property (1- org-clock-marker) org-clock-marker
8746 :org-clock-marker-backup t))
8748 (dcst (downcase sorting-type))
8749 (case-fold-search nil)
8750 (now (current-time)))
8751 (org-preserve-local-variables
8752 (sort-subr
8753 (/= dcst sorting-type)
8754 ;; This function moves to the beginning character of the
8755 ;; "record" to be sorted.
8756 (lambda nil
8757 (if (re-search-forward re nil t)
8758 (goto-char (match-beginning 0))
8759 (goto-char (point-max))))
8760 ;; This function moves to the last character of the "record" being
8761 ;; sorted.
8762 (lambda nil
8763 (save-match-data
8764 (condition-case nil
8765 (outline-forward-same-level 1)
8766 (error
8767 (goto-char (point-max))))))
8768 ;; This function returns the value that gets sorted against.
8769 (lambda ()
8770 (cond
8771 ((= dcst ?n)
8772 (string-to-number
8773 (org-sort-remove-invisible (org-get-heading t t t t))))
8774 ((= dcst ?a)
8775 (funcall case-func
8776 (org-sort-remove-invisible (org-get-heading t t t t))))
8777 ((= dcst ?k)
8778 (or (get-text-property (point) :org-clock-minutes) 0))
8779 ((= dcst ?t)
8780 (let ((end (save-excursion (outline-next-heading) (point))))
8781 (if (or (re-search-forward org-ts-regexp end t)
8782 (re-search-forward org-ts-regexp-both end t))
8783 (org-time-string-to-seconds (match-string 0))
8784 (float-time now))))
8785 ((= dcst ?c)
8786 (let ((end (save-excursion (outline-next-heading) (point))))
8787 (if (re-search-forward
8788 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8789 end t)
8790 (org-time-string-to-seconds (match-string 0))
8791 (float-time now))))
8792 ((= dcst ?s)
8793 (let ((end (save-excursion (outline-next-heading) (point))))
8794 (if (re-search-forward org-scheduled-time-regexp end t)
8795 (org-time-string-to-seconds (match-string 1))
8796 (float-time now))))
8797 ((= dcst ?d)
8798 (let ((end (save-excursion (outline-next-heading) (point))))
8799 (if (re-search-forward org-deadline-time-regexp end t)
8800 (org-time-string-to-seconds (match-string 1))
8801 (float-time now))))
8802 ((= dcst ?p)
8803 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8804 (string-to-char (match-string 2))
8805 org-default-priority))
8806 ((= dcst ?r)
8807 (or (org-entry-get nil property) ""))
8808 ((= dcst ?o)
8809 (when (looking-at org-complex-heading-regexp)
8810 (let* ((m (match-string 2))
8811 (s (if (member m org-done-keywords) '- '+)))
8812 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8813 ((= dcst ?f)
8814 (if getkey-func
8815 (progn
8816 (setq tmp (funcall getkey-func))
8817 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8818 tmp)
8819 (error "Invalid key function `%s'" getkey-func)))
8820 (t (error "Invalid sorting type `%c'" sorting-type))))
8822 (cond
8823 ((= dcst ?a) 'org-string-collate-lessp)
8824 ((= dcst ?f)
8825 (or compare-func
8826 (and interactive?
8827 (org-read-function
8828 (concat "Function for comparing keys "
8829 "(empty for default `sort-subr' predicate): ")
8830 'allow-empty))))
8831 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8832 (when restore-clock?
8833 (move-marker org-clock-marker
8834 (1+ (next-single-property-change
8835 start :org-clock-marker-backup)))
8836 (remove-text-properties (1- org-clock-marker) org-clock-marker
8837 '(:org-clock-marker-backup t)))))
8838 (run-hooks 'org-after-sorting-entries-or-items-hook)
8839 (message "Sorting entries...done")))
8841 (defun org-contextualize-keys (alist contexts)
8842 "Return valid elements in ALIST depending on CONTEXTS.
8844 `org-agenda-custom-commands' or `org-capture-templates' are the
8845 values used for ALIST, and `org-agenda-custom-commands-contexts'
8846 or `org-capture-templates-contexts' are the associated contexts
8847 definitions."
8848 (let ((contexts
8849 ;; normalize contexts
8850 (mapcar
8851 (lambda(c) (cond ((listp (cadr c))
8852 (list (car c) (car c) (nth 1 c)))
8853 ((string= "" (cadr c))
8854 (list (car c) (car c) (nth 2 c)))
8855 (t c)))
8856 contexts))
8857 (a alist) r s)
8858 ;; loop over all commands or templates
8859 (dolist (c a)
8860 (let (vrules repl)
8861 (cond
8862 ((not (assoc (car c) contexts))
8863 (push c r))
8864 ((and (assoc (car c) contexts)
8865 (setq vrules (org-contextualize-validate-key
8866 (car c) contexts)))
8867 (mapc (lambda (vr)
8868 (unless (equal (car vr) (cadr vr))
8869 (setq repl vr)))
8870 vrules)
8871 (if (not repl) (push c r)
8872 (push (cadr repl) s)
8873 (push
8874 (cons (car c)
8875 (cdr (or (assoc (cadr repl) alist)
8876 (error "Undefined key `%s' as contextual replacement for `%s'"
8877 (cadr repl) (car c)))))
8878 r))))))
8879 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8880 (delq
8882 (delete-dups
8883 (mapcar (lambda (x)
8884 (let ((tpl (car x)))
8885 (unless (delq
8887 (mapcar (lambda (y)
8888 (equal y tpl))
8890 x)))
8891 (reverse r))))))
8893 (defun org-contextualize-validate-key (key contexts)
8894 "Check CONTEXTS for agenda or capture KEY."
8895 (let (res)
8896 (dolist (r contexts)
8897 (dolist (rr (car (last r)))
8898 (when
8899 (and (equal key (car r))
8900 (if (functionp rr) (funcall rr)
8901 (or (and (eq (car rr) 'in-file)
8902 (buffer-file-name)
8903 (string-match (cdr rr) (buffer-file-name)))
8904 (and (eq (car rr) 'in-mode)
8905 (string-match (cdr rr) (symbol-name major-mode)))
8906 (and (eq (car rr) 'in-buffer)
8907 (string-match (cdr rr) (buffer-name)))
8908 (when (and (eq (car rr) 'not-in-file)
8909 (buffer-file-name))
8910 (not (string-match (cdr rr) (buffer-file-name))))
8911 (when (eq (car rr) 'not-in-mode)
8912 (not (string-match (cdr rr) (symbol-name major-mode))))
8913 (when (eq (car rr) 'not-in-buffer)
8914 (not (string-match (cdr rr) (buffer-name)))))))
8915 (push r res))))
8916 (delete-dups (delq nil res))))
8918 ;; Defined to provide a value for defcustom, since there is no
8919 ;; string-collate-greaterp in Emacs.
8920 (defun org-string-collate-greaterp (s1 s2)
8921 "Return non-nil if S1 is greater than S2 in collation order."
8922 (not (org-string-collate-lessp s1 s2)))
8924 ;;;###autoload
8925 (defun org-run-like-in-org-mode (cmd)
8926 "Run a command, pretending that the current buffer is in Org mode.
8927 This will temporarily bind local variables that are typically bound in
8928 Org mode to the values they have in Org mode, and then interactively
8929 call CMD."
8930 (org-load-modules-maybe)
8931 (let (binds)
8932 (dolist (var (org-get-local-variables))
8933 (when (or (not (boundp (car var)))
8934 (eq (symbol-value (car var))
8935 (default-value (car var))))
8936 (push (list (car var) `(quote ,(cadr var))) binds)))
8937 (eval `(let ,binds
8938 (call-interactively (quote ,cmd))))))
8940 (defun org-get-category (&optional pos force-refresh)
8941 "Get the category applying to position POS."
8942 (save-match-data
8943 (when force-refresh (org-refresh-category-properties))
8944 (let ((pos (or pos (point))))
8945 (or (get-text-property pos 'org-category)
8946 (progn (org-refresh-category-properties)
8947 (get-text-property pos 'org-category))))))
8949 ;;; Refresh properties
8951 (defun org-refresh-properties (dprop tprop)
8952 "Refresh buffer text properties.
8953 DPROP is the drawer property and TPROP is either the
8954 corresponding text property to set, or an alist with each element
8955 being a text property (as a symbol) and a function to apply to
8956 the value of the drawer property."
8957 (let* ((case-fold-search t)
8958 (inhibit-read-only t)
8959 (inherit? (org-property-inherit-p dprop))
8960 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8961 (global (and inherit? (org--property-global-value dprop nil))))
8962 (org-with-silent-modifications
8963 (org-with-point-at 1
8964 ;; Set global values (e.g., values defined through
8965 ;; "#+PROPERTY:" keywords) to the whole buffer.
8966 (when global (put-text-property (point-min) (point-max) tprop global))
8967 ;; Set local values.
8968 (while (re-search-forward property-re nil t)
8969 (when (org-at-property-p)
8970 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8971 (outline-next-heading))))))
8973 (defun org-refresh-property (tprop p &optional inherit)
8974 "Refresh the buffer text property TPROP from the drawer property P.
8975 The refresh happens only for the current headline, or the whole
8976 sub-tree if optional argument INHERIT is non-nil."
8977 (unless (org-before-first-heading-p)
8978 (save-excursion
8979 (org-back-to-heading t)
8980 (let ((start (point))
8981 (end (save-excursion
8982 (if inherit (org-end-of-subtree t t)
8983 (or (outline-next-heading) (point-max))))))
8984 (if (symbolp tprop)
8985 ;; TPROP is a text property symbol.
8986 (put-text-property start end tprop p)
8987 ;; TPROP is an alist with (property . function) elements.
8988 (pcase-dolist (`(,prop . ,f) tprop)
8989 (put-text-property start end prop (funcall f p))))))))
8991 (defun org-refresh-category-properties ()
8992 "Refresh category text properties in the buffer."
8993 (let ((case-fold-search t)
8994 (inhibit-read-only t)
8995 (default-category
8996 (cond ((null org-category)
8997 (if buffer-file-name
8998 (file-name-sans-extension
8999 (file-name-nondirectory buffer-file-name))
9000 "???"))
9001 ((symbolp org-category) (symbol-name org-category))
9002 (t org-category))))
9003 (org-with-silent-modifications
9004 (org-with-wide-buffer
9005 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9006 ;; This is the default category for the buffer. If none is
9007 ;; found, fall-back to `org-category' or buffer file name.
9008 (put-text-property
9009 (point-min) (point-max)
9010 'org-category
9011 (catch 'buffer-category
9012 (goto-char (point-max))
9013 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9014 (let ((element (org-element-at-point)))
9015 (when (eq (org-element-type element) 'keyword)
9016 (throw 'buffer-category
9017 (org-element-property :value element)))))
9018 default-category))
9019 ;; Set sub-tree specific categories.
9020 (goto-char (point-min))
9021 (let ((regexp (org-re-property "CATEGORY")))
9022 (while (re-search-forward regexp nil t)
9023 (let ((value (match-string-no-properties 3)))
9024 (when (org-at-property-p)
9025 (put-text-property
9026 (save-excursion (org-back-to-heading t) (point))
9027 (save-excursion (org-end-of-subtree t t) (point))
9028 'org-category
9029 value)))))))))
9031 (defun org-refresh-stats-properties ()
9032 "Refresh stats text properties in the buffer."
9033 (org-with-silent-modifications
9034 (org-with-point-at 1
9035 (let ((regexp (concat org-outline-regexp-bol
9036 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9037 (while (re-search-forward regexp nil t)
9038 (let* ((numerator (string-to-number (match-string 1)))
9039 (denominator (and (match-end 2)
9040 (string-to-number (match-string 2))))
9041 (stats (cond ((not denominator) numerator) ;percent
9042 ((= denominator 0) 0)
9043 (t (/ (* numerator 100) denominator)))))
9044 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9045 'org-stats stats)))))))
9047 (defun org-refresh-effort-properties ()
9048 "Refresh effort properties"
9049 (org-refresh-properties
9050 org-effort-property
9051 '((effort . identity)
9052 (effort-minutes . org-duration-to-minutes))))
9054 ;;;; Link Stuff
9056 ;;; Link abbreviations
9058 (defun org-link-expand-abbrev (link)
9059 "Apply replacements as defined in `org-link-abbrev-alist'."
9060 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9061 (let* ((key (match-string 1 link))
9062 (as (or (assoc key org-link-abbrev-alist-local)
9063 (assoc key org-link-abbrev-alist)))
9064 (tag (and (match-end 2) (match-string 3 link)))
9065 rpl)
9066 (if (not as)
9067 link
9068 (setq rpl (cdr as))
9069 (cond
9070 ((symbolp rpl) (funcall rpl tag))
9071 ((string-match "%(\\([^)]+\\))" rpl)
9072 (replace-match
9073 (save-match-data
9074 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9075 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9076 ((string-match "%h" rpl)
9077 (replace-match (url-hexify-string (or tag "")) t t rpl))
9078 (t (concat rpl tag)))))
9079 link))
9081 ;;; Storing and inserting links
9083 (defvar org-insert-link-history nil
9084 "Minibuffer history for links inserted with `org-insert-link'.")
9086 (defvar org-stored-links nil
9087 "Contains the links stored with `org-store-link'.")
9089 (defvar org-store-link-plist nil
9090 "Plist with info about the most recently link created with `org-store-link'.")
9092 (defun org-store-link-functions ()
9093 "Return a list of functions that are called to create and store a link.
9094 The functions defined in the :store property of
9095 `org-link-parameters'.
9097 Each function will be called in turn until one returns a non-nil
9098 value. Each function should check if it is responsible for
9099 creating this link (for example by looking at the major mode).
9100 If not, it must exit and return nil. If yes, it should return
9101 a non-nil value after calling `org-store-link-props' with a list
9102 of properties and values. Special properties are:
9104 :type The link prefix, like \"http\". This must be given.
9105 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9106 This is obligatory as well.
9107 :description Optional default description for the second pair
9108 of brackets in an Org mode link. The user can still change
9109 this when inserting this link into an Org mode buffer.
9111 In addition to these, any additional properties can be specified
9112 and then used in capture templates."
9113 (cl-loop for link in org-link-parameters
9114 with store-func
9115 do (setq store-func (org-link-get-parameter (car link) :store))
9116 if store-func
9117 collect store-func))
9119 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9120 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9122 ;;;###autoload
9123 (defun org-store-link (arg &optional interactive?)
9124 "Store an org-link to the current location.
9125 \\<org-mode-map>
9126 This link is added to `org-stored-links' and can later be inserted
9127 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9129 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9130 A single
9131 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9132 `org-gnus-prefer-web-links' for links to Usenet articles.
9134 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9135 skipping storing functions that are not
9136 part of Org core.
9138 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9139 prefix ARG forces storing a link for each line in the
9140 active region.
9142 Assume the function is called interactively if INTERACTIVE? is
9143 non-nil."
9144 (interactive "P\np")
9145 (org-load-modules-maybe)
9146 (if (and (equal arg '(64)) (org-region-active-p))
9147 (save-excursion
9148 (let ((end (region-end)))
9149 (goto-char (region-beginning))
9150 (set-mark (point))
9151 (while (< (point-at-eol) end)
9152 (move-end-of-line 1) (activate-mark)
9153 (let (current-prefix-arg)
9154 (call-interactively 'org-store-link))
9155 (move-beginning-of-line 2)
9156 (set-mark (point)))))
9157 (setq org-store-link-plist nil)
9158 (let (link cpltxt desc description search txt custom-id agenda-link)
9159 (cond
9160 ;; Store a link using an external link type, if any function is
9161 ;; available. If more than one can generate a link from current
9162 ;; location, ask which one to use.
9163 ((and (not (equal arg '(16)))
9164 (let ((results-alist nil))
9165 (dolist (f (org-store-link-functions))
9166 (when (funcall f)
9167 ;; XXX: return value is not link's plist, so we
9168 ;; store the new value before it is modified. It
9169 ;; would be cleaner to ask store link functions to
9170 ;; return the plist instead.
9171 (push (cons f (copy-sequence org-store-link-plist))
9172 results-alist)))
9173 (pcase results-alist
9174 (`nil nil)
9175 (`((,_ . ,_)) t) ;single choice: nothing to do
9176 (`((,name . ,_) . ,_)
9177 ;; Reinstate link plist associated to the chosen
9178 ;; function.
9179 (apply #'org-store-link-props
9180 (cdr (assoc-string
9181 (completing-read
9182 "Which function for creating the link? "
9183 (mapcar #'car results-alist)
9184 nil t (symbol-name name))
9185 results-alist)))
9186 t))))
9187 (setq link (plist-get org-store-link-plist :link))
9188 (setq desc (or (plist-get org-store-link-plist :description)
9189 link)))
9191 ;; Store a link from a source code buffer.
9192 ((org-src-edit-buffer-p)
9193 (let ((coderef-format (org-src-coderef-format)))
9194 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9195 (setq link (format "(%s)" (match-string-no-properties 3))))
9196 (interactive?
9197 (let ((label (read-string "Code line label: ")))
9198 (end-of-line)
9199 (setq link (format coderef-format label))
9200 (let ((gc (- 79 (length link))))
9201 (if (< (current-column) gc)
9202 (org-move-to-column gc t)
9203 (insert " ")))
9204 (insert link)
9205 (setq link (concat "(" label ")"))
9206 (setq desc nil)))
9207 (t (setq link nil)))))
9209 ;; We are in the agenda, link to referenced location
9210 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9211 (let ((m (or (get-text-property (point) 'org-hd-marker)
9212 (get-text-property (point) 'org-marker))))
9213 (when m
9214 (org-with-point-at m
9215 (setq agenda-link (org-store-link nil interactive?))))))
9217 ((eq major-mode 'calendar-mode)
9218 (let ((cd (calendar-cursor-to-date)))
9219 (setq link
9220 (format-time-string
9221 (car org-time-stamp-formats)
9222 (apply 'encode-time
9223 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9224 nil nil nil))))
9225 (org-store-link-props :type "calendar" :date cd)))
9227 ((eq major-mode 'help-mode)
9228 (setq link (concat "help:" (save-excursion
9229 (goto-char (point-min))
9230 (looking-at "^[^ ]+")
9231 (match-string 0))))
9232 (org-store-link-props :type "help"))
9234 ((eq major-mode 'w3-mode)
9235 (setq cpltxt (if (and (buffer-name)
9236 (not (string-match "Untitled" (buffer-name))))
9237 (buffer-name)
9238 (url-view-url t))
9239 link (url-view-url t))
9240 (org-store-link-props :type "w3" :url (url-view-url t)))
9242 ((eq major-mode 'image-mode)
9243 (setq cpltxt (concat "file:"
9244 (abbreviate-file-name buffer-file-name))
9245 link cpltxt)
9246 (org-store-link-props :type "image" :file buffer-file-name))
9248 ;; In dired, store a link to the file of the current line
9249 ((derived-mode-p 'dired-mode)
9250 (let ((file (dired-get-filename nil t)))
9251 (setq file (if file
9252 (abbreviate-file-name
9253 (expand-file-name (dired-get-filename nil t)))
9254 ;; otherwise, no file so use current directory.
9255 default-directory))
9256 (setq cpltxt (concat "file:" file)
9257 link cpltxt)))
9259 ((setq search (run-hook-with-args-until-success
9260 'org-create-file-search-functions))
9261 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9262 "::" search))
9263 (setq cpltxt (or description link)))
9265 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9266 (org-with-limited-levels
9267 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9268 (cond
9269 ;; Store a link using the target at point
9270 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9271 (setq cpltxt
9272 (concat "file:"
9273 (abbreviate-file-name
9274 (buffer-file-name (buffer-base-buffer)))
9275 "::" (match-string 1))
9276 link cpltxt))
9277 ((and (featurep 'org-id)
9278 (or (eq org-id-link-to-org-use-id t)
9279 (and interactive?
9280 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9281 (and (eq org-id-link-to-org-use-id
9282 'create-if-interactive-and-no-custom-id)
9283 (not custom-id))))
9284 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9285 ;; Store a link using the ID at point
9286 (setq link (condition-case nil
9287 (prog1 (org-id-store-link)
9288 (setq desc (or (plist-get org-store-link-plist
9289 :description)
9290 "")))
9291 (error
9292 ;; Probably before first headline, link only to file
9293 (concat "file:"
9294 (abbreviate-file-name
9295 (buffer-file-name (buffer-base-buffer))))))))
9297 ;; Just link to current headline
9298 (setq cpltxt (concat "file:"
9299 (abbreviate-file-name
9300 (buffer-file-name (buffer-base-buffer)))))
9301 ;; Add a context search string
9302 (when (org-xor org-context-in-file-links
9303 (equal arg '(4)))
9304 (let* ((element (org-element-at-point))
9305 (name (org-element-property :name element)))
9306 (setq txt (cond
9307 ((org-at-heading-p) nil)
9308 (name)
9309 ((org-region-active-p)
9310 (buffer-substring (region-beginning) (region-end)))))
9311 (when (or (null txt) (string-match "\\S-" txt))
9312 (setq cpltxt
9313 (concat cpltxt "::"
9314 (condition-case nil
9315 (org-make-org-heading-search-string txt)
9316 (error "")))
9317 desc (or name
9318 (nth 4 (ignore-errors (org-heading-components)))
9319 "NONE")))))
9320 (when (string-match "::\\'" cpltxt)
9321 (setq cpltxt (substring cpltxt 0 -2)))
9322 (setq link cpltxt)))))
9324 ((buffer-file-name (buffer-base-buffer))
9325 ;; Just link to this file here.
9326 (setq cpltxt (concat "file:"
9327 (abbreviate-file-name
9328 (buffer-file-name (buffer-base-buffer)))))
9329 ;; Add a context string.
9330 (when (org-xor org-context-in-file-links
9331 (equal arg '(4)))
9332 (setq txt (if (org-region-active-p)
9333 (buffer-substring (region-beginning) (region-end))
9334 (buffer-substring (point-at-bol) (point-at-eol))))
9335 ;; Only use search option if there is some text.
9336 (when (string-match "\\S-" txt)
9337 (setq cpltxt
9338 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9339 desc "NONE")))
9340 (setq link cpltxt))
9342 (interactive?
9343 (user-error "No method for storing a link from this buffer"))
9345 (t (setq link nil)))
9347 ;; We're done setting link and desc, clean up
9348 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9349 (setq link (or link cpltxt)
9350 desc (or desc cpltxt))
9351 (cond ((not desc))
9352 ((equal desc "NONE") (setq desc nil))
9353 (t (setq desc
9354 (replace-regexp-in-string
9355 org-bracket-link-analytic-regexp
9356 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9357 desc))))
9358 ;; Return the link
9359 (if (not (and interactive? link))
9360 (or agenda-link (and link (org-make-link-string link desc)))
9361 (push (list link desc) org-stored-links)
9362 (message "Stored: %s" (or desc link))
9363 (when custom-id
9364 (setq link (concat "file:" (abbreviate-file-name
9365 (buffer-file-name)) "::#" custom-id))
9366 (push (list link desc) org-stored-links))
9367 (car org-stored-links)))))
9369 (defun org-store-link-props (&rest plist)
9370 "Store link properties.
9371 The properties are pre-processed by extracting names, addresses
9372 and dates."
9373 (let ((x (plist-get plist :from)))
9374 (when x
9375 (let ((adr (mail-extract-address-components x)))
9376 (setq plist (plist-put plist :fromname (car adr)))
9377 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9378 (let ((x (plist-get plist :to)))
9379 (when x
9380 (let ((adr (mail-extract-address-components x)))
9381 (setq plist (plist-put plist :toname (car adr)))
9382 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9383 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9384 (when x
9385 (setq plist (plist-put plist :date-timestamp
9386 (format-time-string
9387 (org-time-stamp-format t) x)))
9388 (setq plist (plist-put plist :date-timestamp-inactive
9389 (format-time-string
9390 (org-time-stamp-format t t) x)))))
9391 (let ((from (plist-get plist :from))
9392 (to (plist-get plist :to)))
9393 (when (and from to org-from-is-user-regexp)
9394 (setq plist
9395 (plist-put plist :fromto
9396 (if (string-match org-from-is-user-regexp from)
9397 (concat "to %t")
9398 (concat "from %f"))))))
9399 (setq org-store-link-plist plist))
9401 (defun org-add-link-props (&rest plist)
9402 "Add these properties to the link property list."
9403 (let (key value)
9404 (while plist
9405 (setq key (pop plist) value (pop plist))
9406 (setq org-store-link-plist
9407 (plist-put org-store-link-plist key value)))))
9409 (defun org-email-link-description (&optional fmt)
9410 "Return the description part of an email link.
9411 This takes information from `org-store-link-plist' and formats it
9412 according to FMT (default from `org-email-link-description-format')."
9413 (setq fmt (or fmt org-email-link-description-format))
9414 (let* ((p org-store-link-plist)
9415 (to (plist-get p :toaddress))
9416 (from (plist-get p :fromaddress))
9417 (table
9418 (list
9419 (cons "%c" (plist-get p :fromto))
9420 (cons "%F" (plist-get p :from))
9421 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9422 (cons "%T" (plist-get p :to))
9423 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9424 (cons "%s" (plist-get p :subject))
9425 (cons "%d" (plist-get p :date))
9426 (cons "%m" (plist-get p :message-id)))))
9427 (when (string-match "%c" fmt)
9428 ;; Check if the user wrote this message
9429 (if (and org-from-is-user-regexp from to
9430 (save-match-data (string-match org-from-is-user-regexp from)))
9431 (setq fmt (replace-match "to %t" t t fmt))
9432 (setq fmt (replace-match "from %f" t t fmt))))
9433 (org-replace-escapes fmt table)))
9435 (defun org-make-org-heading-search-string (&optional string)
9436 "Make search string for the current headline or STRING."
9437 (let ((s (or string
9438 (and (derived-mode-p 'org-mode)
9439 (save-excursion
9440 (org-back-to-heading t)
9441 (org-element-property :raw-value (org-element-at-point))))))
9442 (lines org-context-in-file-links))
9443 (unless string (setq s (concat "*" s))) ;Add * for headlines
9444 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9445 (when (and string (integerp lines) (> lines 0))
9446 (let ((slines (org-split-string s "\n")))
9447 (when (< lines (length slines))
9448 (setq s (mapconcat
9449 'identity
9450 (reverse (nthcdr (- (length slines) lines)
9451 (reverse slines))) "\n")))))
9452 (mapconcat #'identity (split-string s) " ")))
9454 (defconst org-link-escape-chars
9455 ;;%20 %5B %5D %25
9456 '(?\s ?\[ ?\] ?%)
9457 "List of characters that should be escaped in a link when stored to Org.
9458 This is the list that is used for internal purposes.")
9460 (defun org-make-link-string (link &optional description)
9461 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9462 (unless (org-string-nw-p link) (error "Empty link"))
9463 (let ((uri (cond ((string-match org-link-types-re link)
9464 (concat (match-string 1 link)
9465 (org-link-escape (substring link (match-end 1)))))
9466 ((or (file-name-absolute-p link)
9467 (string-match-p "\\`\\.\\.?/" link))
9468 (org-link-escape link))
9469 ;; For readability, do not encode space characters
9470 ;; in fuzzy links.
9471 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9472 (description
9473 (and (org-string-nw-p description)
9474 ;; Remove brackets from description, as they are fatal.
9475 (replace-regexp-in-string
9476 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9477 (org-trim description)))))
9478 (format "[[%s]%s]"
9480 (if description (format "[%s]" description) ""))))
9482 (defun org-link-escape (text &optional table merge)
9483 "Return percent escaped representation of TEXT.
9484 TEXT is a string with the text to escape.
9485 Optional argument TABLE is a list with characters that should be
9486 escaped. When nil, `org-link-escape-chars' is used.
9487 If optional argument MERGE is set, merge TABLE into
9488 `org-link-escape-chars'."
9489 (let ((characters-to-encode
9490 (cond ((null table) org-link-escape-chars)
9491 (merge (append org-link-escape-chars table))
9492 (t table))))
9493 (mapconcat
9494 (lambda (c)
9495 (if (or (memq c characters-to-encode)
9496 (and org-url-hexify-p (or (< c 32) (> c 126))))
9497 (mapconcat (lambda (e) (format "%%%.2X" e))
9498 (or (encode-coding-char c 'utf-8)
9499 (error "Unable to percent escape character: %c" c))
9501 (char-to-string c)))
9502 text "")))
9504 (defun org-link-unescape (str)
9505 "Unhex hexified Unicode parts in string STR.
9506 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9507 reciprocal of `org-link-escape', which see."
9508 (if (org-string-nw-p str)
9509 (replace-regexp-in-string
9510 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9511 str))
9513 (defun org-link-unescape-compound (hex)
9514 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9515 Note: this function also decodes single byte encodings like
9516 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9517 (save-match-data
9518 (let* ((bytes (cdr (split-string hex "%")))
9519 (ret "")
9520 (eat 0)
9521 (sum 0))
9522 (while bytes
9523 (let* ((val (string-to-number (pop bytes) 16))
9524 (shift-xor
9525 (if (= 0 eat)
9526 (cond
9527 ((>= val 252) (cons 6 252))
9528 ((>= val 248) (cons 5 248))
9529 ((>= val 240) (cons 4 240))
9530 ((>= val 224) (cons 3 224))
9531 ((>= val 192) (cons 2 192))
9532 (t (cons 0 0)))
9533 (cons 6 128))))
9534 (when (>= val 192) (setq eat (car shift-xor)))
9535 (setq val (logxor val (cdr shift-xor)))
9536 (setq sum (+ (lsh sum (car shift-xor)) val))
9537 (when (> eat 0) (setq eat (- eat 1)))
9538 (cond
9539 ((= 0 eat) ;multi byte
9540 (setq ret (concat ret (char-to-string sum)))
9541 (setq sum 0))
9542 ((not bytes) ; single byte(s)
9543 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9544 ret)))
9546 (defun org-link-unescape-single-byte-sequence (hex)
9547 "Unhexify hex-encoded single byte character sequences."
9548 (mapconcat (lambda (byte)
9549 (char-to-string (string-to-number byte 16)))
9550 (cdr (split-string hex "%")) ""))
9552 (defun org-fixup-message-id-for-http (s)
9553 "Replace special characters in a message id, so it can be used in an http query."
9554 (when (string-match "%" s)
9555 (setq s (mapconcat (lambda (c)
9556 (if (eq c ?%)
9557 "%25"
9558 (char-to-string c)))
9559 s "")))
9560 (while (string-match "<" s)
9561 (setq s (replace-match "%3C" t t s)))
9562 (while (string-match ">" s)
9563 (setq s (replace-match "%3E" t t s)))
9564 (while (string-match "@" s)
9565 (setq s (replace-match "%40" t t s)))
9568 (defun org-link-prettify (link)
9569 "Return a human-readable representation of LINK.
9570 The car of LINK must be a raw link.
9571 The cdr of LINK must be either a link description or nil."
9572 (let ((desc (or (cadr link) "<no description>")))
9573 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9574 "<" (car link) ">")))
9576 ;;;###autoload
9577 (defun org-insert-link-global ()
9578 "Insert a link like Org mode does.
9579 This command can be called in any mode to insert a link in Org syntax."
9580 (interactive)
9581 (org-load-modules-maybe)
9582 (org-run-like-in-org-mode 'org-insert-link))
9584 (defun org-insert-all-links (arg &optional pre post)
9585 "Insert all links in `org-stored-links'.
9586 When a universal prefix, do not delete the links from `org-stored-links'.
9587 When `ARG' is a number, insert the last N link(s).
9588 `PRE' and `POST' are optional arguments to define a string to
9589 prepend or to append."
9590 (interactive "P")
9591 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9592 (links (copy-sequence org-stored-links))
9593 (pr (or pre "- "))
9594 (po (or post "\n"))
9595 (cnt 1) l)
9596 (if (null org-stored-links)
9597 (message "No link to insert")
9598 (while (and (or (listp arg) (>= arg cnt))
9599 (setq l (if (listp arg)
9600 (pop links)
9601 (pop org-stored-links))))
9602 (setq cnt (1+ cnt))
9603 (insert pr)
9604 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9605 (insert po)))))
9607 (defun org-insert-last-stored-link (arg)
9608 "Insert the last link stored in `org-stored-links'."
9609 (interactive "p")
9610 (org-insert-all-links arg "" "\n"))
9612 (defun org-link-fontify-links-to-this-file ()
9613 "Fontify links to the current file in `org-stored-links'."
9614 (let ((f (buffer-file-name)) a b)
9615 (setq a (mapcar (lambda(l)
9616 (let ((ll (car l)))
9617 (when (and (string-match "^file:\\(.+\\)::" ll)
9618 (equal f (expand-file-name (match-string 1 ll))))
9619 ll)))
9620 org-stored-links))
9621 (when (featurep 'org-id)
9622 (setq b (mapcar (lambda(l)
9623 (let ((ll (car l)))
9624 (when (and (string-match "^id:\\(.+\\)$" ll)
9625 (equal f (expand-file-name
9626 (or (org-id-find-id-file
9627 (match-string 1 ll)) ""))))
9628 ll)))
9629 org-stored-links)))
9630 (mapcar (lambda(l)
9631 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9632 (delq nil (append a b)))))
9634 (defvar org--links-history nil)
9635 (defun org-insert-link (&optional complete-file link-location default-description)
9636 "Insert a link. At the prompt, enter the link.
9638 Completion can be used to insert any of the link protocol prefixes in use.
9640 The history can be used to select a link previously stored with
9641 `org-store-link'. When the empty string is entered (i.e. if you just
9642 press `RET' at the prompt), the link defaults to the most recently
9643 stored link. As `SPC' triggers completion in the minibuffer, you need to
9644 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9646 You will also be prompted for a description, and if one is given, it will
9647 be displayed in the buffer instead of the link.
9649 If there is already a link at point, this command will allow you to edit
9650 link and description parts.
9652 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9653 file name can be
9654 selected using completion. The path to the file will be relative to the
9655 current directory if the file is in the current directory or a subdirectory.
9656 Otherwise, the link will be the absolute path as completed in the minibuffer
9657 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9658 option `org-link-file-path-type'.
9660 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9661 absolute path even if the file is in
9662 the current directory or below.
9664 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9665 prefix negates `org-keep-stored-link-after-insertion'.
9667 If the LINK-LOCATION parameter is non-nil, this value will be used as
9668 the link location instead of reading one interactively.
9670 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9671 be used as the default description. Otherwise, if
9672 `org-make-link-description-function' is non-nil, this function
9673 will be called with the link target, and the result will be the
9674 default link description. When called non-interactivily, don't
9675 allow to edit the default description."
9676 (interactive "P")
9677 (let* ((wcf (current-window-configuration))
9678 (origbuf (current-buffer))
9679 (region (when (org-region-active-p)
9680 (buffer-substring (region-beginning) (region-end))))
9681 (remove (and region (list (region-beginning) (region-end))))
9682 (desc region)
9683 (link link-location)
9684 (abbrevs org-link-abbrev-alist-local)
9685 entry all-prefixes auto-desc)
9686 (cond
9687 (link-location) ; specified by arg, just use it.
9688 ((org-in-regexp org-bracket-link-regexp 1)
9689 ;; We do have a link at point, and we are going to edit it.
9690 (setq remove (list (match-beginning 0) (match-end 0)))
9691 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9692 (setq link (read-string "Link: "
9693 (org-link-unescape
9694 (match-string-no-properties 1)))))
9695 ((or (org-in-regexp org-angle-link-re)
9696 (org-in-regexp org-plain-link-re))
9697 ;; Convert to bracket link
9698 (setq remove (list (match-beginning 0) (match-end 0))
9699 link (read-string "Link: "
9700 (org-unbracket-string "<" ">" (match-string 0)))))
9701 ((member complete-file '((4) (16)))
9702 ;; Completing read for file names.
9703 (setq link (org-file-complete-link complete-file)))
9705 ;; Read link, with completion for stored links.
9706 (org-link-fontify-links-to-this-file)
9707 (org-switch-to-buffer-other-window "*Org Links*")
9708 (with-current-buffer "*Org Links*"
9709 (erase-buffer)
9710 (insert "Insert a link.
9711 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9712 (when org-stored-links
9713 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9714 (insert (mapconcat 'org-link-prettify
9715 (reverse org-stored-links) "\n")))
9716 (goto-char (point-min)))
9717 (let ((cw (selected-window)))
9718 (select-window (get-buffer-window "*Org Links*" 'visible))
9719 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9720 (unless (pos-visible-in-window-p (point-max))
9721 (org-fit-window-to-buffer))
9722 (and (window-live-p cw) (select-window cw)))
9723 (setq all-prefixes (append (mapcar 'car abbrevs)
9724 (mapcar 'car org-link-abbrev-alist)
9725 (org-link-types)))
9726 (unwind-protect
9727 ;; Fake a link history, containing the stored links.
9728 (let ((org--links-history
9729 (append (mapcar #'car org-stored-links)
9730 org-insert-link-history)))
9731 (setq link
9732 (org-completing-read
9733 "Link: "
9734 (append
9735 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9736 (mapcar #'car org-stored-links))
9737 nil nil nil
9738 'org--links-history
9739 (caar org-stored-links)))
9740 (unless (org-string-nw-p link) (user-error "No link selected"))
9741 (dolist (l org-stored-links)
9742 (when (equal link (cadr l))
9743 (setq link (car l))
9744 (setq auto-desc t)))
9745 (when (or (member link all-prefixes)
9746 (and (equal ":" (substring link -1))
9747 (member (substring link 0 -1) all-prefixes)
9748 (setq link (substring link 0 -1))))
9749 (setq link (with-current-buffer origbuf
9750 (org-link-try-special-completion link)))))
9751 (set-window-configuration wcf)
9752 (kill-buffer "*Org Links*"))
9753 (setq entry (assoc link org-stored-links))
9754 (or entry (push link org-insert-link-history))
9755 (setq desc (or desc (nth 1 entry)))))
9757 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9758 (not org-keep-stored-link-after-insertion))
9759 (setq org-stored-links (delq (assoc link org-stored-links)
9760 org-stored-links)))
9762 (when (and (string-match org-plain-link-re link)
9763 (not (string-match org-ts-regexp link)))
9764 ;; URL-like link, normalize the use of angular brackets.
9765 (setq link (org-unbracket-string "<" ">" link)))
9767 ;; Check if we are linking to the current file with a search
9768 ;; option If yes, simplify the link by using only the search
9769 ;; option.
9770 (when (and buffer-file-name
9771 (let ((case-fold-search nil))
9772 (string-match "\\`file:\\(.+?\\)::" link)))
9773 (let ((path (match-string-no-properties 1 link))
9774 (search (substring-no-properties link (match-end 0))))
9775 (save-match-data
9776 (when (equal (file-truename buffer-file-name) (file-truename path))
9777 ;; We are linking to this same file, with a search option
9778 (setq link search)))))
9780 ;; Check if we can/should use a relative path. If yes, simplify
9781 ;; the link.
9782 (let ((case-fold-search nil))
9783 (when (string-match "\\`\\(file\\|docview\\):" link)
9784 (let* ((type (match-string-no-properties 0 link))
9785 (path-start (match-end 0))
9786 (search (and (string-match "::\\(.*\\)\\'" link)
9787 (match-string 1 link)))
9788 (path
9789 (if search
9790 (substring-no-properties
9791 link path-start (match-beginning 0))
9792 (substring-no-properties link (match-end 0))))
9793 (origpath path))
9794 (cond
9795 ((or (eq org-link-file-path-type 'absolute)
9796 (equal complete-file '(16)))
9797 (setq path (abbreviate-file-name (expand-file-name path))))
9798 ((eq org-link-file-path-type 'noabbrev)
9799 (setq path (expand-file-name path)))
9800 ((eq org-link-file-path-type 'relative)
9801 (setq path (file-relative-name path)))
9803 (save-match-data
9804 (if (string-match (concat "^" (regexp-quote
9805 (expand-file-name
9806 (file-name-as-directory
9807 default-directory))))
9808 (expand-file-name path))
9809 ;; We are linking a file with relative path name.
9810 (setq path (substring (expand-file-name path)
9811 (match-end 0)))
9812 (setq path (abbreviate-file-name (expand-file-name path)))))))
9813 (setq link (concat type path (and search (concat "::" search))))
9814 (when (equal desc origpath)
9815 (setq desc path)))))
9817 (unless auto-desc
9818 (let ((initial-input
9819 (cond
9820 (default-description)
9821 ((not org-make-link-description-function) desc)
9822 (t (condition-case nil
9823 (funcall org-make-link-description-function link desc)
9824 (error
9825 (message "Can't get link description from `%s'"
9826 (symbol-name org-make-link-description-function))
9827 (sit-for 2)
9828 nil))))))
9829 (setq desc (if (called-interactively-p 'any)
9830 (read-string "Description: " initial-input)
9831 initial-input))))
9833 (unless (string-match "\\S-" desc) (setq desc nil))
9834 (when remove (apply 'delete-region remove))
9835 (insert (org-make-link-string link desc))
9836 ;; Redisplay so as the new link has proper invisible characters.
9837 (sit-for 0)))
9839 (defun org-link-try-special-completion (type)
9840 "If there is completion support for link type TYPE, offer it."
9841 (let ((fun (org-link-get-parameter type :complete)))
9842 (if (functionp fun)
9843 (funcall fun)
9844 (read-string "Link (no completion support): " (concat type ":")))))
9846 (defun org-file-complete-link (&optional arg)
9847 "Create a file link using completion."
9848 (let ((file (read-file-name "File: "))
9849 (pwd (file-name-as-directory (expand-file-name ".")))
9850 (pwd1 (file-name-as-directory (abbreviate-file-name
9851 (expand-file-name ".")))))
9852 (cond ((equal arg '(16))
9853 (concat "file:"
9854 (abbreviate-file-name (expand-file-name file))))
9855 ((string-match
9856 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9857 (concat "file:" (match-string 1 file)))
9858 ((string-match
9859 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9860 (expand-file-name file))
9861 (concat "file:"
9862 (match-string 1 (expand-file-name file))))
9863 (t (concat "file:" file)))))
9866 ;;; Opening/following a link
9868 (defvar org-link-search-failed nil)
9870 (defvar org-open-link-functions nil
9871 "Hook for functions finding a plain text link.
9872 These functions must take a single argument, the link content.
9873 They will be called for links that look like [[link text][description]]
9874 when LINK TEXT does not have a protocol like \"http:\" and does not look
9875 like a filename (e.g. \"./blue.png\").
9877 These functions will be called *before* Org attempts to resolve the
9878 link by doing text searches in the current buffer - so if you want a
9879 link \"[[target]]\" to still find \"<<target>>\", your function should
9880 handle this as a special case.
9882 When the function does handle the link, it must return a non-nil value.
9883 If it decides that it is not responsible for this link, it must return
9884 nil to indicate that that Org can continue with other options like
9885 exact and fuzzy text search.")
9887 (defun org-next-link (&optional search-backward)
9888 "Move forward to the next link.
9889 If the link is in hidden text, expose it."
9890 (interactive "P")
9891 (when (and org-link-search-failed (eq this-command last-command))
9892 (goto-char (point-min))
9893 (message "Link search wrapped back to beginning of buffer"))
9894 (setq org-link-search-failed nil)
9895 (let* ((pos (point))
9896 (ct (org-context))
9897 (a (assq :link ct))
9898 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9899 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9900 ((looking-at org-any-link-re)
9901 ;; Don't stay stuck at link without an org-link face
9902 (forward-char (if search-backward -1 1))))
9903 (if (funcall srch-fun org-any-link-re nil t)
9904 (progn
9905 (goto-char (match-beginning 0))
9906 (when (org-invisible-p) (org-show-context)))
9907 (goto-char pos)
9908 (setq org-link-search-failed t)
9909 (message "No further link found"))))
9911 (defun org-previous-link ()
9912 "Move backward to the previous link.
9913 If the link is in hidden text, expose it."
9914 (interactive)
9915 (funcall 'org-next-link t))
9917 (defun org-translate-link (s)
9918 "Translate a link string if a translation function has been defined."
9919 (with-temp-buffer
9920 (insert (org-trim s))
9921 (org-trim (org-element-interpret-data (org-element-context)))))
9923 (defun org-translate-link-from-planner (type path)
9924 "Translate a link from Emacs Planner syntax so that Org can follow it.
9925 This is still an experimental function, your mileage may vary."
9926 (cond
9927 ((member type '("http" "https" "news" "ftp"))
9928 ;; standard Internet links are the same.
9929 nil)
9930 ((and (equal type "irc") (string-match "^//" path))
9931 ;; Planner has two / at the beginning of an irc link, we have 1.
9932 ;; We should have zero, actually....
9933 (setq path (substring path 1)))
9934 ((and (equal type "lisp") (string-match "^/" path))
9935 ;; Planner has a slash, we do not.
9936 (setq type "elisp" path (substring path 1)))
9937 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9938 ;; A typical message link. Planner has the id after the final slash,
9939 ;; we separate it with a hash mark
9940 (setq path (concat (match-string 1 path) "#"
9941 (org-unbracket-string "<" ">" (match-string 2 path))))))
9942 (cons type path))
9944 (defun org-find-file-at-mouse (ev)
9945 "Open file link or URL at mouse."
9946 (interactive "e")
9947 (mouse-set-point ev)
9948 (org-open-at-point 'in-emacs))
9950 (defun org-open-at-mouse (ev)
9951 "Open file link or URL at mouse.
9952 See the docstring of `org-open-file' for details."
9953 (interactive "e")
9954 (mouse-set-point ev)
9955 (when (eq major-mode 'org-agenda-mode)
9956 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9957 (org-open-at-point))
9959 (defvar org-window-config-before-follow-link nil
9960 "The window configuration before following a link.
9961 This is saved in case the need arises to restore it.")
9963 ;;;###autoload
9964 (defun org-open-at-point-global ()
9965 "Follow a link or a time-stamp like Org mode does.
9966 Also follow links and emails as seen by `thing-at-point'.
9967 This command can be called in any mode to follow an external
9968 link or a time-stamp that has Org mode syntax. Its behavior
9969 is undefined when called on internal links like fuzzy links.
9970 Raise a user error when there is nothing to follow."
9971 (interactive)
9972 (let ((tap-url (thing-at-point 'url))
9973 (tap-email (thing-at-point 'email)))
9974 (cond ((org-in-regexp org-any-link-re)
9975 (org-open-link-from-string (match-string-no-properties 0)))
9976 ((or (org-in-regexp org-ts-regexp-both nil t)
9977 (org-in-regexp org-tsr-regexp-both nil t))
9978 (org-follow-timestamp-link))
9979 (tap-url (org-open-link-from-string tap-url))
9980 (tap-email (org-open-link-from-string
9981 (concat "mailto:" tap-email)))
9982 (t (user-error "No link found")))))
9984 ;;;###autoload
9985 (defun org-open-link-from-string (s &optional arg reference-buffer)
9986 "Open a link in the string S, as if it was in Org mode."
9987 (interactive "sLink: \nP")
9988 (let ((reference-buffer (or reference-buffer (current-buffer))))
9989 (with-temp-buffer
9990 (let ((org-inhibit-startup (not reference-buffer)))
9991 (org-mode)
9992 (insert s)
9993 (goto-char (point-min))
9994 (when reference-buffer
9995 (setq org-link-abbrev-alist-local
9996 (with-current-buffer reference-buffer
9997 org-link-abbrev-alist-local)))
9998 (org-open-at-point arg reference-buffer)))))
10000 (defvar org-open-at-point-functions nil
10001 "Hook that is run when following a link at point.
10003 Functions in this hook must return t if they identify and follow
10004 a link at point. If they don't find anything interesting at point,
10005 they must return nil.")
10007 (defvar org-link-search-inhibit-query nil)
10008 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10009 (defun org--open-doi-link (path)
10010 "Open a \"doi\" type link.
10011 PATH is a the path to search for, as a string."
10012 (browse-url (url-encode-url (concat org-doi-server-url path))))
10014 (defun org--open-elisp-link (path)
10015 "Open a \"elisp\" type link.
10016 PATH is the sexp to evaluate, as a string."
10017 (let ((cmd path))
10018 (if (or (and (org-string-nw-p
10019 org-confirm-elisp-link-not-regexp)
10020 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10021 (not org-confirm-elisp-link-function)
10022 (funcall org-confirm-elisp-link-function
10023 (format "Execute \"%s\" as elisp? "
10024 (org-add-props cmd nil 'face 'org-warning))))
10025 (message "%s => %s" cmd
10026 (if (eq (string-to-char cmd) ?\()
10027 (eval (read cmd))
10028 (call-interactively (read cmd))))
10029 (user-error "Abort"))))
10031 (defun org--open-help-link (path)
10032 "Open a \"help\" type link.
10033 PATH is a symbol name, as a string."
10034 (pcase (intern path)
10035 ((and (pred fboundp) variable) (describe-function variable))
10036 ((and (pred boundp) function) (describe-variable function))
10037 (name (user-error "Unknown function or variable: %s" name))))
10039 (defun org--open-shell-link (path)
10040 "Open a \"shell\" type link.
10041 PATH is the command to execute, as a string."
10042 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10043 (cmd path))
10044 (if (or (and (org-string-nw-p
10045 org-confirm-shell-link-not-regexp)
10046 (string-match
10047 org-confirm-shell-link-not-regexp cmd))
10048 (not org-confirm-shell-link-function)
10049 (funcall org-confirm-shell-link-function
10050 (format "Execute \"%s\" in shell? "
10051 (org-add-props cmd nil
10052 'face 'org-warning))))
10053 (progn
10054 (message "Executing %s" cmd)
10055 (shell-command cmd buf)
10056 (when (featurep 'midnight)
10057 (setq clean-buffer-list-kill-buffer-names
10058 (cons (buffer-name buf)
10059 clean-buffer-list-kill-buffer-names))))
10060 (user-error "Abort"))))
10062 (defun org-open-at-point (&optional arg reference-buffer)
10063 "Open link, timestamp, footnote or tags at point.
10065 When point is on a link, follow it. Normally, files will be
10066 opened by an appropriate application. If the optional prefix
10067 argument ARG is non-nil, Emacs will visit the file. With
10068 a double prefix argument, try to open outside of Emacs, in the
10069 application the system uses for this file type.
10071 When point is on a timestamp, open the agenda at the day
10072 specified.
10074 When point is a footnote definition, move to the first reference
10075 found. If it is on a reference, move to the associated
10076 definition.
10078 When point is on a headline, display a list of every link in the
10079 entry, so it is possible to pick one, or all, of them. If point
10080 is on a tag, call `org-tags-view' instead.
10082 When optional argument REFERENCE-BUFFER is non-nil, it should
10083 specify a buffer from where the link search should happen. This
10084 is used internally by `org-open-link-from-string'.
10086 On top of syntactically correct links, this function will also
10087 try to open links and time-stamps in comments, example
10088 blocks... i.e., whenever point is on something looking like
10089 a timestamp or a link."
10090 (interactive "P")
10091 ;; On a code block, open block's results.
10092 (unless (call-interactively 'org-babel-open-src-block-result)
10093 (org-load-modules-maybe)
10094 (setq org-window-config-before-follow-link (current-window-configuration))
10095 (org-remove-occur-highlights nil nil t)
10096 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10097 (let* ((context
10098 ;; Only consider supported types, even if they are not
10099 ;; the closest one.
10100 (org-element-lineage
10101 (org-element-context)
10102 '(clock footnote-definition footnote-reference headline
10103 inlinetask link timestamp)
10105 (type (org-element-type context))
10106 (value (org-element-property :value context)))
10107 (cond
10108 ;; On a headline or an inlinetask, but not on a timestamp,
10109 ;; a link, a footnote reference.
10110 ((memq type '(headline inlinetask))
10111 (org-match-line org-complex-heading-regexp)
10112 (if (and (match-beginning 5)
10113 (>= (point) (match-beginning 5))
10114 (< (point) (match-end 5)))
10115 ;; On tags.
10116 (org-tags-view arg (substring (match-string 5) 0 -1))
10117 ;; Not on tags.
10118 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10119 (`(nil . ,_)
10120 (require 'org-attach)
10121 (org-attach-reveal 'if-exists))
10122 (`(,links . ,links-end)
10123 (dolist (link (if (stringp links) (list links) links))
10124 (search-forward link nil links-end)
10125 (goto-char (match-beginning 0))
10126 (org-open-at-point))))))
10127 ;; On a footnote reference or at definition's label.
10128 ((or (eq type 'footnote-reference)
10129 (and (eq type 'footnote-definition)
10130 (save-excursion
10131 ;; Do not validate action when point is on the
10132 ;; spaces right after the footnote label, in
10133 ;; order to be on par with behavior on links.
10134 (skip-chars-forward " \t")
10135 (let ((begin
10136 (org-element-property :contents-begin context)))
10137 (if begin (< (point) begin)
10138 (= (org-element-property :post-affiliated context)
10139 (line-beginning-position)))))))
10140 (org-footnote-action))
10141 ;; No valid context. Ignore catch-all types like `headline'.
10142 ;; If point is on something looking like a link or
10143 ;; a time-stamp, try opening it. It may be useful in
10144 ;; comments, example blocks...
10145 ((memq type '(footnote-definition headline inlinetask nil))
10146 (call-interactively #'org-open-at-point-global))
10147 ;; On a clock line, make sure point is on the timestamp
10148 ;; before opening it.
10149 ((and (eq type 'clock)
10150 value
10151 (>= (point) (org-element-property :begin value))
10152 (<= (point) (org-element-property :end value)))
10153 (org-follow-timestamp-link))
10154 ;; Do nothing on white spaces after an object.
10155 ((>= (point)
10156 (save-excursion
10157 (goto-char (org-element-property :end context))
10158 (skip-chars-backward " \t")
10159 (point)))
10160 (user-error "No link found"))
10161 ((eq type 'timestamp) (org-follow-timestamp-link))
10162 ((eq type 'link)
10163 (let ((type (org-element-property :type context))
10164 (path (org-link-unescape (org-element-property :path context))))
10165 ;; Switch back to REFERENCE-BUFFER needed when called in
10166 ;; a temporary buffer through `org-open-link-from-string'.
10167 (with-current-buffer (or reference-buffer (current-buffer))
10168 (cond
10169 ((equal type "file")
10170 (if (string-match "[*?{]" (file-name-nondirectory path))
10171 (dired path)
10172 ;; Look into `org-link-parameters' in order to find
10173 ;; a DEDICATED-FUNCTION to open file. The function
10174 ;; will be applied on raw link instead of parsed
10175 ;; link due to the limitation in `org-add-link-type'
10176 ;; ("open" function called with a single argument).
10177 ;; If no such function is found, fallback to
10178 ;; `org-open-file'.
10179 (let* ((option (org-element-property :search-option context))
10180 (app (org-element-property :application context))
10181 (dedicated-function
10182 (org-link-get-parameter
10183 (if app (concat type "+" app) type)
10184 :follow)))
10185 (if dedicated-function
10186 (funcall dedicated-function
10187 (concat path
10188 (and option (concat "::" option))))
10189 (apply #'org-open-file
10190 path
10191 (cond (arg)
10192 ((equal app "emacs") 'emacs)
10193 ((equal app "sys") 'system))
10194 (cond ((not option) nil)
10195 ((string-match-p "\\`[0-9]+\\'" option)
10196 (list (string-to-number option)))
10197 (t (list nil
10198 (org-link-unescape option)))))))))
10199 ((functionp (org-link-get-parameter type :follow))
10200 (funcall (org-link-get-parameter type :follow) path))
10201 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10202 (unless (run-hook-with-args-until-success
10203 'org-open-link-functions path)
10204 (if (not arg) (org-mark-ring-push)
10205 (switch-to-buffer-other-window
10206 (org-get-buffer-for-internal-link (current-buffer))))
10207 (let ((destination
10208 (org-with-wide-buffer
10209 (if (equal type "radio")
10210 (org-search-radio-target
10211 (org-element-property :path context))
10212 (org-link-search
10213 (if (member type '("custom-id" "coderef"))
10214 (org-element-property :raw-link context)
10215 path)
10216 ;; Prevent fuzzy links from matching
10217 ;; themselves.
10218 (and (equal type "fuzzy")
10219 (+ 2 (org-element-property :begin context)))))
10220 (point))))
10221 (unless (and (<= (point-min) destination)
10222 (>= (point-max) destination))
10223 (widen))
10224 (goto-char destination))))
10225 (t (browse-url-at-point))))))
10226 (t (user-error "No link found")))))
10227 (run-hook-with-args 'org-follow-link-hook)))
10229 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10230 "Offer links in the current entry and return the selected link.
10231 If there is only one link, return it.
10232 If NTH is an integer, return the NTH link found.
10233 If ZERO is a string, check also this string for a link, and if
10234 there is one, return it."
10235 (with-current-buffer buffer
10236 (org-with-wide-buffer
10237 (goto-char marker)
10238 (let ((cnt ?0)
10239 have-zero end links link c)
10240 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10241 (push (match-string 0 zero) links)
10242 (setq cnt (1- cnt) have-zero t))
10243 (save-excursion
10244 (org-back-to-heading t)
10245 (setq end (save-excursion (outline-next-heading) (point)))
10246 (while (re-search-forward org-any-link-re end t)
10247 (push (match-string 0) links))
10248 (setq links (org-uniquify (reverse links))))
10249 (cond
10250 ((null links)
10251 (message "No links"))
10252 ((equal (length links) 1)
10253 (setq link (car links)))
10254 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10255 (setq link (nth (if have-zero nth (1- nth)) links)))
10256 (t ; we have to select a link
10257 (save-excursion
10258 (save-window-excursion
10259 (delete-other-windows)
10260 (with-output-to-temp-buffer "*Select Link*"
10261 (dolist (l links)
10262 (cond
10263 ((not (string-match org-bracket-link-regexp l))
10264 (princ (format "[%c] %s\n" (cl-incf cnt)
10265 (org-unbracket-string "<" ">" l))))
10266 ((match-end 3)
10267 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10268 (match-string 3 l) (match-string 1 l))))
10269 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10270 (match-string 1 l)))))))
10271 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10272 (message "Select link to open, RET to open all:")
10273 (setq c (read-char-exclusive))
10274 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10275 (when (equal c ?q) (user-error "Abort"))
10276 (if (equal c ?\C-m)
10277 (setq link links)
10278 (setq nth (- c ?0))
10279 (when have-zero (setq nth (1+ nth)))
10280 (unless (and (integerp nth) (>= (length links) nth))
10281 (user-error "Invalid link selection"))
10282 (setq link (nth (1- nth) links)))))
10283 (cons link end)))))
10285 ;; TODO: These functions are deprecated since `org-open-at-point'
10286 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10287 (defun org-open-file-with-system (path)
10288 "Open file at PATH using the system way of opening it."
10289 (org-open-file path 'system))
10290 (defun org-open-file-with-emacs (path)
10291 "Open file at PATH in Emacs."
10292 (org-open-file path 'emacs))
10295 ;;; File search
10297 (defvar org-create-file-search-functions nil
10298 "List of functions to construct the right search string for a file link.
10299 These functions are called in turn with point at the location to
10300 which the link should point.
10302 A function in the hook should first test if it would like to
10303 handle this file type, for example by checking the `major-mode'
10304 or the file extension. If it decides not to handle this file, it
10305 should just return nil to give other functions a chance. If it
10306 does handle the file, it must return the search string to be used
10307 when following the link. The search string will be part of the
10308 file link, given after a double colon, and `org-open-at-point'
10309 will automatically search for it. If special measures must be
10310 taken to make the search successful, another function should be
10311 added to the companion hook `org-execute-file-search-functions',
10312 which see.
10314 A function in this hook may also use `setq' to set the variable
10315 `description' to provide a suggestion for the descriptive text to
10316 be used for this link when it gets inserted into an Org buffer
10317 with \\[org-insert-link].")
10319 (defvar org-execute-file-search-functions nil
10320 "List of functions to execute a file search triggered by a link.
10322 Functions added to this hook must accept a single argument, the
10323 search string that was part of the file link, the part after the
10324 double colon. The function must first check if it would like to
10325 handle this search, for example by checking the `major-mode' or
10326 the file extension. If it decides not to handle this search, it
10327 should just return nil to give other functions a chance. If it
10328 does handle the search, it must return a non-nil value to keep
10329 other functions from trying.
10331 Each function can access the current prefix argument through the
10332 variable `current-prefix-arg'. Note that a single prefix is used
10333 to force opening a link in Emacs, so it may be good to only use a
10334 numeric or double prefix to guide the search function.
10336 In case this is needed, a function in this hook can also restore
10337 the window configuration before `org-open-at-point' was called using:
10339 (set-window-configuration org-window-config-before-follow-link)")
10341 (defun org-search-radio-target (target)
10342 "Search a radio target matching TARGET in current buffer.
10343 White spaces are not significant."
10344 (let ((re (format "<<<%s>>>"
10345 (mapconcat #'regexp-quote
10346 (split-string target)
10347 "[ \t]+\\(?:\n[ \t]*\\)?")))
10348 (origin (point)))
10349 (goto-char (point-min))
10350 (catch :radio-match
10351 (while (re-search-forward re nil t)
10352 (backward-char)
10353 (let ((object (org-element-context)))
10354 (when (eq (org-element-type object) 'radio-target)
10355 (goto-char (org-element-property :begin object))
10356 (org-show-context 'link-search)
10357 (throw :radio-match nil))))
10358 (goto-char origin)
10359 (user-error "No match for radio target: %s" target))))
10361 (defun org-link-search (s &optional avoid-pos stealth)
10362 "Search for a search string S.
10364 If S starts with \"#\", it triggers a custom ID search.
10366 If S is enclosed within parenthesis, it initiates a coderef
10367 search.
10369 If S is surrounded by forward slashes, it is interpreted as
10370 a regular expression. In Org mode files, this will create an
10371 `org-occur' sparse tree. In ordinary files, `occur' will be used
10372 to list matches. If the current buffer is in `dired-mode', grep
10373 will be used to search in all files.
10375 When AVOID-POS is given, ignore matches near that position.
10377 When optional argument STEALTH is non-nil, do not modify
10378 visibility around point, thus ignoring `org-show-context-detail'
10379 variable.
10381 Search is case-insensitive and ignores white spaces. Return type
10382 of matched result, which is either `dedicated' or `fuzzy'."
10383 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10384 (let* ((case-fold-search t)
10385 (origin (point))
10386 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10387 (starred (eq (string-to-char normalized) ?*))
10388 (words (split-string (if starred (substring s 1) s)))
10389 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10390 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10391 type)
10392 (cond
10393 ;; Check if there are any special search functions.
10394 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10395 ((eq (string-to-char s) ?#)
10396 ;; Look for a custom ID S if S starts with "#".
10397 (let* ((id (substring normalized 1))
10398 (match (org-find-property "CUSTOM_ID" id)))
10399 (if match (progn (goto-char match) (setf type 'dedicated))
10400 (error "No match for custom ID: %s" id))))
10401 ((string-match "\\`(\\(.*\\))\\'" normalized)
10402 ;; Look for coderef targets if S is enclosed within parenthesis.
10403 (let ((coderef (match-string-no-properties 1 normalized))
10404 (re (substring s-single-re 1 -1)))
10405 (goto-char (point-min))
10406 (catch :coderef-match
10407 (while (re-search-forward re nil t)
10408 (let ((element (org-element-at-point)))
10409 (when (and (memq (org-element-type element)
10410 '(example-block src-block))
10411 ;; Build proper regexp according to current
10412 ;; block's label format.
10413 (let ((label-fmt
10414 (regexp-quote
10415 (or (org-element-property :label-fmt element)
10416 org-coderef-label-format))))
10417 (save-excursion
10418 (beginning-of-line)
10419 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10420 (format label-fmt coderef))))))
10421 (setq type 'dedicated)
10422 (goto-char (match-beginning 1))
10423 (throw :coderef-match nil))))
10424 (goto-char origin)
10425 (error "No match for coderef: %s" coderef))))
10426 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10427 ;; Look for a regular expression.
10428 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10429 (match-string 1 s)))
10430 ;; From here, we handle fuzzy links.
10432 ;; Look for targets, only if not in a headline search.
10433 ((and (not starred)
10434 (let ((target (format "<<%s>>" s-multi-re)))
10435 (catch :target-match
10436 (goto-char (point-min))
10437 (while (re-search-forward target nil t)
10438 (backward-char)
10439 (let ((context (org-element-context)))
10440 (when (eq (org-element-type context) 'target)
10441 (setq type 'dedicated)
10442 (goto-char (org-element-property :begin context))
10443 (throw :target-match t))))
10444 nil))))
10445 ;; Look for elements named after S, only if not in a headline
10446 ;; search.
10447 ((and (not starred)
10448 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10449 (catch :name-match
10450 (goto-char (point-min))
10451 (while (re-search-forward name nil t)
10452 (let ((element (org-element-at-point)))
10453 (when (equal words
10454 (split-string
10455 (org-element-property :name element)))
10456 (setq type 'dedicated)
10457 (beginning-of-line)
10458 (throw :name-match t))))
10459 nil))))
10460 ;; Regular text search. Prefer headlines in Org mode buffers.
10461 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10462 ;; statistics cookies and tags.
10463 ((and (derived-mode-p 'org-mode)
10464 (let ((title-re
10465 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10466 org-outline-regexp-bol
10467 org-comment-string
10468 (mapconcat #'regexp-quote words ".+")))
10469 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10470 (comment-re (eval-when-compile
10471 (format "\\`%s[ \t]+" org-comment-string))))
10472 (goto-char (point-min))
10473 (catch :found
10474 (while (re-search-forward title-re nil t)
10475 (when (equal words
10476 (split-string
10477 (replace-regexp-in-string
10478 cookie-re ""
10479 (replace-regexp-in-string
10480 comment-re "" (org-get-heading t t t)))))
10481 (throw :found t)))
10482 nil)))
10483 (beginning-of-line)
10484 (setq type 'dedicated))
10485 ;; Offer to create non-existent headline depending on
10486 ;; `org-link-search-must-match-exact-headline'.
10487 ((and (derived-mode-p 'org-mode)
10488 (not org-link-search-inhibit-query)
10489 (eq org-link-search-must-match-exact-headline 'query-to-create)
10490 (yes-or-no-p "No match - create this as a new heading? "))
10491 (goto-char (point-max))
10492 (unless (bolp) (newline))
10493 (org-insert-heading nil t t)
10494 (insert s "\n")
10495 (beginning-of-line 0))
10496 ;; Only headlines are looked after. No need to process
10497 ;; further: throw an error.
10498 ((and (derived-mode-p 'org-mode)
10499 (or starred org-link-search-must-match-exact-headline))
10500 (goto-char origin)
10501 (error "No match for fuzzy expression: %s" normalized))
10502 ;; Regular text search.
10503 ((catch :fuzzy-match
10504 (goto-char (point-min))
10505 (while (re-search-forward s-multi-re nil t)
10506 ;; Skip match if it contains AVOID-POS or it is included in
10507 ;; a link with a description but outside the description.
10508 (unless (or (and avoid-pos
10509 (<= (match-beginning 0) avoid-pos)
10510 (> (match-end 0) avoid-pos))
10511 (and (save-match-data
10512 (org-in-regexp org-bracket-link-regexp))
10513 (match-beginning 3)
10514 (or (> (match-beginning 3) (point))
10515 (<= (match-end 3) (point)))
10516 (org-element-lineage
10517 (save-match-data (org-element-context))
10518 '(link) t)))
10519 (goto-char (match-beginning 0))
10520 (setq type 'fuzzy)
10521 (throw :fuzzy-match t)))
10522 nil))
10523 ;; All failed. Throw an error.
10524 (t (goto-char origin)
10525 (error "No match for fuzzy expression: %s" normalized)))
10526 ;; Disclose surroundings of match, if appropriate.
10527 (when (and (derived-mode-p 'org-mode) (not stealth))
10528 (org-show-context 'link-search))
10529 type))
10531 (defun org-get-buffer-for-internal-link (buffer)
10532 "Return a buffer to be used for displaying the link target of internal links."
10533 (cond
10534 ((not org-display-internal-link-with-indirect-buffer)
10535 buffer)
10536 ((string-suffix-p "(Clone)" (buffer-name buffer))
10537 (message "Buffer is already a clone, not making another one")
10538 ;; we also do not modify visibility in this case
10539 buffer)
10540 (t ; make a new indirect buffer for displaying the link
10541 (let* ((bn (buffer-name buffer))
10542 (ibn (concat bn "(Clone)"))
10543 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10544 (with-current-buffer ib (org-overview))
10545 ib))))
10547 (defun org-do-occur (regexp &optional cleanup)
10548 "Call the Emacs command `occur'.
10549 If CLEANUP is non-nil, remove the printout of the regular expression
10550 in the *Occur* buffer. This is useful if the regex is long and not useful
10551 to read."
10552 (occur regexp)
10553 (when cleanup
10554 (let ((cwin (selected-window)) win beg end)
10555 (when (setq win (get-buffer-window "*Occur*"))
10556 (select-window win))
10557 (goto-char (point-min))
10558 (when (re-search-forward "match[a-z]+" nil t)
10559 (setq beg (match-end 0))
10560 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10561 (setq end (1- (match-beginning 0)))))
10562 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10563 (goto-char (point-min))
10564 (select-window cwin))))
10567 ;;; The Mark Ring
10569 (defvar org-mark-ring nil
10570 "Mark ring for positions before jumps in Org mode.")
10572 (defvar org-mark-ring-last-goto nil
10573 "Last position in the mark ring used to go back.")
10575 ;; Fill and close the ring
10576 (setq org-mark-ring nil)
10577 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10579 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10580 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10581 org-mark-ring)
10583 (defun org-mark-ring-push (&optional pos buffer)
10584 "Put the current position into the mark ring and rotate it.
10585 Also push position into the Emacs mark ring. If optional
10586 argument POS and BUFFER are not nil, mark this location instead."
10587 (interactive)
10588 (let ((pos (or pos (point)))
10589 (buffer (or buffer (current-buffer))))
10590 (with-current-buffer buffer
10591 (org-with-point-at pos (push-mark nil t)))
10592 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10593 (move-marker (car org-mark-ring) pos buffer))
10594 (message
10595 (substitute-command-keys
10596 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10598 (defun org-mark-ring-goto (&optional n)
10599 "Jump to the previous position in the mark ring.
10600 With prefix arg N, jump back that many stored positions. When
10601 called several times in succession, walk through the entire ring.
10602 Org mode commands jumping to a different position in the current file,
10603 or to another Org file, automatically push the old position onto the ring."
10604 (interactive "p")
10605 (let (p m)
10606 (if (eq last-command this-command)
10607 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10608 (setq p org-mark-ring))
10609 (setq org-mark-ring-last-goto p)
10610 (setq m (car p))
10611 (pop-to-buffer-same-window (marker-buffer m))
10612 (goto-char m)
10613 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10615 (defun org-add-angle-brackets (s)
10616 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10617 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10620 ;;; Following specific links
10622 (defvar org-agenda-buffer-tmp-name)
10623 (defvar org-agenda-start-on-weekday)
10624 (defun org-follow-timestamp-link ()
10625 "Open an agenda view for the time-stamp date/range at point."
10626 (cond
10627 ((org-at-date-range-p t)
10628 (let ((org-agenda-start-on-weekday)
10629 (t1 (match-string 1))
10630 (t2 (match-string 2)) tt1 tt2)
10631 (setq tt1 (time-to-days (org-time-string-to-time t1))
10632 tt2 (time-to-days (org-time-string-to-time t2)))
10633 (let ((org-agenda-buffer-tmp-name
10634 (format "*Org Agenda(a:%s)"
10635 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10636 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10637 ((org-at-timestamp-p 'lax)
10638 (let ((org-agenda-buffer-tmp-name
10639 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10640 (org-agenda-list nil (time-to-days (org-time-string-to-time
10641 (substring (match-string 1) 0 10)))
10642 1)))
10643 (t (error "This should not happen"))))
10646 ;;; Following file links
10647 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10648 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10649 (declare-function mailcap-mime-info
10650 "mailcap" (string &optional request no-decode))
10651 (defvar org-wait nil)
10652 (defun org-open-file (path &optional in-emacs line search)
10653 "Open the file at PATH.
10654 First, this expands any special file name abbreviations. Then the
10655 configuration variable `org-file-apps' is checked if it contains an
10656 entry for this file type, and if yes, the corresponding command is launched.
10658 If no application is found, Emacs simply visits the file.
10660 With optional prefix argument IN-EMACS, Emacs will visit the file.
10661 With a double \\[universal-argument] \\[universal-argument] \
10662 prefix arg, Org tries to avoid opening in Emacs
10663 and to use an external application to visit the file.
10665 Optional LINE specifies a line to go to, optional SEARCH a string
10666 to search for. If LINE or SEARCH is given, the file will be
10667 opened in Emacs, unless an entry from org-file-apps that makes
10668 use of groups in a regexp matches.
10670 If you want to change the way frames are used when following a
10671 link, please customize `org-link-frame-setup'.
10673 If the file does not exist, an error is thrown."
10674 (let* ((file (if (equal path "")
10675 buffer-file-name
10676 (substitute-in-file-name (expand-file-name path))))
10677 (file-apps (append org-file-apps (org-default-apps)))
10678 (apps (cl-remove-if
10679 'org-file-apps-entry-match-against-dlink-p file-apps))
10680 (apps-dlink (cl-remove-if-not
10681 'org-file-apps-entry-match-against-dlink-p file-apps))
10682 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10683 (dirp (unless remp (file-directory-p file)))
10684 (file (if (and dirp org-open-directory-means-index-dot-org)
10685 (concat (file-name-as-directory file) "index.org")
10686 file))
10687 (a-m-a-p (assq 'auto-mode apps))
10688 (dfile (downcase file))
10689 ;; Reconstruct the original link from the PATH, LINE and
10690 ;; SEARCH args.
10691 (link (cond (line (concat file "::" (number-to-string line)))
10692 (search (concat file "::" search))
10693 (t file)))
10694 (dlink (downcase link))
10695 (ext
10696 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10697 (match-string 1 dfile)))
10698 (save-position-maybe
10699 (let ((old-buffer (current-buffer))
10700 (old-pos (point))
10701 (old-mode major-mode))
10702 (lambda ()
10703 (and (derived-mode-p 'org-mode)
10704 (eq old-mode 'org-mode)
10705 (or (not (eq old-buffer (current-buffer)))
10706 (not (eq old-pos (point))))
10707 (org-mark-ring-push old-pos old-buffer)))))
10708 cmd link-match-data)
10709 (cond
10710 ((member in-emacs '((16) system))
10711 (setq cmd (cdr (assq 'system apps))))
10712 (in-emacs (setq cmd 'emacs))
10714 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10715 (and dirp (cdr (assq 'directory apps)))
10716 ;; First, try matching against apps-dlink if we
10717 ;; get a match here, store the match data for
10718 ;; later.
10719 (let ((match (assoc-default dlink apps-dlink
10720 'string-match)))
10721 (if match
10722 (progn (setq link-match-data (match-data))
10723 match)
10724 (progn (setq in-emacs (or in-emacs line search))
10725 nil))) ; if we have no match in apps-dlink,
10726 ; always open the file in emacs if line or search
10727 ; is given (for backwards compatibility)
10728 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10729 'string-match)
10730 (cdr (assoc ext apps))
10731 (cdr (assq t apps))))))
10732 (when (eq cmd 'system)
10733 (setq cmd (cdr (assq 'system apps))))
10734 (when (eq cmd 'default)
10735 (setq cmd (cdr (assoc t apps))))
10736 (when (eq cmd 'mailcap)
10737 (require 'mailcap)
10738 (mailcap-parse-mailcaps)
10739 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10740 (command (mailcap-mime-info mime-type)))
10741 (if (stringp command)
10742 (setq cmd command)
10743 (setq cmd 'emacs))))
10744 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10745 (not (file-exists-p file))
10746 (not org-open-non-existing-files))
10747 (user-error "No such file: %s" file))
10748 (cond
10749 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10750 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10751 (while (string-match "['\"]%s['\"]" cmd)
10752 (setq cmd (replace-match "%s" t t cmd)))
10753 (setq cmd (replace-regexp-in-string
10754 "%s"
10755 (shell-quote-argument (convert-standard-filename file))
10757 nil t))
10759 ;; Replace "%1", "%2" etc. in command with group matches from regex
10760 (save-match-data
10761 (let ((match-index 1)
10762 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10763 (set-match-data link-match-data)
10764 (while (<= match-index number-of-groups)
10765 (let ((regex (concat "%" (number-to-string match-index)))
10766 (replace-with (match-string match-index dlink)))
10767 (while (string-match regex cmd)
10768 (setq cmd (replace-match replace-with t t cmd))))
10769 (setq match-index (+ match-index 1)))))
10771 (save-window-excursion
10772 (message "Running %s...done" cmd)
10773 (start-process-shell-command cmd nil cmd)
10774 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10775 ((or (stringp cmd)
10776 (eq cmd 'emacs))
10777 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10778 (widen)
10779 (cond (line (org-goto-line line)
10780 (when (derived-mode-p 'org-mode) (org-reveal)))
10781 (search (condition-case err
10782 (org-link-search search)
10783 ;; Save position before error-ing out so user
10784 ;; can easily move back to the original buffer.
10785 (error (funcall save-position-maybe)
10786 (error (nth 1 err)))))))
10787 ((functionp cmd)
10788 (save-match-data
10789 (set-match-data link-match-data)
10790 (condition-case nil
10791 (funcall cmd file link)
10792 ;; FIXME: Remove this check when most default installations
10793 ;; of Emacs have at least Org 9.0.
10794 ((debug wrong-number-of-arguments wrong-type-argument
10795 invalid-function)
10796 (user-error "Please see Org News for version 9.0 about \
10797 `org-file-apps'--Lisp error: %S" cmd)))))
10798 ((consp cmd)
10799 ;; FIXME: Remove this check when most default installations of
10800 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10801 ;; fall back to `org-link-frame-setup' for an old usage of
10802 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10803 (user-error "Please see Org News for version 9.0 about \
10804 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10805 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10806 (funcall save-position-maybe)))
10808 (defun org-file-apps-entry-match-against-dlink-p (entry)
10809 "This function returns non-nil if `entry' uses a regular
10810 expression which should be matched against the whole link by
10811 org-open-file.
10813 It assumes that is the case when the entry uses a regular
10814 expression which has at least one grouping construct and the
10815 action is either a lisp form or a command string containing
10816 `%1', i.e. using at least one subexpression match as a
10817 parameter."
10818 (let ((selector (car entry))
10819 (action (cdr entry)))
10820 (if (stringp selector)
10821 (and (> (regexp-opt-depth selector) 0)
10822 (or (and (stringp action)
10823 (string-match "%[0-9]" action))
10824 (consp action)))
10825 nil)))
10827 (defun org-default-apps ()
10828 "Return the default applications for this operating system."
10829 (cond
10830 ((eq system-type 'darwin)
10831 org-file-apps-defaults-macosx)
10832 ((eq system-type 'windows-nt)
10833 org-file-apps-defaults-windowsnt)
10834 (t org-file-apps-defaults-gnu)))
10836 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10837 "Convert extensions to regular expressions in the cars of LIST.
10838 Also, weed out any non-string entries, because the return value is used
10839 only for regexp matching.
10840 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10841 point to the symbol `emacs', indicating that the file should
10842 be opened in Emacs."
10843 (append
10844 (delq nil
10845 (mapcar (lambda (x)
10846 (unless (not (stringp (car x)))
10847 (if (string-match "\\W" (car x))
10849 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10850 list))
10851 (when add-auto-mode
10852 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10854 (defvar ange-ftp-name-format)
10855 (defun org-file-remote-p (file)
10856 "Test whether FILE specifies a location on a remote system.
10857 Return non-nil if the location is indeed remote.
10859 For example, the filename \"/user@host:/foo\" specifies a location
10860 on the system \"/user@host:\"."
10861 (cond ((fboundp 'file-remote-p)
10862 (file-remote-p file))
10863 ((fboundp 'tramp-handle-file-remote-p)
10864 (tramp-handle-file-remote-p file))
10865 ((and (boundp 'ange-ftp-name-format)
10866 (string-match (car ange-ftp-name-format) file))
10867 t)))
10870 ;;;; Refiling
10872 (defun org-get-org-file ()
10873 "Read a filename, with default directory `org-directory'."
10874 (let ((default (or org-default-notes-file remember-data-file)))
10875 (read-file-name (format "File name [%s]: " default)
10876 (file-name-as-directory org-directory)
10877 default)))
10879 (defun org-notes-order-reversed-p ()
10880 "Check if the current file should receive notes in reversed order."
10881 (cond
10882 ((not org-reverse-note-order) nil)
10883 ((eq t org-reverse-note-order) t)
10884 ((not (listp org-reverse-note-order)) nil)
10885 (t (catch 'exit
10886 (dolist (entry org-reverse-note-order)
10887 (when (string-match (car entry) buffer-file-name)
10888 (throw 'exit (cdr entry))))))))
10890 (defvar org-refile-target-table nil
10891 "The list of refile targets, created by `org-refile'.")
10893 (defvar org-agenda-new-buffers nil
10894 "Buffers created to visit agenda files.")
10896 (defvar org-refile-cache nil
10897 "Cache for refile targets.")
10899 (defvar org-refile-markers nil
10900 "All the markers used for caching refile locations.")
10902 (defun org-refile-marker (pos)
10903 "Get a new refile marker, but only if caching is in use."
10904 (if (not org-refile-use-cache)
10906 (let ((m (make-marker)))
10907 (move-marker m pos)
10908 (push m org-refile-markers)
10909 m)))
10911 (defun org-refile-cache-clear ()
10912 "Clear the refile cache and disable all the markers."
10913 (dolist (m org-refile-markers) (move-marker m nil))
10914 (setq org-refile-markers nil)
10915 (setq org-refile-cache nil)
10916 (message "Refile cache has been cleared"))
10918 (defun org-refile-cache-check-set (set)
10919 "Check if all the markers in the cache still have live buffers."
10920 (let (marker)
10921 (catch 'exit
10922 (while (and set (setq marker (nth 3 (pop set))))
10923 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10924 (when (and marker (null (marker-buffer marker)))
10925 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10926 (sit-for 3)
10927 (throw 'exit nil)))
10928 t)))
10930 (defun org-refile-cache-put (set &rest identifiers)
10931 "Push the refile targets SET into the cache, under IDENTIFIERS."
10932 (let* ((key (sha1 (prin1-to-string identifiers)))
10933 (entry (assoc key org-refile-cache)))
10934 (if entry
10935 (setcdr entry set)
10936 (push (cons key set) org-refile-cache))))
10938 (defun org-refile-cache-get (&rest identifiers)
10939 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10940 (cond
10941 ((not org-refile-cache) nil)
10942 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10944 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10945 org-refile-cache))))
10946 (and set (org-refile-cache-check-set set) set)))))
10948 (defvar org-outline-path-cache nil
10949 "Alist between buffer positions and outline paths.
10950 It value is an alist (POSITION . PATH) where POSITION is the
10951 buffer position at the beginning of an entry and PATH is a list
10952 of strings describing the outline path for that entry, in reverse
10953 order.")
10955 (defun org-refile-get-targets (&optional default-buffer)
10956 "Produce a table with refile targets."
10957 (let ((case-fold-search nil)
10958 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10959 (entries (or org-refile-targets '((nil . (:level . 1)))))
10960 targets tgs files desc descre)
10961 (message "Getting targets...")
10962 (with-current-buffer (or default-buffer (current-buffer))
10963 (dolist (entry entries)
10964 (setq files (car entry) desc (cdr entry))
10965 (cond
10966 ((null files) (setq files (list (current-buffer))))
10967 ((eq files 'org-agenda-files)
10968 (setq files (org-agenda-files 'unrestricted)))
10969 ((and (symbolp files) (fboundp files))
10970 (setq files (funcall files)))
10971 ((and (symbolp files) (boundp files))
10972 (setq files (symbol-value files))))
10973 (when (stringp files) (setq files (list files)))
10974 (cond
10975 ((eq (car desc) :tag)
10976 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10977 ((eq (car desc) :todo)
10978 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10979 ((eq (car desc) :regexp)
10980 (setq descre (cdr desc)))
10981 ((eq (car desc) :level)
10982 (setq descre (concat "^\\*\\{" (number-to-string
10983 (if org-odd-levels-only
10984 (1- (* 2 (cdr desc)))
10985 (cdr desc)))
10986 "\\}[ \t]")))
10987 ((eq (car desc) :maxlevel)
10988 (setq descre (concat "^\\*\\{1," (number-to-string
10989 (if org-odd-levels-only
10990 (1- (* 2 (cdr desc)))
10991 (cdr desc)))
10992 "\\}[ \t]")))
10993 (t (error "Bad refiling target description %s" desc)))
10994 (dolist (f files)
10995 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10997 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10998 (progn
10999 (when (bufferp f)
11000 (setq f (buffer-file-name (buffer-base-buffer f))))
11001 (setq f (and f (expand-file-name f)))
11002 (when (eq org-refile-use-outline-path 'file)
11003 (push (list (file-name-nondirectory f) f nil nil) tgs))
11004 (when (eq org-refile-use-outline-path 'buffer-name)
11005 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11006 (when (eq org-refile-use-outline-path 'full-file-path)
11007 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11008 (org-with-wide-buffer
11009 (goto-char (point-min))
11010 (setq org-outline-path-cache nil)
11011 (while (re-search-forward descre nil t)
11012 (beginning-of-line)
11013 (let ((case-fold-search nil))
11014 (looking-at org-complex-heading-regexp))
11015 (let ((begin (point))
11016 (heading (match-string-no-properties 4)))
11017 (unless (or (and
11018 org-refile-target-verify-function
11019 (not
11020 (funcall org-refile-target-verify-function)))
11021 (not heading))
11022 (let ((re (format org-complex-heading-regexp-format
11023 (regexp-quote heading)))
11024 (target
11025 (if (not org-refile-use-outline-path) heading
11026 (mapconcat
11027 #'identity
11028 (append
11029 (pcase org-refile-use-outline-path
11030 (`file (list (file-name-nondirectory
11031 (buffer-file-name
11032 (buffer-base-buffer)))))
11033 (`full-file-path
11034 (list (buffer-file-name
11035 (buffer-base-buffer))))
11036 (`buffer-name
11037 (list (buffer-name
11038 (buffer-base-buffer))))
11039 (_ nil))
11040 (mapcar (lambda (s) (replace-regexp-in-string
11041 "/" "\\/" s nil t))
11042 (org-get-outline-path t t)))
11043 "/"))))
11044 (push (list target f re (org-refile-marker (point)))
11045 tgs)))
11046 (when (= (point) begin)
11047 ;; Verification function has not moved point.
11048 (end-of-line)))))))
11049 (when org-refile-use-cache
11050 (org-refile-cache-put tgs (buffer-file-name) descre))
11051 (setq targets (append tgs targets))))))
11052 (message "Getting targets...done")
11053 (delete-dups (nreverse targets))))
11055 (defun org--get-outline-path-1 (&optional use-cache)
11056 "Return outline path to current headline.
11058 Outline path is a list of strings, in reverse order. When
11059 optional argument USE-CACHE is non-nil, make use of a cache. See
11060 `org-get-outline-path' for details.
11062 Assume buffer is widened and point is on a headline."
11063 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11064 (let ((p (point))
11065 (heading (let ((case-fold-search nil))
11066 (looking-at org-complex-heading-regexp)
11067 (if (not (match-end 4)) ""
11068 ;; Remove statistics cookies.
11069 (org-trim
11070 (org-link-display-format
11071 (replace-regexp-in-string
11072 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11073 (match-string-no-properties 4))))))))
11074 (if (org-up-heading-safe)
11075 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11076 (when use-cache
11077 (push (cons p path) org-outline-path-cache))
11078 path)
11079 ;; This is a new root node. Since we assume we are moving
11080 ;; forward, we can drop previous cache so as to limit number
11081 ;; of associations there.
11082 (let ((path (list heading)))
11083 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11084 path)))))
11086 (defun org-get-outline-path (&optional with-self use-cache)
11087 "Return the outline path to the current entry.
11089 An outline path is a list of ancestors for current headline, as
11090 a list of strings. Statistics cookies are removed and links are
11091 replaced with their description, if any, or their path otherwise.
11093 When optional argument WITH-SELF is non-nil, the path also
11094 includes the current headline.
11096 When optional argument USE-CACHE is non-nil, cache outline paths
11097 between calls to this function so as to avoid backtracking. This
11098 argument is useful when planning to find more than one outline
11099 path in the same document. In that case, there are two
11100 conditions to satisfy:
11101 - `org-outline-path-cache' is set to nil before starting the
11102 process;
11103 - outline paths are computed by increasing buffer positions."
11104 (org-with-wide-buffer
11105 (and (or (and with-self (org-back-to-heading t))
11106 (org-up-heading-safe))
11107 (reverse (org--get-outline-path-1 use-cache)))))
11109 (defun org-format-outline-path (path &optional width prefix separator)
11110 "Format the outline path PATH for display.
11111 WIDTH is the maximum number of characters that is available.
11112 PREFIX is a prefix to be included in the returned string,
11113 such as the file name.
11114 SEPARATOR is inserted between the different parts of the path,
11115 the default is \"/\"."
11116 (setq width (or width 79))
11117 (setq path (delq nil path))
11118 (unless (> width 0)
11119 (user-error "Argument `width' must be positive"))
11120 (setq separator (or separator "/"))
11121 (let* ((org-odd-levels-only nil)
11122 (fpath (concat
11123 prefix (and prefix path separator)
11124 (mapconcat
11125 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11126 (cl-loop for head in path
11127 for n from 0
11128 collect (org-add-props
11129 head nil 'face
11130 (nth (% n org-n-level-faces) org-level-faces)))
11131 separator))))
11132 (when (> (length fpath) width)
11133 (if (< width 7)
11134 ;; It's unlikely that `width' will be this small, but don't
11135 ;; waste characters by adding ".." if it is.
11136 (setq fpath (substring fpath 0 width))
11137 (setf (substring fpath (- width 2)) "..")))
11138 fpath))
11140 (defun org-display-outline-path (&optional file current separator just-return-string)
11141 "Display the current outline path in the echo area.
11143 If FILE is non-nil, prepend the output with the file name.
11144 If CURRENT is non-nil, append the current heading to the output.
11145 SEPARATOR is passed through to `org-format-outline-path'. It separates
11146 the different parts of the path and defaults to \"/\".
11147 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11148 (interactive "P")
11149 (let* (case-fold-search
11150 (bfn (buffer-file-name (buffer-base-buffer)))
11151 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11152 res)
11153 (when current (setq path (append path
11154 (save-excursion
11155 (org-back-to-heading t)
11156 (when (looking-at org-complex-heading-regexp)
11157 (list (match-string 4)))))))
11158 (setq res
11159 (org-format-outline-path
11160 path
11161 (1- (frame-width))
11162 (and file bfn (concat (file-name-nondirectory bfn) separator))
11163 separator))
11164 (if just-return-string
11165 (org-no-properties res)
11166 (org-unlogged-message "%s" res))))
11168 (defvar org-refile-history nil
11169 "History for refiling operations.")
11171 (defvar org-after-refile-insert-hook nil
11172 "Hook run after `org-refile' has inserted its stuff at the new location.
11173 Note that this is still *before* the stuff will be removed from
11174 the *old* location.")
11176 (defvar org-capture-last-stored-marker)
11177 (defvar org-refile-keep nil
11178 "Non-nil means `org-refile' will copy instead of refile.")
11180 (defun org-copy ()
11181 "Like `org-refile', but copy."
11182 (interactive)
11183 (let ((org-refile-keep t))
11184 (funcall 'org-refile nil nil nil "Copy")))
11186 (defun org-refile (&optional arg default-buffer rfloc msg)
11187 "Move the entry or entries at point to another heading.
11189 The list of target headings is compiled using the information in
11190 `org-refile-targets', which see.
11192 At the target location, the entry is filed as a subitem of the
11193 target heading. Depending on `org-reverse-note-order', the new
11194 subitem will either be the first or the last subitem.
11196 If there is an active region, all entries in that region will be
11197 refiled. However, the region must fulfill the requirement that
11198 the first heading sets the top-level of the moved text.
11200 With a `\\[universal-argument]' ARG, the command will only visit the target \
11201 location
11202 and not actually move anything.
11204 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11205 location where the last
11206 refiling operation has put the subtree.
11208 With a numeric prefix argument of `2', refile to the running clock.
11210 With a numeric prefix argument of `3', emulate `org-refile-keep'
11211 being set to t and copy to the target location, don't move it.
11212 Beware that keeping refiled entries may result in duplicated ID
11213 properties.
11215 RFLOC can be a refile location obtained in a different way.
11217 MSG is a string to replace \"Refile\" in the default prompt with
11218 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11220 See also `org-refile-use-outline-path'.
11222 If you are using target caching (see `org-refile-use-cache'), you
11223 have to clear the target cache in order to find new targets.
11224 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11225 prefix argument (`C-u C-u C-u C-c C-w')."
11226 (interactive "P")
11227 (if (member arg '(0 (64)))
11228 (org-refile-cache-clear)
11229 (let* ((actionmsg (cond (msg msg)
11230 ((equal arg 3) "Refile (and keep)")
11231 (t "Refile")))
11232 (regionp (org-region-active-p))
11233 (region-start (and regionp (region-beginning)))
11234 (region-end (and regionp (region-end)))
11235 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11236 pos it nbuf file level reversed)
11237 (setq last-command nil)
11238 (when regionp
11239 (goto-char region-start)
11240 (or (bolp) (goto-char (point-at-bol)))
11241 (setq region-start (point))
11242 (unless (or (org-kill-is-subtree-p
11243 (buffer-substring region-start region-end))
11244 (prog1 org-refile-active-region-within-subtree
11245 (let ((s (point-at-eol)))
11246 (org-toggle-heading)
11247 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11248 (user-error "The region is not a (sequence of) subtree(s)")))
11249 (if (equal arg '(16))
11250 (org-refile-goto-last-stored)
11251 (when (or
11252 (and (equal arg 2)
11253 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11254 (prog1
11255 (setq it (list (or org-clock-heading "running clock")
11256 (buffer-file-name
11257 (marker-buffer org-clock-hd-marker))
11259 (marker-position org-clock-hd-marker)))
11260 (setq arg nil)))
11261 (setq it
11262 (or rfloc
11263 (let (heading-text)
11264 (save-excursion
11265 (unless (and arg (listp arg))
11266 (org-back-to-heading t)
11267 (setq heading-text
11268 (replace-regexp-in-string
11269 org-bracket-link-regexp
11270 "\\3"
11271 (or (nth 4 (org-heading-components))
11272 ""))))
11273 (org-refile-get-location
11274 (cond ((and arg (listp arg)) "Goto")
11275 (regionp (concat actionmsg " region to"))
11276 (t (concat actionmsg " subtree \""
11277 heading-text "\" to")))
11278 default-buffer
11279 (and (not (equal '(4) arg))
11280 org-refile-allow-creating-parent-nodes)))))))
11281 (setq file (nth 1 it)
11282 pos (nth 3 it))
11283 (when (and (not arg)
11285 (equal (buffer-file-name) file)
11286 (if regionp
11287 (and (>= pos region-start)
11288 (<= pos region-end))
11289 (and (>= pos (point))
11290 (< pos (save-excursion
11291 (org-end-of-subtree t t))))))
11292 (error "Cannot refile to position inside the tree or region"))
11293 (setq nbuf (or (find-buffer-visiting file)
11294 (find-file-noselect file)))
11295 (if (and arg (not (equal arg 3)))
11296 (progn
11297 (pop-to-buffer-same-window nbuf)
11298 (goto-char (cond (pos)
11299 ((org-notes-order-reversed-p) (point-min))
11300 (t (point-max))))
11301 (org-show-context 'org-goto))
11302 (if regionp
11303 (progn
11304 (org-kill-new (buffer-substring region-start region-end))
11305 (org-save-markers-in-region region-start region-end))
11306 (org-copy-subtree 1 nil t))
11307 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11308 (find-file-noselect file)))
11309 (setq reversed (org-notes-order-reversed-p))
11310 (org-with-wide-buffer
11311 (if pos
11312 (progn
11313 (goto-char pos)
11314 (setq level (org-get-valid-level (funcall outline-level) 1))
11315 (goto-char
11316 (if reversed
11317 (or (outline-next-heading) (point-max))
11318 (or (save-excursion (org-get-next-sibling))
11319 (org-end-of-subtree t t)
11320 (point-max)))))
11321 (setq level 1)
11322 (if (not reversed)
11323 (goto-char (point-max))
11324 (goto-char (point-min))
11325 (or (outline-next-heading) (goto-char (point-max)))))
11326 (unless (bolp) (newline))
11327 (org-paste-subtree level nil nil t)
11328 (when org-log-refile
11329 (org-add-log-setup 'refile nil nil org-log-refile)
11330 (unless (eq org-log-refile 'note)
11331 (save-excursion (org-add-log-note))))
11332 (and org-auto-align-tags
11333 (let ((org-loop-over-headlines-in-active-region nil))
11334 (org-align-tags)))
11335 (let ((bookmark-name (plist-get org-bookmark-names-plist
11336 :last-refile)))
11337 (when bookmark-name
11338 (with-demoted-errors
11339 (bookmark-set bookmark-name))))
11340 ;; If we are refiling for capture, make sure that the
11341 ;; last-capture pointers point here
11342 (when (bound-and-true-p org-capture-is-refiling)
11343 (let ((bookmark-name (plist-get org-bookmark-names-plist
11344 :last-capture-marker)))
11345 (when bookmark-name
11346 (with-demoted-errors
11347 (bookmark-set bookmark-name))))
11348 (move-marker org-capture-last-stored-marker (point)))
11349 (when (fboundp 'deactivate-mark) (deactivate-mark))
11350 (run-hooks 'org-after-refile-insert-hook)))
11351 (unless org-refile-keep
11352 (if regionp
11353 (delete-region (point) (+ (point) (- region-end region-start)))
11354 (org-preserve-local-variables
11355 (delete-region
11356 (and (org-back-to-heading t) (point))
11357 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11358 (when (featurep 'org-inlinetask)
11359 (org-inlinetask-remove-END-maybe))
11360 (setq org-markers-to-move nil)
11361 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11363 (defun org-refile-goto-last-stored ()
11364 "Go to the location where the last refile was stored."
11365 (interactive)
11366 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11367 (message "This is the location of the last refile"))
11369 (defun org-refile--get-location (refloc tbl)
11370 "When user refile to REFLOC, find the associated target in TBL.
11371 Also check `org-refile-target-table'."
11372 (car (delq
11374 (mapcar
11375 (lambda (r) (or (assoc r tbl)
11376 (assoc r org-refile-target-table)))
11377 (list (replace-regexp-in-string "/$" "" refloc)
11378 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11380 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11381 "Prompt the user for a refile location, using PROMPT.
11382 PROMPT should not be suffixed with a colon and a space, because
11383 this function appends the default value from
11384 `org-refile-history' automatically, if that is not empty."
11385 (let ((org-refile-targets org-refile-targets)
11386 (org-refile-use-outline-path org-refile-use-outline-path))
11387 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11388 (unless org-refile-target-table
11389 (user-error "No refile targets"))
11390 (let* ((cbuf (current-buffer))
11391 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11392 (cfunc (if (and org-refile-use-outline-path
11393 org-outline-path-complete-in-steps)
11394 #'org-olpath-completing-read
11395 #'completing-read))
11396 (extra (if org-refile-use-outline-path "/" ""))
11397 (cbnex (concat (buffer-name) extra))
11398 (filename (and cfn (expand-file-name cfn)))
11399 (tbl (mapcar
11400 (lambda (x)
11401 (if (and (not (member org-refile-use-outline-path
11402 '(file full-file-path)))
11403 (not (equal filename (nth 1 x))))
11404 (cons (concat (car x) extra " ("
11405 (file-name-nondirectory (nth 1 x)) ")")
11406 (cdr x))
11407 (cons (concat (car x) extra) (cdr x))))
11408 org-refile-target-table))
11409 (completion-ignore-case t)
11410 cdef
11411 (prompt (concat prompt
11412 (or (and (car org-refile-history)
11413 (concat " (default " (car org-refile-history) ")"))
11414 (and (assoc cbnex tbl) (setq cdef cbnex)
11415 (concat " (default " cbnex ")"))) ": "))
11416 pa answ parent-target child parent old-hist)
11417 (setq old-hist org-refile-history)
11418 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11419 nil 'org-refile-history (or cdef (car org-refile-history))))
11420 (if (setq pa (org-refile--get-location answ tbl))
11421 (progn
11422 (org-refile-check-position pa)
11423 (when (or (not org-refile-history)
11424 (not (eq old-hist org-refile-history))
11425 (not (equal (car pa) (car org-refile-history))))
11426 (setq org-refile-history
11427 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11428 org-refile-history
11429 (cdr org-refile-history))))
11430 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11431 (pop org-refile-history)))
11433 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11434 (progn
11435 (setq parent (match-string 1 answ)
11436 child (match-string 2 answ))
11437 (setq parent-target (org-refile--get-location parent tbl))
11438 (when (and parent-target
11439 (or (eq new-nodes t)
11440 (and (eq new-nodes 'confirm)
11441 (y-or-n-p (format "Create new node \"%s\"? "
11442 child)))))
11443 (org-refile-new-child parent-target child)))
11444 (user-error "Invalid target location")))))
11446 (declare-function org-string-nw-p "org-macs" (s))
11447 (defun org-refile-check-position (refile-pointer)
11448 "Check if the refile pointer matches the headline to which it points."
11449 (let* ((file (nth 1 refile-pointer))
11450 (re (nth 2 refile-pointer))
11451 (pos (nth 3 refile-pointer))
11452 buffer)
11453 (if (and (not (markerp pos)) (not file))
11454 (user-error "Please indicate a target file in the refile path")
11455 (when (org-string-nw-p re)
11456 (setq buffer (if (markerp pos)
11457 (marker-buffer pos)
11458 (or (find-buffer-visiting file)
11459 (find-file-noselect file))))
11460 (with-current-buffer buffer
11461 (org-with-wide-buffer
11462 (goto-char pos)
11463 (beginning-of-line 1)
11464 (unless (looking-at-p re)
11465 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11467 (defun org-refile-new-child (parent-target child)
11468 "Use refile target PARENT-TARGET to add new CHILD below it."
11469 (unless parent-target
11470 (error "Cannot find parent for new node"))
11471 (let ((file (nth 1 parent-target))
11472 (pos (nth 3 parent-target))
11473 level)
11474 (with-current-buffer (or (find-buffer-visiting file)
11475 (find-file-noselect file))
11476 (org-with-wide-buffer
11477 (if pos
11478 (goto-char pos)
11479 (goto-char (point-max))
11480 (unless (bolp) (newline)))
11481 (when (looking-at org-outline-regexp)
11482 (setq level (funcall outline-level))
11483 (org-end-of-subtree t t))
11484 (org-back-over-empty-lines)
11485 (insert "\n" (make-string
11486 (if pos (org-get-valid-level level 1) 1) ?*)
11487 " " child "\n")
11488 (beginning-of-line 0)
11489 (list (concat (car parent-target) "/" child) file "" (point))))))
11491 (defun org-olpath-completing-read (prompt collection &rest args)
11492 "Read an outline path like a file name."
11493 (let ((thetable collection))
11494 (apply #'completing-read
11495 prompt
11496 (lambda (string predicate &optional flag)
11497 (cond
11498 ((eq flag nil) (try-completion string thetable))
11499 ((eq flag t)
11500 (let ((l (length string)))
11501 (mapcar (lambda (x)
11502 (let ((r (substring x l))
11503 (f (if (string-match " ([^)]*)$" x)
11504 (match-string 0 x)
11505 "")))
11506 (if (string-match "/" r)
11507 (concat string (substring r 0 (match-end 0)) f)
11508 x)))
11509 (all-completions string thetable predicate))))
11510 ;; Exact match?
11511 ((eq flag 'lambda) (assoc string thetable))))
11512 args)))
11514 ;;;; Dynamic blocks
11516 (defun org-find-dblock (name)
11517 "Find the first dynamic block with name NAME in the buffer.
11518 If not found, stay at current position and return nil."
11519 (let ((case-fold-search t) pos)
11520 (save-excursion
11521 (goto-char (point-min))
11522 (setq pos (and (re-search-forward
11523 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11524 (match-beginning 0))))
11525 (when pos (goto-char pos))
11526 pos))
11528 (defun org-create-dblock (plist)
11529 "Create a dynamic block section, with parameters taken from PLIST.
11530 PLIST must contain a :name entry which is used as the name of the block."
11531 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11532 (end-of-line 1)
11533 (newline))
11534 (let ((col (current-column))
11535 (name (plist-get plist :name)))
11536 (insert "#+BEGIN: " name)
11537 (while plist
11538 (if (eq (car plist) :name)
11539 (setq plist (cddr plist))
11540 (insert " " (prin1-to-string (pop plist)))))
11541 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11542 (beginning-of-line -2)))
11544 (defun org-prepare-dblock ()
11545 "Prepare dynamic block for refresh.
11546 This empties the block, puts the cursor at the insert position and returns
11547 the property list including an extra property :name with the block name."
11548 (unless (looking-at org-dblock-start-re)
11549 (user-error "Not at a dynamic block"))
11550 (let* ((begdel (1+ (match-end 0)))
11551 (name (org-no-properties (match-string 1)))
11552 (params (append (list :name name)
11553 (read (concat "(" (match-string 3) ")")))))
11554 (save-excursion
11555 (beginning-of-line 1)
11556 (skip-chars-forward " \t")
11557 (setq params (plist-put params :indentation-column (current-column))))
11558 (unless (re-search-forward org-dblock-end-re nil t)
11559 (error "Dynamic block not terminated"))
11560 (setq params
11561 (append params
11562 (list :content (buffer-substring
11563 begdel (match-beginning 0)))))
11564 (delete-region begdel (match-beginning 0))
11565 (goto-char begdel)
11566 (open-line 1)
11567 params))
11569 (defun org-map-dblocks (&optional command)
11570 "Apply COMMAND to all dynamic blocks in the current buffer.
11571 If COMMAND is not given, use `org-update-dblock'."
11572 (let ((cmd (or command 'org-update-dblock)))
11573 (save-excursion
11574 (goto-char (point-min))
11575 (while (re-search-forward org-dblock-start-re nil t)
11576 (goto-char (match-beginning 0))
11577 (save-excursion
11578 (condition-case nil
11579 (funcall cmd)
11580 (error (message "Error during update of dynamic block"))))
11581 (unless (re-search-forward org-dblock-end-re nil t)
11582 (error "Dynamic block not terminated"))))))
11584 (defun org-dblock-update (&optional arg)
11585 "User command for updating dynamic blocks.
11586 Update the dynamic block at point. With prefix ARG, update all dynamic
11587 blocks in the buffer."
11588 (interactive "P")
11589 (if arg
11590 (org-update-all-dblocks)
11591 (or (looking-at org-dblock-start-re)
11592 (org-beginning-of-dblock))
11593 (org-update-dblock)))
11595 (defun org-update-dblock ()
11596 "Update the dynamic block at point.
11597 This means to empty the block, parse for parameters and then call
11598 the correct writing function."
11599 (interactive)
11600 (save-excursion
11601 (let* ((win (selected-window))
11602 (pos (point))
11603 (line (org-current-line))
11604 (params (org-prepare-dblock))
11605 (name (plist-get params :name))
11606 (indent (plist-get params :indentation-column))
11607 (cmd (intern (concat "org-dblock-write:" name))))
11608 (message "Updating dynamic block `%s' at line %d..." name line)
11609 (funcall cmd params)
11610 (message "Updating dynamic block `%s' at line %d...done" name line)
11611 (goto-char pos)
11612 (when (and indent (> indent 0))
11613 (setq indent (make-string indent ?\ ))
11614 (save-excursion
11615 (select-window win)
11616 (org-beginning-of-dblock)
11617 (forward-line 1)
11618 (while (not (looking-at org-dblock-end-re))
11619 (insert indent)
11620 (beginning-of-line 2))
11621 (when (looking-at org-dblock-end-re)
11622 (and (looking-at "[ \t]+")
11623 (replace-match ""))
11624 (insert indent)))))))
11626 (defun org-beginning-of-dblock ()
11627 "Find the beginning of the dynamic block at point.
11628 Error if there is no such block at point."
11629 (let ((pos (point))
11630 beg)
11631 (end-of-line 1)
11632 (if (and (re-search-backward org-dblock-start-re nil t)
11633 (setq beg (match-beginning 0))
11634 (re-search-forward org-dblock-end-re nil t)
11635 (> (match-end 0) pos))
11636 (goto-char beg)
11637 (goto-char pos)
11638 (error "Not in a dynamic block"))))
11640 (defun org-update-all-dblocks ()
11641 "Update all dynamic blocks in the buffer.
11642 This function can be used in a hook."
11643 (interactive)
11644 (when (derived-mode-p 'org-mode)
11645 (org-map-dblocks 'org-update-dblock)))
11648 ;;;; Completion
11650 (declare-function org-export-backend-options "ox" (cl-x) t)
11651 (defun org-get-export-keywords ()
11652 "Return a list of all currently understood export keywords.
11653 Export keywords include options, block names, attributes and
11654 keywords relative to each registered export back-end."
11655 (let (keywords)
11656 (dolist (backend
11657 (bound-and-true-p org-export-registered-backends)
11658 (delq nil keywords))
11659 ;; Back-end name (for keywords, like #+LATEX:)
11660 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11661 (dolist (option-entry (org-export-backend-options backend))
11662 ;; Back-end options.
11663 (push (nth 1 option-entry) keywords)))))
11665 (defconst org-options-keywords
11666 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11667 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11668 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11669 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11670 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11672 (defcustom org-structure-template-alist
11673 '(("a" . "export ascii")
11674 ("c" . "center")
11675 ("C" . "comment")
11676 ("e" . "example")
11677 ("E" . "export")
11678 ("h" . "export html")
11679 ("l" . "export latex")
11680 ("q" . "quote")
11681 ("s" . "src")
11682 ("v" . "verse"))
11683 "An alist of keys and block types.
11684 `org-insert-structure-template' will display a menu with this
11685 list of templates to choose from. The block type is inserted,
11686 with \"#+BEGIN_\" and \"#+END_\" added automatically.
11688 The menu keys are defined by the car of each entry in this alist.
11689 If two entries have the keys \"a\" and \"aa\" respectively, the
11690 former will be inserted by typing \"a TAB/RET/SPC\" and the
11691 latter will be inserted by typing \"aa\". If an entry with the
11692 key \"aab\" is later added, it can be inserted by typing \"ab\".
11694 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11695 block can be inserted by pressing TAB after the string \"<KEY\"."
11696 :group 'org-edit-structure
11697 :type '(repeat
11698 (cons (string :tag "Key")
11699 (string :tag "Template")))
11700 :package-version '(Org . "9.2"))
11702 (defun org--insert-structure-template-mks ()
11703 "Present `org-structure-template-alist' with `org-mks'.
11705 Menus are added if keys require more than one keystroke. Tabs
11706 are added to single key entries when more than one stroke is
11707 needed. Keys longer than two characters are reduced to two
11708 characters."
11709 (let* (case-fold-search
11710 (templates (append org-structure-template-alist
11711 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11712 (keys (mapcar #'car templates))
11713 (start-letters
11714 (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11715 ;; Sort each element of `org-structure-template-alist' into
11716 ;; sublists according to the first letter.
11717 (superlist
11718 (mapcar (lambda (letter)
11719 (list letter
11720 (cl-remove-if-not
11721 (apply-partially #'string-match-p (concat "^" letter))
11722 templates :key #'car)))
11723 start-letters)))
11724 (org-mks
11725 (apply #'append
11726 ;; Make an `org-mks' table. If only one element is
11727 ;; present in a sublist, make it part of the top-menu,
11728 ;; otherwise make a submenu according to the starting
11729 ;; letter and populate it.
11730 (mapcar (lambda (sublist)
11731 (if (eq 1 (length (cadr sublist)))
11732 (mapcar (lambda (elm)
11733 (list (substring (car elm) 0 1)
11734 (cdr elm) ""))
11735 (cadr sublist))
11736 ;; Create submenu.
11737 (let* ((topkey (car sublist))
11738 (elms (cadr sublist))
11739 (keys (mapcar #'car elms))
11740 (long (> (length elms) 3)))
11741 (append
11742 (list
11743 ;; Make a description of the submenu.
11744 (list topkey
11745 (concat
11746 (mapconcat #'cdr
11747 (cl-subseq elms 0 (if long 3 (length elms)))
11748 ", ")
11749 (when long ", ..."))))
11750 ;; List of entries in submenu.
11751 (cl-mapcar #'list
11752 (org--insert-structure-template-unique-keys keys)
11753 (mapcar #'cdr elms)
11754 (make-list (length elms) ""))))))
11755 superlist))
11756 "Select a key\n============"
11757 "Key: ")))
11759 (defun org--insert-structure-template-unique-keys (keys)
11760 "Make a list of unique, two characters long elements from KEYS.
11762 Elements of length one have a tab appended. Elements of length
11763 two are kept as is. Longer elements are truncated to length two.
11765 If an element cannot be made unique, an error is raised."
11766 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11767 menu-keys)
11768 (dolist (key orderd-keys)
11769 (let ((potential-key
11770 (cl-case (length key)
11771 (1 (concat key "\t"))
11772 (2 key)
11773 (otherwise
11774 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11775 (mapcar (apply-partially #'concat (substring key 0 1))
11776 (split-string (substring key 1) "" t)))))))
11777 (if (or (not potential-key) (assoc potential-key menu-keys))
11778 (user-error "Could not make unique key for %s." key)
11779 (push (cons potential-key key) menu-keys))))
11780 (mapcar #'car
11781 (cl-sort menu-keys #'<
11782 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11784 (defun org-insert-structure-template (type)
11785 "Insert a block structure of the type #+begin_foo/#+end_foo.
11786 Select a block from `org-structure-template-alist' then type
11787 either RET, TAB or SPC to write the block type. With an active
11788 region, wrap the region in the block. Otherwise, insert an empty
11789 block."
11790 (interactive
11791 (list (pcase (org--insert-structure-template-mks)
11792 (`("\t" . ,_) (read-string "Structure type: "))
11793 (`(,_ ,choice . ,_) choice))))
11794 (let* ((region? (use-region-p))
11795 (col (current-indentation))
11796 (indent (make-string col ?\s))
11797 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11798 (region-string (and region?
11799 (buffer-substring (region-beginning)
11800 (region-end))))
11801 (region-end-blank (and region?
11802 (save-excursion
11803 (goto-char (region-end))
11804 (when (looking-at "[ \t]*$")
11805 (replace-match "")
11806 t))))
11808 (when region? (delete-region (region-beginning) (region-end)))
11809 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11810 (insert "\n"))
11811 (beginning-of-line)
11812 (save-excursion
11813 (insert
11814 (with-temp-buffer
11815 (when region?
11816 (insert region-string "\n")
11817 (when (string-match-p
11818 (concat "\\`" (regexp-opt '("example" "export" "src")))
11819 type)
11820 (org-escape-code-in-region (point-min) (point-max))))
11821 (goto-char (point-min))
11822 ;; Delete trailing white-lines.
11823 (when region?
11824 (while (looking-at-p "^[ \t]*$")
11825 (delete-region (line-beginning-position)
11826 (line-beginning-position 2))))
11827 (save-excursion
11828 (while (not (eobp))
11829 (unless (looking-at-p indent)
11830 (insert indent))
11831 (forward-line)))
11832 (insert
11833 indent
11834 (format "#+begin_%s%s\n" type (if special? " " "")))
11835 (unless region? (indent-to col))
11836 (setq s (point))
11837 (goto-char (point-max))
11838 (skip-chars-backward "[ \t\n]" s)
11839 (delete-region (line-end-position) (point-max))
11840 (insert "\n" indent
11841 (format "#+end_%s" (car (split-string type)))
11842 (if region-end-blank "" "\n"))
11843 (buffer-substring (point-min) (point))))
11844 (when (and (eobp) (not (bolp))) (insert "\n")))
11845 (cond (special?
11846 (end-of-line))
11848 (forward-line)
11849 (skip-chars-forward "[ \t]*")))))
11852 ;;;; TODO, DEADLINE, Comments
11854 (defun org-toggle-comment ()
11855 "Change the COMMENT state of an entry."
11856 (interactive)
11857 (save-excursion
11858 (org-back-to-heading)
11859 (let ((case-fold-search nil))
11860 (looking-at org-complex-heading-regexp))
11861 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11862 (skip-chars-forward " \t")
11863 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11864 (if (org-in-commented-heading-p t)
11865 (delete-region (point)
11866 (progn (search-forward " " (line-end-position) 'move)
11867 (skip-chars-forward " \t")
11868 (point)))
11869 (insert org-comment-string)
11870 (unless (eolp) (insert " ")))))
11872 (defvar org-last-todo-state-is-todo nil
11873 "This is non-nil when the last TODO state change led to a TODO state.
11874 If the last change removed the TODO tag or switched to DONE, then
11875 this is nil.")
11877 (defvar org-todo-setup-filter-hook nil
11878 "Hook for functions that pre-filter todo specs.
11879 Each function takes a todo spec and returns either nil or the spec
11880 transformed into canonical form." )
11882 (defvar org-todo-get-default-hook nil
11883 "Hook for functions that get a default item for todo.
11884 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11885 nil or a string to be used for the todo mark." )
11887 (defvar org-agenda-headline-snapshot-before-repeat)
11889 (defun org-current-effective-time ()
11890 "Return current time adjusted for `org-extend-today-until' variable."
11891 (let* ((ct (org-current-time))
11892 (dct (decode-time ct))
11893 (ct1
11894 (cond
11895 (org-use-last-clock-out-time-as-effective-time
11896 (or (org-clock-get-last-clock-out-time) ct))
11897 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11898 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11899 (t ct))))
11900 ct1))
11902 (defun org-todo-yesterday (&optional arg)
11903 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11904 (interactive "P")
11905 (if (eq major-mode 'org-agenda-mode)
11906 (apply 'org-agenda-todo-yesterday arg)
11907 (let* ((org-use-effective-time t)
11908 (hour (nth 2 (decode-time (org-current-time))))
11909 (org-extend-today-until (1+ hour)))
11910 (org-todo arg))))
11912 (defvar org-block-entry-blocking ""
11913 "First entry preventing the TODO state change.")
11915 (defun org-cancel-repeater ()
11916 "Cancel a repeater by setting its numeric value to zero."
11917 (interactive)
11918 (save-excursion
11919 (org-back-to-heading t)
11920 (let ((bound1 (point))
11921 (bound0 (save-excursion (outline-next-heading) (point))))
11922 (when (and (re-search-forward
11923 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11924 org-deadline-time-regexp "\\)\\|\\("
11925 org-ts-regexp "\\)")
11926 bound0 t)
11927 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11928 bound1 t))
11929 (replace-match "0" t nil nil 1)))))
11931 (defvar org-state)
11932 (defvar org-blocked-by-checkboxes)
11933 (defun org-todo (&optional arg)
11934 "Change the TODO state of an item.
11936 The state of an item is given by a keyword at the start of the heading,
11937 like
11938 *** TODO Write paper
11939 *** DONE Call mom
11941 The different keywords are specified in the variable `org-todo-keywords'.
11942 By default the available states are \"TODO\" and \"DONE\". So, for this
11943 example: when the item starts with TODO, it is changed to DONE.
11944 When it starts with DONE, the DONE is removed. And when neither TODO nor
11945 DONE are present, add TODO at the beginning of the heading.
11947 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11948 state.
11949 With numeric prefix ARG, switch to that state.
11950 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11951 next set of TODO \
11952 keywords (nextset).
11953 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11954 prefix, circumvent any state blocking.
11955 With a numeric prefix arg of 0, inhibit note taking for the change.
11956 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11958 When called through ELisp, arg is also interpreted in the following way:
11959 `none' -> empty state
11960 \"\" -> switch to empty state
11961 `done' -> switch to DONE
11962 `nextset' -> switch to the next set of keywords
11963 `previousset' -> switch to the previous set of keywords
11964 \"WAITING\" -> switch to the specified keyword, but only if it
11965 really is a member of `org-todo-keywords'."
11966 (interactive "P")
11967 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11968 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11969 'region-start-level 'region))
11970 org-loop-over-headlines-in-active-region)
11971 (org-map-entries
11972 `(org-todo ,arg)
11973 org-loop-over-headlines-in-active-region
11974 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11975 (when (equal arg '(16)) (setq arg 'nextset))
11976 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11977 (let ((org-blocker-hook org-blocker-hook)
11978 commentp
11979 case-fold-search)
11980 (when (equal arg '(64))
11981 (setq arg nil org-blocker-hook nil))
11982 (when (and org-blocker-hook
11983 (or org-inhibit-blocking
11984 (org-entry-get nil "NOBLOCKING")))
11985 (setq org-blocker-hook nil))
11986 (save-excursion
11987 (catch 'exit
11988 (org-back-to-heading t)
11989 (when (org-in-commented-heading-p t)
11990 (org-toggle-comment)
11991 (setq commentp t))
11992 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11993 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11994 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11995 (let* ((match-data (match-data))
11996 (startpos (copy-marker (line-beginning-position)))
11997 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11998 (org-log-done org-log-done)
11999 (org-log-repeat org-log-repeat)
12000 (org-todo-log-states org-todo-log-states)
12001 (org-inhibit-logging
12002 (if (equal arg 0)
12003 (progn (setq arg nil) 'note) org-inhibit-logging))
12004 (this (match-string 1))
12005 (hl-pos (match-beginning 0))
12006 (head (org-get-todo-sequence-head this))
12007 (ass (assoc head org-todo-kwd-alist))
12008 (interpret (nth 1 ass))
12009 (done-word (nth 3 ass))
12010 (final-done-word (nth 4 ass))
12011 (org-last-state (or this ""))
12012 (completion-ignore-case t)
12013 (member (member this org-todo-keywords-1))
12014 (tail (cdr member))
12015 (org-state (cond
12016 ((and org-todo-key-trigger
12017 (or (and (equal arg '(4))
12018 (eq org-use-fast-todo-selection 'prefix))
12019 (and (not arg) org-use-fast-todo-selection
12020 (not (eq org-use-fast-todo-selection
12021 'prefix)))))
12022 ;; Use fast selection.
12023 (org-fast-todo-selection))
12024 ((and (equal arg '(4))
12025 (or (not org-use-fast-todo-selection)
12026 (not org-todo-key-trigger)))
12027 ;; Read a state with completion.
12028 (completing-read
12029 "State: " (mapcar #'list org-todo-keywords-1)
12030 nil t))
12031 ((eq arg 'right)
12032 (if this
12033 (if tail (car tail) nil)
12034 (car org-todo-keywords-1)))
12035 ((eq arg 'left)
12036 (unless (equal member org-todo-keywords-1)
12037 (if this
12038 (nth (- (length org-todo-keywords-1)
12039 (length tail) 2)
12040 org-todo-keywords-1)
12041 (org-last org-todo-keywords-1))))
12042 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12043 (setq arg nil))) ;hack to fall back to cycling
12044 (arg
12045 ;; User or caller requests a specific state.
12046 (cond
12047 ((equal arg "") nil)
12048 ((eq arg 'none) nil)
12049 ((eq arg 'done) (or done-word (car org-done-keywords)))
12050 ((eq arg 'nextset)
12051 (or (car (cdr (member head org-todo-heads)))
12052 (car org-todo-heads)))
12053 ((eq arg 'previousset)
12054 (let ((org-todo-heads (reverse org-todo-heads)))
12055 (or (car (cdr (member head org-todo-heads)))
12056 (car org-todo-heads))))
12057 ((car (member arg org-todo-keywords-1)))
12058 ((stringp arg)
12059 (user-error "State `%s' not valid in this file" arg))
12060 ((nth (1- (prefix-numeric-value arg))
12061 org-todo-keywords-1))))
12062 ((null member) (or head (car org-todo-keywords-1)))
12063 ((equal this final-done-word) nil) ;-> make empty
12064 ((null tail) nil) ;-> first entry
12065 ((memq interpret '(type priority))
12066 (if (eq this-command last-command)
12067 (car tail)
12068 (if (> (length tail) 0)
12069 (or done-word (car org-done-keywords))
12070 nil)))
12072 (car tail))))
12073 (org-state (or
12074 (run-hook-with-args-until-success
12075 'org-todo-get-default-hook org-state org-last-state)
12076 org-state))
12077 (next (if org-state (concat " " org-state " ") " "))
12078 (change-plist (list :type 'todo-state-change :from this :to org-state
12079 :position startpos))
12080 dolog now-done-p)
12081 (when org-blocker-hook
12082 (let (org-blocked-by-checkboxes block-reason)
12083 (setq org-last-todo-state-is-todo
12084 (not (member this org-done-keywords)))
12085 (unless (save-excursion
12086 (save-match-data
12087 (org-with-wide-buffer
12088 (run-hook-with-args-until-failure
12089 'org-blocker-hook change-plist))))
12090 (setq block-reason (if org-blocked-by-checkboxes
12091 "contained checkboxes"
12092 (format "\"%s\"" org-block-entry-blocking)))
12093 (if (called-interactively-p 'interactive)
12094 (user-error "TODO state change from %s to %s blocked (by %s)"
12095 this org-state block-reason)
12096 ;; Fail silently.
12097 (message "TODO state change from %s to %s blocked (by %s)"
12098 this org-state block-reason)
12099 (throw 'exit nil)))))
12100 (store-match-data match-data)
12101 (replace-match next t t)
12102 (cond ((equal this org-state)
12103 (message "TODO state was already %s" (org-trim next)))
12104 ((not (pos-visible-in-window-p hl-pos))
12105 (message "TODO state changed to %s" (org-trim next))))
12106 (unless head
12107 (setq head (org-get-todo-sequence-head org-state)
12108 ass (assoc head org-todo-kwd-alist)
12109 interpret (nth 1 ass)
12110 done-word (nth 3 ass)
12111 final-done-word (nth 4 ass)))
12112 (when (memq arg '(nextset previousset))
12113 (message "Keyword-Set %d/%d: %s"
12114 (- (length org-todo-sets) -1
12115 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12116 (length org-todo-sets)
12117 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12118 (setq org-last-todo-state-is-todo
12119 (not (member org-state org-done-keywords)))
12120 (setq now-done-p (and (member org-state org-done-keywords)
12121 (not (member this org-done-keywords))))
12122 (and logging (org-local-logging logging))
12123 (when (and (or org-todo-log-states org-log-done)
12124 (not (eq org-inhibit-logging t))
12125 (not (memq arg '(nextset previousset))))
12126 ;; We need to look at recording a time and note.
12127 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12128 (nth 2 (assoc this org-todo-log-states))))
12129 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12130 (setq dolog 'time))
12131 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12132 (and org-state
12133 (member org-state org-not-done-keywords)
12134 (not (member this org-not-done-keywords))))
12135 ;; This is now a todo state and was not one before
12136 ;; If there was a CLOSED time stamp, get rid of it.
12137 (org-add-planning-info nil nil 'closed))
12138 (when (and now-done-p org-log-done)
12139 ;; It is now done, and it was not done before.
12140 (org-add-planning-info 'closed (org-current-effective-time))
12141 (when (and (not dolog) (eq 'note org-log-done))
12142 (org-add-log-setup 'done org-state this 'note)))
12143 (when (and org-state dolog)
12144 ;; This is a non-nil state, and we need to log it.
12145 (org-add-log-setup 'state org-state this dolog)))
12146 ;; Fixup tag positioning.
12147 (org-todo-trigger-tag-changes org-state)
12148 (when org-auto-align-tags (org-align-tags))
12149 (when org-provide-todo-statistics
12150 (org-update-parent-todo-statistics))
12151 (run-hooks 'org-after-todo-state-change-hook)
12152 (when (and arg (not (member org-state org-done-keywords)))
12153 (setq head (org-get-todo-sequence-head org-state)))
12154 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12155 ;; Do we need to trigger a repeat?
12156 (when now-done-p
12157 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12158 ;; This is for the agenda, take a snapshot of the headline.
12159 (save-match-data
12160 (setq org-agenda-headline-snapshot-before-repeat
12161 (org-get-heading))))
12162 (org-auto-repeat-maybe org-state))
12163 ;; Fixup cursor location if close to the keyword.
12164 (when (and (outline-on-heading-p)
12165 (not (bolp))
12166 (save-excursion (beginning-of-line 1)
12167 (looking-at org-todo-line-regexp))
12168 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12169 (goto-char (or (match-end 2) (match-end 1)))
12170 (and (looking-at " ") (just-one-space)))
12171 (when org-trigger-hook
12172 (save-excursion
12173 (run-hook-with-args 'org-trigger-hook change-plist)))
12174 (when commentp (org-toggle-comment))))))))
12176 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12177 "Block turning an entry into a TODO, using the hierarchy.
12178 This checks whether the current task should be blocked from state
12179 changes. Such blocking occurs when:
12181 1. The task has children which are not all in a completed state.
12183 2. A task has a parent with the property :ORDERED:, and there
12184 are siblings prior to the current task with incomplete
12185 status.
12187 3. The parent of the task is blocked because it has siblings that should
12188 be done first, or is child of a block grandparent TODO entry."
12190 (if (not org-enforce-todo-dependencies)
12191 t ; if locally turned off don't block
12192 (catch 'dont-block
12193 ;; If this is not a todo state change, or if this entry is already DONE,
12194 ;; do not block
12195 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12196 (member (plist-get change-plist :from)
12197 (cons 'done org-done-keywords))
12198 (member (plist-get change-plist :to)
12199 (cons 'todo org-not-done-keywords))
12200 (not (plist-get change-plist :to)))
12201 (throw 'dont-block t))
12202 ;; If this task has children, and any are undone, it's blocked
12203 (save-excursion
12204 (org-back-to-heading t)
12205 (let ((this-level (funcall outline-level)))
12206 (outline-next-heading)
12207 (let ((child-level (funcall outline-level)))
12208 (while (and (not (eobp))
12209 (> child-level this-level))
12210 ;; this todo has children, check whether they are all
12211 ;; completed
12212 (when (and (not (org-entry-is-done-p))
12213 (org-entry-is-todo-p))
12214 (setq org-block-entry-blocking (org-get-heading))
12215 (throw 'dont-block nil))
12216 (outline-next-heading)
12217 (setq child-level (funcall outline-level))))))
12218 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12219 ;; any previous siblings are undone, it's blocked
12220 (save-excursion
12221 (org-back-to-heading t)
12222 (let* ((pos (point))
12223 (parent-pos (and (org-up-heading-safe) (point)))
12224 (case-fold-search nil))
12225 (unless parent-pos (throw 'dont-block t)) ; no parent
12226 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12227 (forward-line 1)
12228 (re-search-forward org-not-done-heading-regexp pos t))
12229 (setq org-block-entry-blocking (match-string 0))
12230 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12231 ;; Search further up the hierarchy, to see if an ancestor is blocked
12232 (while t
12233 (goto-char parent-pos)
12234 (unless (looking-at org-not-done-heading-regexp)
12235 (throw 'dont-block t)) ; do not block, parent is not a TODO
12236 (setq pos (point))
12237 (setq parent-pos (and (org-up-heading-safe) (point)))
12238 (unless parent-pos (throw 'dont-block t)) ; no parent
12239 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12240 (forward-line 1)
12241 (re-search-forward org-not-done-heading-regexp pos t)
12242 (setq org-block-entry-blocking (org-get-heading)))
12243 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12245 (defcustom org-track-ordered-property-with-tag nil
12246 "Should the ORDERED property also be shown as a tag?
12247 The ORDERED property decides if an entry should require subtasks to be
12248 completed in sequence. Since a property is not very visible, setting
12249 this option means that toggling the ORDERED property with the command
12250 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12251 not relevant for the behavior, but it makes things more visible.
12253 Note that toggling the tag with tags commands will not change the property
12254 and therefore not influence behavior!
12256 This can be t, meaning the tag ORDERED should be used, It can also be a
12257 string to select a different tag for this task."
12258 :group 'org-todo
12259 :type '(choice
12260 (const :tag "No tracking" nil)
12261 (const :tag "Track with ORDERED tag" t)
12262 (string :tag "Use other tag")))
12264 (defun org-toggle-ordered-property ()
12265 "Toggle the ORDERED property of the current entry.
12266 For better visibility, you can track the value of this property with a tag.
12267 See variable `org-track-ordered-property-with-tag'."
12268 (interactive)
12269 (let* ((t1 org-track-ordered-property-with-tag)
12270 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12271 (save-excursion
12272 (org-back-to-heading)
12273 (if (org-entry-get nil "ORDERED")
12274 (progn
12275 (org-delete-property "ORDERED")
12276 (and tag (org-toggle-tag tag 'off))
12277 (message "Subtasks can be completed in arbitrary order"))
12278 (org-entry-put nil "ORDERED" "t")
12279 (and tag (org-toggle-tag tag 'on))
12280 (message "Subtasks must be completed in sequence")))))
12282 (defun org-block-todo-from-checkboxes (change-plist)
12283 "Block turning an entry into a TODO, using checkboxes.
12284 This checks whether the current task should be blocked from state
12285 changes because there are unchecked boxes in this entry."
12286 (if (not org-enforce-todo-checkbox-dependencies)
12287 t ; if locally turned off don't block
12288 (catch 'dont-block
12289 ;; If this is not a todo state change, or if this entry is already DONE,
12290 ;; do not block
12291 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12292 (member (plist-get change-plist :from)
12293 (cons 'done org-done-keywords))
12294 (member (plist-get change-plist :to)
12295 (cons 'todo org-not-done-keywords))
12296 (not (plist-get change-plist :to)))
12297 (throw 'dont-block t))
12298 ;; If this task has checkboxes that are not checked, it's blocked
12299 (save-excursion
12300 (org-back-to-heading t)
12301 (let ((beg (point)) end)
12302 (outline-next-heading)
12303 (setq end (point))
12304 (goto-char beg)
12305 (when (org-list-search-forward
12306 (concat (org-item-beginning-re)
12307 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12308 "\\[[- ]\\]")
12309 end t)
12310 (when (boundp 'org-blocked-by-checkboxes)
12311 (setq org-blocked-by-checkboxes t))
12312 (throw 'dont-block nil))))
12313 t))) ; do not block
12315 (defun org-entry-blocked-p ()
12316 "Non-nil if entry at point is blocked."
12317 (and (not (org-entry-get nil "NOBLOCKING"))
12318 (member (org-entry-get nil "TODO") org-not-done-keywords)
12319 (not (run-hook-with-args-until-failure
12320 'org-blocker-hook
12321 (list :type 'todo-state-change
12322 :position (point)
12323 :from 'todo
12324 :to 'done)))))
12326 (defun org-update-statistics-cookies (all)
12327 "Update the statistics cookie, either from TODO or from checkboxes.
12328 This should be called with the cursor in a line with a statistics
12329 cookie. When called with a \\[universal-argument] prefix, update
12330 all statistics cookies in the buffer."
12331 (interactive "P")
12332 (if all
12333 (progn
12334 (org-update-checkbox-count 'all)
12335 (org-map-entries 'org-update-parent-todo-statistics))
12336 (if (not (org-at-heading-p))
12337 (org-update-checkbox-count)
12338 (let ((pos (point-marker))
12339 end l1 l2)
12340 (ignore-errors (org-back-to-heading t))
12341 (if (not (org-at-heading-p))
12342 (org-update-checkbox-count)
12343 (setq l1 (org-outline-level))
12344 (setq end (save-excursion
12345 (outline-next-heading)
12346 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12347 (point)))
12348 (if (and (save-excursion
12349 (re-search-forward
12350 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12351 (not (save-excursion (re-search-forward
12352 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12353 (org-update-checkbox-count)
12354 (if (and l2 (> l2 l1))
12355 (progn
12356 (goto-char end)
12357 (org-update-parent-todo-statistics))
12358 (goto-char pos)
12359 (beginning-of-line 1)
12360 (while (re-search-forward
12361 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12362 (point-at-eol) t)
12363 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12364 (goto-char pos)
12365 (move-marker pos nil)))))
12367 (defvar org-entry-property-inherited-from) ;; defined below
12368 (defun org-update-parent-todo-statistics ()
12369 "Update any statistics cookie in the parent of the current headline.
12370 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12371 the entire subtree and this will travel up the hierarchy and update
12372 statistics everywhere."
12373 (let* ((prop (save-excursion (org-up-heading-safe)
12374 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12375 (recursive (or (not org-hierarchical-todo-statistics)
12376 (and prop (string-match "\\<recursive\\>" prop))))
12377 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12379 (first t)
12380 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12381 level ltoggle l1 new ndel
12382 (cnt-all 0) (cnt-done 0) is-percent kwd
12383 checkbox-beg cookie-present)
12384 (catch 'exit
12385 (save-excursion
12386 (beginning-of-line 1)
12387 (setq ltoggle (funcall outline-level))
12388 ;; Three situations are to consider:
12390 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12391 ;; to the top-level ancestor on the headline;
12393 ;; 2. If parent has "recursive" property, repeat up to the
12394 ;; headline setting that property, taking inheritance into
12395 ;; account;
12397 ;; 3. Else, move up to direct parent and proceed only once.
12398 (while (and (setq level (org-up-heading-safe))
12399 (or recursive first)
12400 (>= (point) lim))
12401 (setq first nil cookie-present nil)
12402 (unless (and level
12403 (not (string-match
12404 "\\<checkbox\\>"
12405 (downcase (or (org-entry-get nil "COOKIE_DATA")
12406 "")))))
12407 (throw 'exit nil))
12408 (while (re-search-forward box-re (point-at-eol) t)
12409 (setq cnt-all 0 cnt-done 0 cookie-present t)
12410 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12411 (save-match-data
12412 (unless (outline-next-heading) (throw 'exit nil))
12413 (while (and (looking-at org-complex-heading-regexp)
12414 (> (setq l1 (length (match-string 1))) level))
12415 (setq kwd (and (or recursive (= l1 ltoggle))
12416 (match-string 2)))
12417 (if (or (eq org-provide-todo-statistics 'all-headlines)
12418 (and (eq org-provide-todo-statistics t)
12419 (or (member kwd org-done-keywords)))
12420 (and (listp org-provide-todo-statistics)
12421 (stringp (car org-provide-todo-statistics))
12422 (or (member kwd org-provide-todo-statistics)
12423 (member kwd org-done-keywords)))
12424 (and (listp org-provide-todo-statistics)
12425 (listp (car org-provide-todo-statistics))
12426 (or (member kwd (car org-provide-todo-statistics))
12427 (and (member kwd org-done-keywords)
12428 (member kwd (cadr org-provide-todo-statistics))))))
12429 (setq cnt-all (1+ cnt-all))
12430 (and (eq org-provide-todo-statistics t)
12432 (setq cnt-all (1+ cnt-all))))
12433 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12434 (member kwd org-done-keywords))
12435 (and (listp org-provide-todo-statistics)
12436 (listp (car org-provide-todo-statistics))
12437 (member kwd org-done-keywords)
12438 (member kwd (cadr org-provide-todo-statistics)))
12439 (and (listp org-provide-todo-statistics)
12440 (stringp (car org-provide-todo-statistics))
12441 (member kwd org-done-keywords)))
12442 (setq cnt-done (1+ cnt-done)))
12443 (outline-next-heading)))
12444 (setq new
12445 (if is-percent
12446 (format "[%d%%]" (floor (* 100.0 cnt-done)
12447 (max 1 cnt-all)))
12448 (format "[%d/%d]" cnt-done cnt-all))
12449 ndel (- (match-end 0) checkbox-beg))
12450 (goto-char checkbox-beg)
12451 (insert new)
12452 (delete-region (point) (+ (point) ndel))
12453 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12454 (when cookie-present
12455 (run-hook-with-args 'org-after-todo-statistics-hook
12456 cnt-done (- cnt-all cnt-done))))))
12457 (run-hooks 'org-todo-statistics-hook)))
12459 (defvar org-after-todo-statistics-hook nil
12460 "Hook that is called after a TODO statistics cookie has been updated.
12461 Each function is called with two arguments: the number of not-done entries
12462 and the number of done entries.
12464 For example, the following function, when added to this hook, will switch
12465 an entry to DONE when all children are done, and back to TODO when new
12466 entries are set to a TODO status. Note that this hook is only called
12467 when there is a statistics cookie in the headline!
12469 (defun org-summary-todo (n-done n-not-done)
12470 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12471 (let (org-log-done org-log-states) ; turn off logging
12472 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12475 (defvar org-todo-statistics-hook nil
12476 "Hook that is run whenever Org thinks TODO statistics should be updated.
12477 This hook runs even if there is no statistics cookie present, in which case
12478 `org-after-todo-statistics-hook' would not run.")
12480 (defun org-todo-trigger-tag-changes (state)
12481 "Apply the changes defined in `org-todo-state-tags-triggers'."
12482 (let ((l org-todo-state-tags-triggers)
12483 changes)
12484 (when (or (not state) (equal state ""))
12485 (setq changes (append changes (cdr (assoc "" l)))))
12486 (when (and (stringp state) (> (length state) 0))
12487 (setq changes (append changes (cdr (assoc state l)))))
12488 (when (member state org-not-done-keywords)
12489 (setq changes (append changes (cdr (assq 'todo l)))))
12490 (when (member state org-done-keywords)
12491 (setq changes (append changes (cdr (assq 'done l)))))
12492 (dolist (c changes)
12493 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12495 (defun org-local-logging (value)
12496 "Get logging settings from a property VALUE."
12497 ;; Directly set the variables, they are already local.
12498 (setq org-log-done nil
12499 org-log-repeat nil
12500 org-todo-log-states nil)
12501 (dolist (w (split-string value))
12502 (let (a)
12503 (cond
12504 ((setq a (assoc w org-startup-options))
12505 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12506 (set (nth 1 a) (nth 2 a))))
12507 ((setq a (org-extract-log-state-settings w))
12508 (and (member (car a) org-todo-keywords-1)
12509 (push a org-todo-log-states)))))))
12511 (defun org-get-todo-sequence-head (kwd)
12512 "Return the head of the TODO sequence to which KWD belongs.
12513 If KWD is not set, check if there is a text property remembering the
12514 right sequence."
12515 (let (p)
12516 (cond
12517 ((not kwd)
12518 (or (get-text-property (point-at-bol) 'org-todo-head)
12519 (progn
12520 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12521 nil (point-at-eol)))
12522 (get-text-property p 'org-todo-head))))
12523 ((not (member kwd org-todo-keywords-1))
12524 (car org-todo-keywords-1))
12525 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12527 (defun org-fast-todo-selection ()
12528 "Fast TODO keyword selection with single keys.
12529 Returns the new TODO keyword, or nil if no state change should occur."
12530 (let* ((fulltable org-todo-key-alist)
12531 (done-keywords org-done-keywords) ;; needed for the faces.
12532 (maxlen (apply 'max (mapcar
12533 (lambda (x)
12534 (if (stringp (car x)) (string-width (car x)) 0))
12535 fulltable)))
12536 (expert nil)
12537 (fwidth (+ maxlen 3 1 3))
12538 (ncol (/ (- (window-width) 4) fwidth))
12539 tg cnt e c tbl
12540 groups ingroup)
12541 (save-excursion
12542 (save-window-excursion
12543 (if expert
12544 (set-buffer (get-buffer-create " *Org todo*"))
12545 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12546 (erase-buffer)
12547 (setq-local org-done-keywords done-keywords)
12548 (setq tbl fulltable cnt 0)
12549 (while (setq e (pop tbl))
12550 (cond
12551 ((equal e '(:startgroup))
12552 (push '() groups) (setq ingroup t)
12553 (unless (= cnt 0)
12554 (setq cnt 0)
12555 (insert "\n"))
12556 (insert "{ "))
12557 ((equal e '(:endgroup))
12558 (setq ingroup nil cnt 0)
12559 (insert "}\n"))
12560 ((equal e '(:newline))
12561 (unless (= cnt 0)
12562 (setq cnt 0)
12563 (insert "\n")
12564 (setq e (car tbl))
12565 (while (equal (car tbl) '(:newline))
12566 (insert "\n")
12567 (setq tbl (cdr tbl)))))
12569 (setq tg (car e) c (cdr e))
12570 (when ingroup (push tg (car groups)))
12571 (setq tg (org-add-props tg nil 'face
12572 (org-get-todo-face tg)))
12573 (when (and (= cnt 0) (not ingroup)) (insert " "))
12574 (insert "[" c "] " tg (make-string
12575 (- fwidth 4 (length tg)) ?\ ))
12576 (when (= (setq cnt (1+ cnt)) ncol)
12577 (insert "\n")
12578 (when ingroup (insert " "))
12579 (setq cnt 0)))))
12580 (insert "\n")
12581 (goto-char (point-min))
12582 (unless expert (org-fit-window-to-buffer))
12583 (message "[a-z..]:Set [SPC]:clear")
12584 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12585 (cond
12586 ((or (= c ?\C-g)
12587 (and (= c ?q) (not (rassoc c fulltable))))
12588 (setq quit-flag t))
12589 ((= c ?\ ) nil)
12590 ((setq e (rassoc c fulltable) tg (car e))
12592 (t (setq quit-flag t)))))))
12594 (defun org-entry-is-todo-p ()
12595 (member (org-get-todo-state) org-not-done-keywords))
12597 (defun org-entry-is-done-p ()
12598 (member (org-get-todo-state) org-done-keywords))
12600 (defun org-get-todo-state ()
12601 "Return the TODO keyword of the current subtree."
12602 (save-excursion
12603 (org-back-to-heading t)
12604 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12605 (match-end 2)
12606 (match-string 2))))
12608 (defun org-at-date-range-p (&optional inactive-ok)
12609 "Non-nil if point is inside a date range.
12611 When optional argument INACTIVE-OK is non-nil, also consider
12612 inactive time ranges.
12614 When this function returns a non-nil value, match data is set
12615 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12616 on INACTIVE-OK."
12617 (interactive)
12618 (save-excursion
12619 (catch 'exit
12620 (let ((pos (point)))
12621 (skip-chars-backward "^[<\r\n")
12622 (skip-chars-backward "<[")
12623 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12624 (>= (match-end 0) pos)
12625 (throw 'exit t))
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 nil)))
12633 (defun org-get-repeat (&optional timestamp)
12634 "Check if there is a time-stamp with repeater in this entry.
12636 Return the repeater, as a string, or nil. Also return nil when
12637 this function is called before first heading.
12639 When optional argument TIMESTAMP is a string, extract the
12640 repeater from there instead."
12641 (save-match-data
12642 (cond (timestamp
12643 (and (string-match org-repeat-re timestamp)
12644 (match-string-no-properties 1 timestamp)))
12645 ((org-before-first-heading-p) nil)
12647 (save-excursion
12648 (org-back-to-heading t)
12649 (let ((end (org-entry-end-position)))
12650 (catch :repeat
12651 (while (re-search-forward org-repeat-re end t)
12652 (when (save-match-data (org-at-timestamp-p 'agenda))
12653 (throw :repeat (match-string-no-properties 1)))))))))))
12655 (defvar org-last-changed-timestamp)
12656 (defvar org-last-inserted-timestamp)
12657 (defvar org-log-post-message)
12658 (defvar org-log-note-purpose)
12659 (defvar org-log-note-how nil)
12660 (defvar org-log-note-extra)
12661 (defun org-auto-repeat-maybe (done-word)
12662 "Check if the current headline contains a repeated time-stamp.
12664 If yes, set TODO state back to what it was and change the base date
12665 of repeating deadline/scheduled time stamps to new date.
12667 This function is run automatically after each state change to a DONE state."
12668 (let* ((repeat (org-get-repeat))
12669 (aa (assoc org-last-state org-todo-kwd-alist))
12670 (interpret (nth 1 aa))
12671 (head (nth 2 aa))
12672 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12673 (msg "Entry repeats: ")
12674 (org-log-done nil)
12675 (org-todo-log-states nil)
12676 (end (copy-marker (org-entry-end-position))))
12677 (unwind-protect
12678 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12679 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12680 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12681 (and (stringp org-todo-repeat-to-state)
12682 org-todo-repeat-to-state)
12683 (and org-todo-repeat-to-state org-last-state))))
12684 (org-todo (cond
12685 ((and to-state (member to-state org-todo-keywords-1))
12686 to-state)
12687 ((eq interpret 'type) org-last-state)
12688 (head)
12689 (t 'none))))
12690 (org-back-to-heading t)
12691 (org-add-planning-info nil nil 'closed)
12692 ;; When `org-log-repeat' is non-nil or entry contains
12693 ;; a clock, set LAST_REPEAT property.
12694 (when (or org-log-repeat
12695 (catch :clock
12696 (save-excursion
12697 (while (re-search-forward org-clock-line-re end t)
12698 (when (org-at-clock-log-p) (throw :clock t))))))
12699 (org-entry-put nil "LAST_REPEAT" (format-time-string
12700 (org-time-stamp-format t t)
12701 (current-time))))
12702 (when org-log-repeat
12703 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12704 (memq 'org-add-log-note post-command-hook))
12705 ;; We are already setup for some record.
12706 (when (eq org-log-repeat 'note)
12707 ;; Make sure we take a note, not only a time stamp.
12708 (setq org-log-note-how 'note))
12709 ;; Set up for taking a record.
12710 (org-add-log-setup 'state
12711 (or done-word (car org-done-keywords))
12712 org-last-state
12713 org-log-repeat)))
12714 (let ((planning-re (regexp-opt
12715 (list org-scheduled-string org-deadline-string))))
12716 (while (re-search-forward org-ts-regexp end t)
12717 (let* ((ts (match-string 0))
12718 (planning? (org-at-planning-p))
12719 (type (if (not planning?) "Plain:"
12720 (save-excursion
12721 (re-search-backward
12722 planning-re (line-beginning-position) t)
12723 (match-string 0)))))
12724 (cond
12725 ;; Ignore fake time-stamps (e.g., within comments).
12726 ((not (org-at-timestamp-p 'agenda)))
12727 ;; Time-stamps without a repeater are usually
12728 ;; skipped. However, a SCHEDULED time-stamp without
12729 ;; one is removed, as they are no longer relevant.
12730 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12731 ts))
12732 (when (equal type org-scheduled-string)
12733 (org-remove-timestamp-with-keyword type)))
12735 (let ((n (string-to-number (match-string 2 ts)))
12736 (what (match-string 3 ts)))
12737 (when (equal what "w") (setq n (* n 7) what "d"))
12738 (when (and (equal what "h")
12739 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12740 ts)))
12741 (user-error
12742 "Cannot repeat in Repeat in %d hour(s) because no hour \
12743 has been set"
12745 ;; Preparation, see if we need to modify the start
12746 ;; date for the change.
12747 (when (match-end 1)
12748 (let ((time (save-match-data
12749 (org-time-string-to-time ts))))
12750 (cond
12751 ((equal (match-string 1 ts) ".")
12752 ;; Shift starting date to today
12753 (org-timestamp-change
12754 (- (org-today) (time-to-days time))
12755 'day))
12756 ((equal (match-string 1 ts) "+")
12757 (let ((nshiftmax 10)
12758 (nshift 0))
12759 (while (or (= nshift 0)
12760 (not (time-less-p (current-time) time)))
12761 (when (= (cl-incf nshift) nshiftmax)
12762 (or (y-or-n-p
12763 (format "%d repeater intervals were not \
12764 enough to shift date past today. Continue? "
12765 nshift))
12766 (user-error "Abort")))
12767 (org-timestamp-change n (cdr (assoc what whata)))
12768 (org-in-regexp org-ts-regexp3)
12769 (setq ts (match-string 1))
12770 (setq time
12771 (save-match-data
12772 (org-time-string-to-time ts)))))
12773 (org-timestamp-change (- n) (cdr (assoc what whata)))
12774 ;; Rematch, so that we have everything in place
12775 ;; for the real shift.
12776 (org-in-regexp org-ts-regexp3)
12777 (setq ts (match-string 1))
12778 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12779 ts)))))
12780 (save-excursion
12781 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12782 (setq msg
12783 (concat
12784 msg type " " org-last-changed-timestamp " "))))))))
12785 (setq org-log-post-message msg)
12786 (message "%s" msg))
12787 (set-marker end nil))))
12789 (defun org-show-todo-tree (arg)
12790 "Make a compact tree which shows all headlines marked with TODO.
12791 The tree will show the lines where the regexp matches, and all higher
12792 headlines above the match.
12793 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12794 With a numeric prefix N, construct a sparse tree for the Nth element
12795 of `org-todo-keywords-1'."
12796 (interactive "P")
12797 (let ((case-fold-search nil)
12798 (kwd-re
12799 (cond ((null arg) org-not-done-regexp)
12800 ((equal arg '(4))
12801 (let ((kwd
12802 (completing-read "Keyword (or KWD1|KWD2|...): "
12803 (mapcar #'list org-todo-keywords-1))))
12804 (concat "\\("
12805 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12806 "\\)\\>")))
12807 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12808 (regexp-quote (nth (1- (prefix-numeric-value arg))
12809 org-todo-keywords-1)))
12810 (t (user-error "Invalid prefix argument: %s" arg)))))
12811 (message "%d TODO entries found"
12812 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12814 (defun org--deadline-or-schedule (arg type time)
12815 "Insert DEADLINE or SCHEDULE information in current entry.
12816 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12817 `org-schedule' for information about ARG and TIME arguments."
12818 (let* ((deadline? (eq type 'deadline))
12819 (keyword (if deadline? org-deadline-string org-scheduled-string))
12820 (log (if deadline? org-log-redeadline org-log-reschedule))
12821 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12822 (old-date-time (and old-date (org-time-string-to-time old-date)))
12823 ;; Save repeater cookie from either TIME or current scheduled
12824 ;; time stamp. We are going to insert it back at the end of
12825 ;; the process.
12826 (repeater (or (and (org-string-nw-p time)
12827 ;; We use `org-repeat-re' because we need
12828 ;; to tell the difference between a real
12829 ;; repeater and a time delta, e.g. "+2d".
12830 (string-match org-repeat-re time)
12831 (match-string 1 time))
12832 (and (org-string-nw-p old-date)
12833 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12834 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12835 old-date)
12836 (match-string 1 old-date)))))
12837 (pcase arg
12838 (`(4)
12839 (if (not old-date)
12840 (message (if deadline? "Entry had no deadline to remove"
12841 "Entry was not scheduled"))
12842 (when (and old-date log)
12843 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12844 nil old-date log))
12845 (org-remove-timestamp-with-keyword keyword)
12846 (message (if deadline? "Entry no longer has a deadline."
12847 "Entry is no longer scheduled."))))
12848 (`(16)
12849 (save-excursion
12850 (org-back-to-heading t)
12851 (let ((regexp (if deadline? org-deadline-time-regexp
12852 org-scheduled-time-regexp)))
12853 (if (not (re-search-forward regexp (line-end-position 2) t))
12854 (user-error (if deadline? "No deadline information to update"
12855 "No scheduled information to update"))
12856 (let* ((rpl0 (match-string 1))
12857 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12858 (msg (if deadline? "Warn starting from" "Delay until")))
12859 (replace-match
12860 (concat keyword
12861 " <" rpl
12862 (format " -%dd"
12863 (abs (- (time-to-days
12864 (save-match-data
12865 (org-read-date
12866 nil t nil msg old-date-time)))
12867 (time-to-days old-date-time))))
12868 ">") t t))))))
12870 (org-add-planning-info type time 'closed)
12871 (when (and old-date
12873 (not (equal old-date org-last-inserted-timestamp)))
12874 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12875 org-last-inserted-timestamp
12876 old-date
12877 log))
12878 (when repeater
12879 (save-excursion
12880 (org-back-to-heading t)
12881 (when (re-search-forward
12882 (concat keyword " " org-last-inserted-timestamp)
12883 (line-end-position 2)
12885 (goto-char (1- (match-end 0)))
12886 (insert " " repeater)
12887 (setq org-last-inserted-timestamp
12888 (concat (substring org-last-inserted-timestamp 0 -1)
12889 " " repeater
12890 (substring org-last-inserted-timestamp -1))))))
12891 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12892 org-last-inserted-timestamp)))))
12894 (defun org-deadline (arg &optional time)
12895 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12896 With one universal prefix argument, remove any deadline from the item.
12897 With two universal prefix arguments, prompt for a warning delay.
12898 With argument TIME, set the deadline at the corresponding date. TIME
12899 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12900 (interactive "P")
12901 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12902 (org-map-entries
12903 (lambda () (org--deadline-or-schedule arg 'deadline time))
12905 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12906 'region-start-level
12907 'region)
12908 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12909 (org--deadline-or-schedule arg 'deadline time)))
12911 (defun org-schedule (arg &optional time)
12912 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12913 With one universal prefix argument, remove any scheduling date from the item.
12914 With two universal prefix arguments, prompt for a delay cookie.
12915 With argument TIME, scheduled at the corresponding date. TIME can
12916 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12917 (interactive "P")
12918 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12919 (org-map-entries
12920 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12922 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12923 'region-start-level
12924 'region)
12925 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12926 (org--deadline-or-schedule arg 'scheduled time)))
12928 (defun org-get-scheduled-time (pom &optional inherit)
12929 "Get the scheduled time as a time tuple, of a format suitable
12930 for calling org-schedule with, or if there is no scheduling,
12931 returns nil."
12932 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12933 (when time
12934 (apply 'encode-time (org-parse-time-string time)))))
12936 (defun org-get-deadline-time (pom &optional inherit)
12937 "Get the deadline as a time tuple, of a format suitable for
12938 calling org-deadline with, or if there is no scheduling, returns
12939 nil."
12940 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12941 (when time
12942 (apply 'encode-time (org-parse-time-string time)))))
12944 (defun org-remove-timestamp-with-keyword (keyword)
12945 "Remove all time stamps with KEYWORD in the current entry."
12946 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12947 beg)
12948 (save-excursion
12949 (org-back-to-heading t)
12950 (setq beg (point))
12951 (outline-next-heading)
12952 (while (re-search-backward re beg t)
12953 (replace-match "")
12954 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12955 (equal (char-before) ?\ ))
12956 (backward-delete-char 1)
12957 (when (string-match "^[ \t]*$" (buffer-substring
12958 (point-at-bol) (point-at-eol)))
12959 (delete-region (point-at-bol)
12960 (min (point-max) (1+ (point-at-eol))))))))))
12962 (defvar org-time-was-given) ; dynamically scoped parameter
12963 (defvar org-end-time-was-given) ; dynamically scoped parameter
12965 (defun org-at-planning-p ()
12966 "Non-nil when point is on a planning info line."
12967 ;; This is as accurate and faster than `org-element-at-point' since
12968 ;; planning info location is fixed in the section.
12969 (org-with-wide-buffer
12970 (beginning-of-line)
12971 (and (looking-at-p org-planning-line-re)
12972 (eq (point)
12973 (ignore-errors
12974 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12975 (org-back-to-heading t)
12976 (org-with-limited-levels (org-back-to-heading t)))
12977 (line-beginning-position 2))))))
12979 (defun org-add-planning-info (what &optional time &rest remove)
12980 "Insert new timestamp with keyword in the planning line.
12981 WHAT indicates what kind of time stamp to add. It is a symbol
12982 among `closed', `deadline', `scheduled' and nil. TIME indicates
12983 the time to use. If none is given, the user is prompted for
12984 a date. REMOVE indicates what kind of entries to remove. An old
12985 WHAT entry will also be removed."
12986 (let (org-time-was-given org-end-time-was-given default-time default-input)
12987 (catch 'exit
12988 (when (and (memq what '(scheduled deadline))
12989 (or (not time)
12990 (and (stringp time)
12991 (string-match "^[-+]+[0-9]" time))))
12992 ;; Try to get a default date/time from existing timestamp
12993 (save-excursion
12994 (org-back-to-heading t)
12995 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12996 (when (re-search-forward (if (eq what 'scheduled)
12997 org-scheduled-time-regexp
12998 org-deadline-time-regexp)
12999 end t)
13000 (setq ts (match-string 1)
13001 default-time (apply 'encode-time (org-parse-time-string ts))
13002 default-input (and ts (org-get-compact-tod ts)))))))
13003 (when what
13004 (setq time
13005 (if (stringp time)
13006 ;; This is a string (relative or absolute), set
13007 ;; proper date.
13008 (apply #'encode-time
13009 (org-read-date-analyze
13010 time default-time (decode-time default-time)))
13011 ;; If necessary, get the time from the user
13012 (or time (org-read-date nil 'to-time nil nil
13013 default-time default-input)))))
13015 (org-with-wide-buffer
13016 (org-back-to-heading t)
13017 (forward-line)
13018 (unless (bolp) (insert "\n"))
13019 (cond ((looking-at-p org-planning-line-re)
13020 ;; Move to current indentation.
13021 (skip-chars-forward " \t")
13022 ;; Check if we have to remove something.
13023 (dolist (type (if what (cons what remove) remove))
13024 (save-excursion
13025 (when (re-search-forward
13026 (cl-case type
13027 (closed org-closed-time-regexp)
13028 (deadline org-deadline-time-regexp)
13029 (scheduled org-scheduled-time-regexp)
13030 (otherwise
13031 (error "Invalid planning type: %s" type)))
13032 (line-end-position) t)
13033 ;; Delete until next keyword or end of line.
13034 (delete-region
13035 (match-beginning 0)
13036 (if (re-search-forward org-keyword-time-not-clock-regexp
13037 (line-end-position)
13039 (match-beginning 0)
13040 (line-end-position))))))
13041 ;; If there is nothing more to add and no more keyword
13042 ;; is left, remove the line completely.
13043 (if (and (looking-at-p "[ \t]*$") (not what))
13044 (delete-region (line-beginning-position)
13045 (line-beginning-position 2))
13046 ;; If we removed last keyword, do not leave trailing
13047 ;; white space at the end of line.
13048 (let ((p (point)))
13049 (save-excursion
13050 (end-of-line)
13051 (unless (= (skip-chars-backward " \t" p) 0)
13052 (delete-region (point) (line-end-position)))))))
13053 ((not what) (throw 'exit nil)) ; Nothing to do.
13054 (t (insert-before-markers "\n")
13055 (backward-char 1)
13056 (when org-adapt-indentation
13057 (indent-to-column (1+ (org-outline-level))))))
13058 (when what
13059 ;; Insert planning keyword.
13060 (insert (cl-case what
13061 (closed org-closed-string)
13062 (deadline org-deadline-string)
13063 (scheduled org-scheduled-string)
13064 (otherwise (error "Invalid planning type: %s" what)))
13065 " ")
13066 ;; Insert associated timestamp.
13067 (let ((ts (org-insert-time-stamp
13068 time
13069 (or org-time-was-given
13070 (and (eq what 'closed) org-log-done-with-time))
13071 (eq what 'closed)
13072 nil nil (list org-end-time-was-given))))
13073 (unless (eolp) (insert " "))
13074 ts))))))
13076 (defvar org-log-note-marker (make-marker)
13077 "Marker pointing at the entry where the note is to be inserted.")
13078 (defvar org-log-note-purpose nil)
13079 (defvar org-log-note-state nil)
13080 (defvar org-log-note-previous-state nil)
13081 (defvar org-log-note-extra nil)
13082 (defvar org-log-note-window-configuration nil)
13083 (defvar org-log-note-return-to (make-marker))
13084 (defvar org-log-note-effective-time nil
13085 "Remembered current time so that dynamically scoped
13086 `org-extend-today-until' affects timestamps in state change log")
13088 (defvar org-log-post-message nil
13089 "Message to be displayed after a log note has been stored.
13090 The auto-repeater uses this.")
13092 (defun org-add-note ()
13093 "Add a note to the current entry.
13094 This is done in the same way as adding a state change note."
13095 (interactive)
13096 (org-add-log-setup 'note))
13098 (defun org-log-beginning (&optional create)
13099 "Return expected start of log notes in current entry.
13100 When optional argument CREATE is non-nil, the function creates
13101 a drawer to store notes, if necessary. Returned position ignores
13102 narrowing."
13103 (org-with-wide-buffer
13104 (let ((drawer (org-log-into-drawer)))
13105 (cond
13106 (drawer
13107 (org-end-of-meta-data)
13108 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13109 (end (if (org-at-heading-p) (point)
13110 (save-excursion (outline-next-heading) (point))))
13111 (case-fold-search t))
13112 (catch 'exit
13113 ;; Try to find existing drawer.
13114 (while (re-search-forward regexp end t)
13115 (let ((element (org-element-at-point)))
13116 (when (eq (org-element-type element) 'drawer)
13117 (let ((cend (org-element-property :contents-end element)))
13118 (when (and (not org-log-states-order-reversed) cend)
13119 (goto-char cend)))
13120 (throw 'exit nil))))
13121 ;; No drawer found. Create one, if permitted.
13122 (when create
13123 (unless (bolp) (insert "\n"))
13124 (let ((beg (point)))
13125 (insert ":" drawer ":\n:END:\n")
13126 (org-indent-region beg (point))
13127 (org-flag-region
13128 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13129 (end-of-line -1)))))
13131 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13132 (skip-chars-forward " \t\n")
13133 (beginning-of-line)
13134 (unless org-log-states-order-reversed
13135 (org-skip-over-state-notes)
13136 (skip-chars-backward " \t\n")
13137 (forward-line)))))
13138 (if (bolp) (point) (line-beginning-position 2))))
13140 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13141 "Set up the post command hook to take a note.
13142 If this is about to TODO state change, the new state is expected in STATE.
13143 HOW is an indicator what kind of note should be created.
13144 EXTRA is additional text that will be inserted into the notes buffer."
13145 (move-marker org-log-note-marker (point))
13146 (setq org-log-note-purpose purpose
13147 org-log-note-state state
13148 org-log-note-previous-state prev-state
13149 org-log-note-how how
13150 org-log-note-extra extra
13151 org-log-note-effective-time (org-current-effective-time))
13152 (add-hook 'post-command-hook 'org-add-log-note 'append))
13154 (defun org-skip-over-state-notes ()
13155 "Skip past the list of State notes in an entry."
13156 (when (ignore-errors (goto-char (org-in-item-p)))
13157 (let* ((struct (org-list-struct))
13158 (prevs (org-list-prevs-alist struct))
13159 (regexp
13160 (concat "[ \t]*- +"
13161 (replace-regexp-in-string
13162 " +" " +"
13163 (org-replace-escapes
13164 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13165 `(("%d" . ,org-ts-regexp-inactive)
13166 ("%D" . ,org-ts-regexp)
13167 ("%s" . "\"\\S-+\"")
13168 ("%S" . "\"\\S-+\"")
13169 ("%t" . ,org-ts-regexp-inactive)
13170 ("%T" . ,org-ts-regexp)
13171 ("%u" . ".*?")
13172 ("%U" . ".*?")))))))
13173 (while (looking-at-p regexp)
13174 (goto-char (or (org-list-get-next-item (point) struct prevs)
13175 (org-list-get-item-end (point) struct)))))))
13177 (defun org-add-log-note (&optional _purpose)
13178 "Pop up a window for taking a note, and add this note later."
13179 (remove-hook 'post-command-hook 'org-add-log-note)
13180 (setq org-log-note-window-configuration (current-window-configuration))
13181 (delete-other-windows)
13182 (move-marker org-log-note-return-to (point))
13183 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13184 (goto-char org-log-note-marker)
13185 (org-switch-to-buffer-other-window "*Org Note*")
13186 (erase-buffer)
13187 (if (memq org-log-note-how '(time state))
13188 (org-store-log-note)
13189 (let ((org-inhibit-startup t)) (org-mode))
13190 (insert (format "# Insert note for %s.
13191 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13192 (cond
13193 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13194 ((eq org-log-note-purpose 'done) "closed todo item")
13195 ((eq org-log-note-purpose 'state)
13196 (format "state change from \"%s\" to \"%s\""
13197 (or org-log-note-previous-state "")
13198 (or org-log-note-state "")))
13199 ((eq org-log-note-purpose 'reschedule)
13200 "rescheduling")
13201 ((eq org-log-note-purpose 'delschedule)
13202 "no longer scheduled")
13203 ((eq org-log-note-purpose 'redeadline)
13204 "changing deadline")
13205 ((eq org-log-note-purpose 'deldeadline)
13206 "removing deadline")
13207 ((eq org-log-note-purpose 'refile)
13208 "refiling")
13209 ((eq org-log-note-purpose 'note)
13210 "this entry")
13211 (t (error "This should not happen")))))
13212 (when org-log-note-extra (insert org-log-note-extra))
13213 (setq-local org-finish-function 'org-store-log-note)
13214 (run-hooks 'org-log-buffer-setup-hook)))
13216 (defvar org-note-abort nil) ; dynamically scoped
13217 (defun org-store-log-note ()
13218 "Finish taking a log note, and insert it to where it belongs."
13219 (let ((txt (prog1 (buffer-string)
13220 (kill-buffer)))
13221 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13222 lines)
13223 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13224 (setq txt (replace-match "" t t txt)))
13225 (when (string-match "\\s-+\\'" txt)
13226 (setq txt (replace-match "" t t txt)))
13227 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13228 (when (org-string-nw-p note)
13229 (setq note
13230 (org-replace-escapes
13231 note
13232 (list (cons "%u" (user-login-name))
13233 (cons "%U" user-full-name)
13234 (cons "%t" (format-time-string
13235 (org-time-stamp-format 'long 'inactive)
13236 org-log-note-effective-time))
13237 (cons "%T" (format-time-string
13238 (org-time-stamp-format 'long nil)
13239 org-log-note-effective-time))
13240 (cons "%d" (format-time-string
13241 (org-time-stamp-format nil 'inactive)
13242 org-log-note-effective-time))
13243 (cons "%D" (format-time-string
13244 (org-time-stamp-format nil nil)
13245 org-log-note-effective-time))
13246 (cons "%s" (cond
13247 ((not org-log-note-state) "")
13248 ((string-match-p org-ts-regexp
13249 org-log-note-state)
13250 (format "\"[%s]\""
13251 (substring org-log-note-state 1 -1)))
13252 (t (format "\"%s\"" org-log-note-state))))
13253 (cons "%S"
13254 (cond
13255 ((not org-log-note-previous-state) "")
13256 ((string-match-p org-ts-regexp
13257 org-log-note-previous-state)
13258 (format "\"[%s]\""
13259 (substring
13260 org-log-note-previous-state 1 -1)))
13261 (t (format "\"%s\""
13262 org-log-note-previous-state)))))))
13263 (when lines (setq note (concat note " \\\\")))
13264 (push note lines))
13265 (when (and lines (not org-note-abort))
13266 (with-current-buffer (marker-buffer org-log-note-marker)
13267 (org-with-wide-buffer
13268 ;; Find location for the new note.
13269 (goto-char org-log-note-marker)
13270 (set-marker org-log-note-marker nil)
13271 ;; Note associated to a clock is to be located right after
13272 ;; the clock. Do not move point.
13273 (unless (eq org-log-note-purpose 'clock-out)
13274 (goto-char (org-log-beginning t)))
13275 ;; Make sure point is at the beginning of an empty line.
13276 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13277 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13278 ;; In an existing list, add a new item at the top level.
13279 ;; Otherwise, indent line like a regular one.
13280 (let ((itemp (org-in-item-p)))
13281 (if itemp
13282 (indent-line-to
13283 (let ((struct (save-excursion
13284 (goto-char itemp) (org-list-struct))))
13285 (org-list-get-ind (org-list-get-top-point struct) struct)))
13286 (org-indent-line)))
13287 (insert (org-list-bullet-string "-") (pop lines))
13288 (let ((ind (org-list-item-body-column (line-beginning-position))))
13289 (dolist (line lines)
13290 (insert "\n")
13291 (indent-line-to ind)
13292 (insert line)))
13293 (message "Note stored")
13294 (org-back-to-heading t))
13295 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13296 ;; from within `org-add-log-note' because `buffer-undo-list'
13297 ;; is then modified outside of `org-with-remote-undo'.
13298 (when (eq this-command 'org-agenda-todo)
13299 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13300 ;; Don't add undo information when called from `org-agenda-todo'.
13301 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13302 (set-window-configuration org-log-note-window-configuration)
13303 (with-current-buffer (marker-buffer org-log-note-return-to)
13304 (goto-char org-log-note-return-to))
13305 (move-marker org-log-note-return-to nil)
13306 (when org-log-post-message (message "%s" org-log-post-message))))
13308 (defun org-remove-empty-drawer-at (pos)
13309 "Remove an empty drawer at position POS.
13310 POS may also be a marker."
13311 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13312 (org-with-wide-buffer
13313 (goto-char pos)
13314 (let ((drawer (org-element-at-point)))
13315 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13316 (not (org-element-property :contents-begin drawer)))
13317 (delete-region (org-element-property :begin drawer)
13318 (progn (goto-char (org-element-property :end drawer))
13319 (skip-chars-backward " \r\t\n")
13320 (forward-line)
13321 (point))))))))
13323 (defvar org-ts-type nil)
13324 (defun org-sparse-tree (&optional arg type)
13325 "Create a sparse tree, prompt for the details.
13326 This command can create sparse trees. You first need to select the type
13327 of match used to create the tree:
13329 t Show all TODO entries.
13330 T Show entries with a specific TODO keyword.
13331 m Show entries selected by a tags/property match.
13332 p Enter a property name and its value (both with completion on existing
13333 names/values) and show entries with that property.
13334 r Show entries matching a regular expression (`/' can be used as well).
13335 b Show deadlines and scheduled items before a date.
13336 a Show deadlines and scheduled items after a date.
13337 d Show deadlines due within `org-deadline-warning-days'.
13338 D Show deadlines and scheduled items between a date range."
13339 (interactive "P")
13340 (setq type (or type org-sparse-tree-default-date-type))
13341 (setq org-ts-type type)
13342 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13343 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13344 \[c]ycle through date types: %s"
13345 (cl-case type
13346 (all "all timestamps")
13347 (scheduled "only scheduled")
13348 (deadline "only deadline")
13349 (active "only active timestamps")
13350 (inactive "only inactive timestamps")
13351 (closed "with a closed time-stamp")
13352 (otherwise "scheduled/deadline")))
13353 (let ((answer (read-char-exclusive)))
13354 (cl-case answer
13356 (org-sparse-tree
13358 (cadr
13359 (memq type '(nil all scheduled deadline active inactive closed)))))
13360 (?d (call-interactively 'org-check-deadlines))
13361 (?b (call-interactively 'org-check-before-date))
13362 (?a (call-interactively 'org-check-after-date))
13363 (?D (call-interactively 'org-check-dates-range))
13364 (?t (call-interactively 'org-show-todo-tree))
13365 (?T (org-show-todo-tree '(4)))
13366 (?m (call-interactively 'org-match-sparse-tree))
13367 ((?p ?P)
13368 (let* ((kwd (completing-read
13369 "Property: " (mapcar #'list (org-buffer-property-keys))))
13370 (value (completing-read
13371 "Value: " (mapcar #'list (org-property-values kwd)))))
13372 (unless (string-match "\\`{.*}\\'" value)
13373 (setq value (concat "\"" value "\"")))
13374 (org-match-sparse-tree arg (concat kwd "=" value))))
13375 ((?r ?R ?/) (call-interactively 'org-occur))
13376 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13378 (defvar-local org-occur-highlights nil
13379 "List of overlays used for occur matches.")
13380 (defvar-local org-occur-parameters nil
13381 "Parameters of the active org-occur calls.
13382 This is a list, each call to org-occur pushes as cons cell,
13383 containing the regular expression and the callback, onto the list.
13384 The list can contain several entries if `org-occur' has been called
13385 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13386 will only contain one set of parameters. When the highlights are
13387 removed (for example with `C-c C-c', or with the next edit (depending
13388 on `org-remove-highlights-with-change'), this variable is emptied
13389 as well.")
13391 (defun org-occur (regexp &optional keep-previous callback)
13392 "Make a compact tree which shows all matches of REGEXP.
13394 The tree will show the lines where the regexp matches, and any other context
13395 defined in `org-show-context-detail', which see.
13397 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13398 done by a previous call to `org-occur' will be kept, to allow stacking of
13399 calls to this command.
13401 Optional argument CALLBACK can be a function of no argument. In this case,
13402 it is called with point at the end of the match, match data being set
13403 accordingly. Current match is shown only if the return value is non-nil.
13404 The function must neither move point nor alter narrowing."
13405 (interactive "sRegexp: \nP")
13406 (when (equal regexp "")
13407 (user-error "Regexp cannot be empty"))
13408 (unless keep-previous
13409 (org-remove-occur-highlights nil nil t))
13410 (push (cons regexp callback) org-occur-parameters)
13411 (let ((cnt 0))
13412 (save-excursion
13413 (goto-char (point-min))
13414 (when (or (not keep-previous) ; do not want to keep
13415 (not org-occur-highlights)) ; no previous matches
13416 ;; hide everything
13417 (org-overview))
13418 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13419 (isearch-no-upper-case-p regexp t)
13420 org-occur-case-fold-search)))
13421 (while (re-search-forward regexp nil t)
13422 (when (or (not callback)
13423 (save-match-data (funcall callback)))
13424 (setq cnt (1+ cnt))
13425 (when org-highlight-sparse-tree-matches
13426 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13427 (org-show-context 'occur-tree)))))
13428 (when org-remove-highlights-with-change
13429 (add-hook 'before-change-functions 'org-remove-occur-highlights
13430 nil 'local))
13431 (unless org-sparse-tree-open-archived-trees
13432 (org-hide-archived-subtrees (point-min) (point-max)))
13433 (run-hooks 'org-occur-hook)
13434 (when (called-interactively-p 'interactive)
13435 (message "%d match(es) for regexp %s" cnt regexp))
13436 cnt))
13438 (defun org-occur-next-match (&optional n _reset)
13439 "Function for `next-error-function' to find sparse tree matches.
13440 N is the number of matches to move, when negative move backwards.
13441 This function always goes back to the starting point when no
13442 match is found."
13443 (let* ((limit (if (< n 0) (point-min) (point-max)))
13444 (search-func (if (< n 0)
13445 'previous-single-char-property-change
13446 'next-single-char-property-change))
13447 (n (abs n))
13448 (pos (point))
13450 (catch 'exit
13451 (while (setq p1 (funcall search-func (point) 'org-type))
13452 (when (equal p1 limit)
13453 (goto-char pos)
13454 (user-error "No more matches"))
13455 (when (equal (get-char-property p1 'org-type) 'org-occur)
13456 (setq n (1- n))
13457 (when (= n 0)
13458 (goto-char p1)
13459 (throw 'exit (point))))
13460 (goto-char p1))
13461 (goto-char p1)
13462 (user-error "No more matches"))))
13464 (defun org-highlight-new-match (beg end)
13465 "Highlight from BEG to END and mark the highlight is an occur headline."
13466 (let ((ov (make-overlay beg end)))
13467 (overlay-put ov 'face 'secondary-selection)
13468 (overlay-put ov 'org-type 'org-occur)
13469 (push ov org-occur-highlights)))
13471 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13472 "Remove the occur highlights from the buffer.
13473 BEG and END are ignored. If NOREMOVE is nil, remove this function
13474 from the `before-change-functions' in the current buffer."
13475 (interactive)
13476 (unless org-inhibit-highlight-removal
13477 (mapc #'delete-overlay org-occur-highlights)
13478 (setq org-occur-highlights nil)
13479 (setq org-occur-parameters nil)
13480 (unless noremove
13481 (remove-hook 'before-change-functions
13482 'org-remove-occur-highlights 'local))))
13484 ;;;; Priorities
13486 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13487 "Regular expression matching the priority indicator.")
13489 (defvar org-remove-priority-next-time nil)
13491 (defun org-priority-up ()
13492 "Increase the priority of the current item."
13493 (interactive)
13494 (org-priority 'up))
13496 (defun org-priority-down ()
13497 "Decrease the priority of the current item."
13498 (interactive)
13499 (org-priority 'down))
13501 (defun org-priority (&optional action _show)
13502 "Change the priority of an item.
13503 ACTION can be `set', `up', `down', or a character."
13504 (interactive "P")
13505 (if (equal action '(4))
13506 (org-show-priority)
13507 (unless org-enable-priority-commands
13508 (user-error "Priority commands are disabled"))
13509 (setq action (or action 'set))
13510 (let (current new news have remove)
13511 (save-excursion
13512 (org-back-to-heading t)
13513 (when (looking-at org-priority-regexp)
13514 (setq current (string-to-char (match-string 2))
13515 have t))
13516 (cond
13517 ((eq action 'remove)
13518 (setq remove t new ?\ ))
13519 ((or (eq action 'set)
13520 (integerp action))
13521 (if (not (eq action 'set))
13522 (setq new action)
13523 (message "Priority %c-%c, SPC to remove: "
13524 org-highest-priority org-lowest-priority)
13525 (save-match-data
13526 (setq new (read-char-exclusive))))
13527 (when (and (= (upcase org-highest-priority) org-highest-priority)
13528 (= (upcase org-lowest-priority) org-lowest-priority))
13529 (setq new (upcase new)))
13530 (cond ((equal new ?\ ) (setq remove t))
13531 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13532 (user-error "Priority must be between `%c' and `%c'"
13533 org-highest-priority org-lowest-priority))))
13534 ((eq action 'up)
13535 (setq new (if have
13536 (1- current) ; normal cycling
13537 ;; last priority was empty
13538 (if (eq last-command this-command)
13539 org-lowest-priority ; wrap around empty to lowest
13540 ;; default
13541 (if org-priority-start-cycle-with-default
13542 org-default-priority
13543 (1- org-default-priority))))))
13544 ((eq action 'down)
13545 (setq new (if have
13546 (1+ current) ; normal cycling
13547 ;; last priority was empty
13548 (if (eq last-command this-command)
13549 org-highest-priority ; wrap around empty to highest
13550 ;; default
13551 (if org-priority-start-cycle-with-default
13552 org-default-priority
13553 (1+ org-default-priority))))))
13554 (t (user-error "Invalid action")))
13555 (when (or (< (upcase new) org-highest-priority)
13556 (> (upcase new) org-lowest-priority))
13557 (if (and (memq action '(up down))
13558 (not have) (not (eq last-command this-command)))
13559 ;; `new' is from default priority
13560 (error
13561 "The default can not be set, see `org-default-priority' why")
13562 ;; normal cycling: `new' is beyond highest/lowest priority
13563 ;; and is wrapped around to the empty priority
13564 (setq remove t)))
13565 (setq news (format "%c" new))
13566 (if have
13567 (if remove
13568 (replace-match "" t t nil 1)
13569 (replace-match news t t nil 2))
13570 (if remove
13571 (user-error "No priority cookie found in line")
13572 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13573 (if (match-end 2)
13574 (progn
13575 (goto-char (match-end 2))
13576 (insert " [#" news "]"))
13577 (goto-char (match-beginning 3))
13578 (insert "[#" news "] "))))
13579 (org-align-tags))
13580 (if remove
13581 (message "Priority removed")
13582 (message "Priority of current item set to %s" news)))))
13584 (defun org-show-priority ()
13585 "Show the priority of the current item.
13586 This priority is composed of the main priority given with the [#A] cookies,
13587 and by additional input from the age of a schedules or deadline entry."
13588 (interactive)
13589 (let ((pri (if (eq major-mode 'org-agenda-mode)
13590 (org-get-at-bol 'priority)
13591 (save-excursion
13592 (save-match-data
13593 (beginning-of-line)
13594 (and (looking-at org-heading-regexp)
13595 (org-get-priority (match-string 0))))))))
13596 (message "Priority is %d" (if pri pri -1000))))
13598 (defun org-get-priority (s)
13599 "Find priority cookie and return priority."
13600 (save-match-data
13601 (if (functionp org-get-priority-function)
13602 (funcall org-get-priority-function)
13603 (if (not (string-match org-priority-regexp s))
13604 (* 1000 (- org-lowest-priority org-default-priority))
13605 (* 1000 (- org-lowest-priority
13606 (string-to-char (match-string 2 s))))))))
13608 ;;;; Tags
13610 (defvar org-agenda-archives-mode)
13611 (defvar org-map-continue-from nil
13612 "Position from where mapping should continue.
13613 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13615 (defvar org-scanner-tags nil
13616 "The current tag list while the tags scanner is running.")
13618 (defvar org-trust-scanner-tags nil
13619 "Should `org-get-tags' use the tags for the scanner.
13620 This is for internal dynamical scoping only.
13621 When this is non-nil, the function `org-get-tags' will return the value
13622 of `org-scanner-tags' instead of building the list by itself. This
13623 can lead to large speed-ups when the tags scanner is used in a file with
13624 many entries, and when the list of tags is retrieved, for example to
13625 obtain a list of properties. Building the tags list for each entry in such
13626 a file becomes an N^2 operation - but with this variable set, it scales
13627 as N.")
13629 (defvar org--matcher-tags-todo-only nil)
13631 (defun org-scan-tags (action matcher todo-only &optional start-level)
13632 "Scan headline tags with inheritance and produce output ACTION.
13634 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13635 or `agenda' to produce an entry list for an agenda view. It can also be
13636 a Lisp form or a function that should be called at each matched headline, in
13637 this case the return value is a list of all return values from these calls.
13639 MATCHER is a function accepting three arguments, returning
13640 a non-nil value whenever a given set of tags qualifies a headline
13641 for inclusion. See `org-make-tags-matcher' for more information.
13642 As a special case, it can also be set to t (respectively nil) in
13643 order to match all (respectively none) headline.
13645 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13646 included in the output.
13648 START-LEVEL can be a string with asterisks, reducing the scope to
13649 headlines matching this string."
13650 (require 'org-agenda)
13651 (let* ((re (concat "^"
13652 (if start-level
13653 ;; Get the correct level to match
13654 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13655 org-outline-regexp)
13656 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13657 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13658 (props (list 'face 'default
13659 'done-face 'org-agenda-done
13660 'undone-face 'default
13661 'mouse-face 'highlight
13662 'org-not-done-regexp org-not-done-regexp
13663 'org-todo-regexp org-todo-regexp
13664 'org-complex-heading-regexp org-complex-heading-regexp
13665 'help-echo
13666 (format "mouse-2 or RET jump to Org file %S"
13667 (abbreviate-file-name
13668 (or (buffer-file-name (buffer-base-buffer))
13669 (buffer-name (buffer-base-buffer)))))))
13670 (org-map-continue-from nil)
13671 lspos tags tags-list
13672 (tags-alist (list (cons 0 org-file-tags)))
13673 (llast 0) rtn rtn1 level category i txt
13674 todo marker entry priority
13675 ts-date ts-date-type ts-date-pair)
13676 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13677 (setq action (list 'lambda nil action)))
13678 (save-excursion
13679 (goto-char (point-min))
13680 (when (eq action 'sparse-tree)
13681 (org-overview)
13682 (org-remove-occur-highlights))
13683 (while (let (case-fold-search)
13684 (re-search-forward re nil t))
13685 (setq org-map-continue-from nil)
13686 (catch :skip
13687 ;; Ignore closing parts of inline tasks.
13688 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13689 (throw :skip t))
13690 (setq todo
13691 ;; TODO: is the 1-2 difference a bug?
13692 (when (match-end 1) (match-string-no-properties 2))
13693 tags (when (match-end 4) (match-string-no-properties 4)))
13694 (goto-char (setq lspos (match-beginning 0)))
13695 (setq level (org-reduced-level (org-outline-level))
13696 category (org-get-category))
13697 (when (eq action 'agenda)
13698 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13699 ts-date (car ts-date-pair)
13700 ts-date-type (cdr ts-date-pair)))
13701 (setq i llast llast level)
13702 ;; remove tag lists from same and sublevels
13703 (while (>= i level)
13704 (when (setq entry (assoc i tags-alist))
13705 (setq tags-alist (delete entry tags-alist)))
13706 (setq i (1- i)))
13707 ;; add the next tags
13708 (when tags
13709 (setq tags (org-split-string tags ":")
13710 tags-alist
13711 (cons (cons level tags) tags-alist)))
13712 ;; compile tags for current headline
13713 (setq tags-list
13714 (if org-use-tag-inheritance
13715 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13716 tags)
13717 org-scanner-tags tags-list)
13718 (when org-use-tag-inheritance
13719 (setcdr (car tags-alist)
13720 (mapcar (lambda (x)
13721 (setq x (copy-sequence x))
13722 (org-add-prop-inherited x))
13723 (cdar tags-alist))))
13724 (when (and tags org-use-tag-inheritance
13725 (or (not (eq t org-use-tag-inheritance))
13726 org-tags-exclude-from-inheritance))
13727 ;; Selective inheritance, remove uninherited ones.
13728 (setcdr (car tags-alist)
13729 (org-remove-uninherited-tags (cdar tags-alist))))
13730 (when (and
13732 ;; eval matcher only when the todo condition is OK
13733 (and (or (not todo-only) (member todo org-todo-keywords-1))
13734 (if (functionp matcher)
13735 (let ((case-fold-search t) (org-trust-scanner-tags t))
13736 (funcall matcher todo tags-list level))
13737 matcher))
13739 ;; Call the skipper, but return t if it does not
13740 ;; skip, so that the `and' form continues evaluating.
13741 (progn
13742 (unless (eq action 'sparse-tree) (org-agenda-skip))
13745 ;; Check if timestamps are deselecting this entry
13746 (or (not todo-only)
13747 (and (member todo org-todo-keywords-1)
13748 (or (not org-agenda-tags-todo-honor-ignore-options)
13749 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13751 ;; select this headline
13752 (cond
13753 ((eq action 'sparse-tree)
13754 (and org-highlight-sparse-tree-matches
13755 (org-get-heading) (match-end 0)
13756 (org-highlight-new-match
13757 (match-beginning 1) (match-end 1)))
13758 (org-show-context 'tags-tree))
13759 ((eq action 'agenda)
13760 (setq txt (org-agenda-format-item
13762 (concat
13763 (if (eq org-tags-match-list-sublevels 'indented)
13764 (make-string (1- level) ?.) "")
13765 (org-get-heading))
13766 (make-string level ?\s)
13767 category
13768 tags-list)
13769 priority (org-get-priority txt))
13770 (goto-char lspos)
13771 (setq marker (org-agenda-new-marker))
13772 (org-add-props txt props
13773 'org-marker marker 'org-hd-marker marker 'org-category category
13774 'todo-state todo
13775 'ts-date ts-date
13776 'priority priority
13777 'type (concat "tagsmatch" ts-date-type))
13778 (push txt rtn))
13779 ((functionp action)
13780 (setq org-map-continue-from nil)
13781 (save-excursion
13782 (setq rtn1 (funcall action))
13783 (push rtn1 rtn)))
13784 (t (user-error "Invalid action")))
13786 ;; if we are to skip sublevels, jump to end of subtree
13787 (unless org-tags-match-list-sublevels
13788 (org-end-of-subtree t)
13789 (backward-char 1))))
13790 ;; Get the correct position from where to continue
13791 (if org-map-continue-from
13792 (goto-char org-map-continue-from)
13793 (and (= (point) lspos) (end-of-line 1)))))
13794 (when (and (eq action 'sparse-tree)
13795 (not org-sparse-tree-open-archived-trees))
13796 (org-hide-archived-subtrees (point-min) (point-max)))
13797 (nreverse rtn)))
13799 (defun org-remove-uninherited-tags (tags)
13800 "Remove all tags that are not inherited from the list TAGS."
13801 (cond
13802 ((eq org-use-tag-inheritance t)
13803 (if org-tags-exclude-from-inheritance
13804 (org-delete-all org-tags-exclude-from-inheritance tags)
13805 tags))
13806 ((not org-use-tag-inheritance) nil)
13807 ((stringp org-use-tag-inheritance)
13808 (delq nil (mapcar
13809 (lambda (x)
13810 (if (and (string-match org-use-tag-inheritance x)
13811 (not (member x org-tags-exclude-from-inheritance)))
13812 x nil))
13813 tags)))
13814 ((listp org-use-tag-inheritance)
13815 (delq nil (mapcar
13816 (lambda (x)
13817 (if (member x org-use-tag-inheritance) x nil))
13818 tags)))))
13820 (defun org-match-sparse-tree (&optional todo-only match)
13821 "Create a sparse tree according to tags string MATCH.
13823 MATCH is a string with match syntax. It can contain a selection
13824 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13825 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13826 those. See the manual for details.
13828 If optional argument TODO-ONLY is non-nil, only select lines that
13829 are also TODO tasks."
13830 (interactive "P")
13831 (org-agenda-prepare-buffers (list (current-buffer)))
13832 (let ((org--matcher-tags-todo-only todo-only))
13833 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13834 org--matcher-tags-todo-only)))
13836 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13838 (defvar org-cached-props nil)
13839 (defun org-cached-entry-get (pom property)
13840 (if (or (eq t org-use-property-inheritance)
13841 (and (stringp org-use-property-inheritance)
13842 (let ((case-fold-search t))
13843 (string-match-p org-use-property-inheritance property)))
13844 (and (listp org-use-property-inheritance)
13845 (member-ignore-case property org-use-property-inheritance)))
13846 ;; Caching is not possible, check it directly.
13847 (org-entry-get pom property 'inherit)
13848 ;; Get all properties, so we can do complicated checks easily.
13849 (cdr (assoc-string property
13850 (or org-cached-props
13851 (setq org-cached-props (org-entry-properties pom)))
13852 t))))
13854 (defun org-global-tags-completion-table (&optional files)
13855 "Return the list of all tags in all agenda buffer/files.
13856 Optional FILES argument is a list of files which can be used
13857 instead of the agenda files."
13858 (save-excursion
13859 (org-uniquify
13860 (delq nil
13861 (apply #'append
13862 (mapcar
13863 (lambda (file)
13864 (set-buffer (find-file-noselect file))
13865 (org--tag-add-to-alist
13866 (org-get-buffer-tags)
13867 (mapcar (lambda (x)
13868 (and (stringp (car-safe x))
13869 (list (car-safe x))))
13870 org-current-tag-alist)))
13871 (if (car-safe files) files
13872 (org-agenda-files))))))))
13874 (defun org-make-tags-matcher (match)
13875 "Create the TAGS/TODO matcher form for the selection string MATCH.
13877 Returns a cons of the selection string MATCH and a function
13878 implementing the matcher.
13880 The matcher is to be called at an Org entry, with point on the
13881 headline, and returns non-nil if the entry matches the selection
13882 string MATCH. It must be called with three arguments: the TODO
13883 keyword at the entry (or nil if none), the list of all tags at
13884 the entry including inherited ones and the reduced level of the
13885 headline. Additionally, the category of the entry, if any, must
13886 be specified as the text property `org-category' on the headline.
13888 This function sets the variable `org--matcher-tags-todo-only' to
13889 a non-nil value if the matcher restricts matching to TODO
13890 entries, otherwise it is not touched.
13892 See also `org-scan-tags'."
13893 (unless match
13894 ;; Get a new match request, with completion against the global
13895 ;; tags table and the local tags in current buffer.
13896 (let ((org-last-tags-completion-table
13897 (org--tag-add-to-alist
13898 (org-get-buffer-tags)
13899 (org-global-tags-completion-table))))
13900 (setq match
13901 (completing-read
13902 "Match: "
13903 'org-tags-completion-function nil nil nil 'org-tags-history))))
13905 (let ((match0 match)
13906 (re (concat
13907 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13908 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13909 "\\([<>=]\\{1,2\\}\\)"
13910 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13911 "\\|" org-tag-re "\\)"))
13912 (start 0)
13913 tagsmatch todomatch tagsmatcher todomatcher)
13915 ;; Expand group tags.
13916 (setq match (org-tags-expand match))
13918 ;; Check if there is a TODO part of this match, which would be the
13919 ;; part after a "/". To make sure that this slash is not part of
13920 ;; a property value to be matched against, we also check that
13921 ;; there is no / after that slash. First, find the last slash.
13922 (let ((s 0))
13923 (while (string-match "/+" match s)
13924 (setq start (match-beginning 0))
13925 (setq s (match-end 0))))
13926 (if (and (string-match "/+" match start)
13927 (not (string-match-p "\"" match start)))
13928 ;; Match contains also a TODO-matching request.
13929 (progn
13930 (setq tagsmatch (substring match 0 (match-beginning 0)))
13931 (setq todomatch (substring match (match-end 0)))
13932 (when (string-prefix-p "!" todomatch)
13933 (setq org--matcher-tags-todo-only t)
13934 (setq todomatch (substring todomatch 1)))
13935 (when (string-match "\\`\\s-*\\'" todomatch)
13936 (setq todomatch nil)))
13937 ;; Only matching tags.
13938 (setq tagsmatch match)
13939 (setq todomatch nil))
13941 ;; Make the tags matcher.
13942 (when (org-string-nw-p tagsmatch)
13943 (let ((orlist nil)
13944 (orterms (org-split-string tagsmatch "|"))
13945 term)
13946 (while (setq term (pop orterms))
13947 (while (and (equal (substring term -1) "\\") orterms)
13948 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13949 (while (string-match re term)
13950 (let* ((rest (substring term (match-end 0)))
13951 (minus (and (match-end 1)
13952 (equal (match-string 1 term) "-")))
13953 (tag (save-match-data
13954 (replace-regexp-in-string
13955 "\\\\-" "-" (match-string 2 term))))
13956 (regexp (eq (string-to-char tag) ?{))
13957 (levelp (match-end 4))
13958 (propp (match-end 5))
13960 (cond
13961 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13962 (levelp
13963 `(,(org-op-to-function (match-string 3 term))
13964 level
13965 ,(string-to-number (match-string 4 term))))
13966 (propp
13967 (let* ((gv (pcase (upcase (match-string 5 term))
13968 ("CATEGORY"
13969 '(get-text-property (point) 'org-category))
13970 ("TODO" 'todo)
13971 (p `(org-cached-entry-get nil ,p))))
13972 (pv (match-string 7 term))
13973 (regexp (eq (string-to-char pv) ?{))
13974 (strp (eq (string-to-char pv) ?\"))
13975 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13976 (po (org-op-to-function (match-string 6 term)
13977 (if timep 'time strp))))
13978 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13979 (when timep (setq pv (org-matcher-time pv)))
13980 (cond ((and regexp (eq po '/=))
13981 `(not (string-match ,pv (or ,gv ""))))
13982 (regexp `(string-match ,pv (or ,gv "")))
13983 (strp `(,po (or ,gv "") ,pv))
13985 `(,po
13986 (string-to-number (or ,gv ""))
13987 ,(string-to-number pv))))))
13988 (t `(member ,tag tags-list)))))
13989 (push (if minus `(not ,mm) mm) tagsmatcher)
13990 (setq term rest)))
13991 (push `(and ,@tagsmatcher) orlist)
13992 (setq tagsmatcher nil))
13993 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13995 ;; Make the TODO matcher.
13996 (when (org-string-nw-p todomatch)
13997 (let ((orlist nil))
13998 (dolist (term (org-split-string todomatch "|"))
13999 (while (string-match re term)
14000 (let* ((minus (and (match-end 1)
14001 (equal (match-string 1 term) "-")))
14002 (kwd (match-string 2 term))
14003 (regexp (eq (string-to-char kwd) ?{))
14004 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14005 `(equal todo ,kwd))))
14006 (push (if minus `(not ,mm) mm) todomatcher))
14007 (setq term (substring term (match-end 0))))
14008 (push (if (> (length todomatcher) 1)
14009 (cons 'and todomatcher)
14010 (car todomatcher))
14011 orlist)
14012 (setq todomatcher nil))
14013 (setq todomatcher (cons 'or orlist))))
14015 ;; Return the string and function of the matcher. If no
14016 ;; tags-specific or todo-specific matcher exists, match
14017 ;; everything.
14018 (let ((matcher (if (and tagsmatcher todomatcher)
14019 `(and ,tagsmatcher ,todomatcher)
14020 (or tagsmatcher todomatcher t))))
14021 (when org--matcher-tags-todo-only
14022 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14023 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14025 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14026 "Expand group tags in MATCH.
14028 This replaces every group tag in MATCH with a regexp tag search.
14029 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14030 will be replaced like this:
14032 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14033 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14034 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14036 Replacing by a regexp preserves the structure of the match.
14037 E.g., this expansion
14039 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14041 will match anything tagged with \"Lab\" and \"Home\", or tagged
14042 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14044 A group tag in MATCH can contain regular expressions of its own.
14045 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14046 will be replaced like this:
14048 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14050 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14051 assumed to be a single group tag, and the function will return
14052 the list of tags in this group.
14054 When DOWNCASE is non-nil, expand downcased TAGS."
14055 (if org-group-tags
14056 (let* ((case-fold-search t)
14057 (stable org-mode-syntax-table)
14058 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14059 (taggroups (if downcased
14060 (mapcar (lambda (tg) (mapcar #'downcase tg))
14061 taggroups)
14062 taggroups))
14063 (taggroups-keys (mapcar #'car taggroups))
14064 (return-match (if downcased (downcase match) match))
14065 (count 0)
14066 (work-already-expanded tags-already-expanded)
14067 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14068 ;; @ and _ are allowed as word-components in tags.
14069 (modify-syntax-entry ?@ "w" stable)
14070 (modify-syntax-entry ?_ "w" stable)
14071 ;; Temporarily replace regexp-expressions in the match-expression.
14072 (while (string-match "{.+?}" return-match)
14073 (cl-incf count)
14074 (push (match-string 0 return-match) regexps-in-match)
14075 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14076 (while (and taggroups-keys
14077 (with-syntax-table stable
14078 (string-match
14079 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14080 (regexp-opt taggroups-keys) "\\>\\)")
14081 return-match)))
14082 (let* ((dir (match-string 1 return-match))
14083 (tag (match-string 2 return-match))
14084 (tag (if downcased (downcase tag) tag)))
14085 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14086 (member tag tags-already-expanded))
14087 (setq tags-in-group (assoc tag taggroups))
14088 (push tag work-already-expanded)
14089 ;; Recursively expand each tag in the group, if the tag hasn't
14090 ;; already been expanded. Restore the match-data after all recursive calls.
14091 (save-match-data
14092 (let (tags-expanded)
14093 (dolist (x (cdr tags-in-group))
14094 (if (and (member x taggroups-keys)
14095 (not (member x work-already-expanded)))
14096 (setq tags-expanded
14097 (delete-dups
14098 (append
14099 (org-tags-expand x t downcased
14100 work-already-expanded)
14101 tags-expanded)))
14102 (setq tags-expanded
14103 (append (list x) tags-expanded)))
14104 (setq work-already-expanded
14105 (delete-dups
14106 (append tags-expanded
14107 work-already-expanded))))
14108 (setq tags-in-group
14109 (delete-dups (cons (car tags-in-group)
14110 tags-expanded)))))
14111 ;; Filter tag-regexps from tags.
14112 (setq regexp-in-group-escaped
14113 (delq nil (mapcar (lambda (x)
14114 (if (stringp x)
14115 (and (equal "{" (substring x 0 1))
14116 (equal "}" (substring x -1))
14119 tags-in-group))
14120 regexp-in-group
14121 (mapcar (lambda (x)
14122 (substring x 1 -1))
14123 regexp-in-group-escaped)
14124 tags-in-group
14125 (delq nil (mapcar (lambda (x)
14126 (if (stringp x)
14127 (and (not (equal "{" (substring x 0 1)))
14128 (not (equal "}" (substring x -1)))
14131 tags-in-group)))
14132 ;; If single-as-list, do no more in the while-loop.
14133 (if (not single-as-list)
14134 (progn
14135 (when regexp-in-group
14136 (setq regexp-in-group
14137 (concat "\\|"
14138 (mapconcat 'identity regexp-in-group
14139 "\\|"))))
14140 (setq tags-in-group
14141 (concat dir
14142 "{\\<"
14143 (regexp-opt tags-in-group)
14144 "\\>"
14145 regexp-in-group
14146 "}"))
14147 (when (stringp tags-in-group)
14148 (org-add-props tags-in-group '(grouptag t)))
14149 (setq return-match
14150 (replace-match tags-in-group t t return-match)))
14151 (setq tags-in-group
14152 (append regexp-in-group-escaped tags-in-group))))
14153 (setq taggroups-keys (delete tag taggroups-keys))))
14154 ;; Add the regular expressions back into the match-expression again.
14155 (while regexps-in-match
14156 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14157 (pop regexps-in-match)
14158 return-match t t))
14159 (cl-decf count))
14160 (if single-as-list
14161 (if tags-in-group tags-in-group (list return-match))
14162 return-match))
14163 (if single-as-list
14164 (list (if downcased (downcase match) match))
14165 match)))
14167 (defun org-op-to-function (op &optional stringp)
14168 "Turn an operator into the appropriate function."
14169 (setq op
14170 (cond
14171 ((equal op "<" ) '(< org-string< org-time<))
14172 ((equal op ">" ) '(> org-string> org-time>))
14173 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14174 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14175 ((member op '("=" "==")) '(= string= org-time=))
14176 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14177 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14179 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14180 (defvar org-tags-overlay (make-overlay 1 1))
14181 (delete-overlay org-tags-overlay)
14183 (defun org-add-prop-inherited (s)
14184 (add-text-properties 0 (length s) '(inherited t) s)
14187 (defun org-toggle-tag (tag &optional onoff)
14188 "Toggle the tag TAG for the current line.
14189 If ONOFF is `on' or `off', don't toggle but set to this state."
14190 (save-excursion
14191 (org-back-to-heading t)
14192 (let ((current
14193 ;; Reverse the tags list so any new tag is appended to the
14194 ;; current list of tags.
14195 (nreverse (org-get-tags nil t)))
14196 res)
14197 (pcase onoff
14198 (`off (setq current (delete tag current)))
14199 ((or `on (guard (not (member tag current))))
14200 (setq res t)
14201 (cl-pushnew tag current :test #'equal))
14202 (_ (setq current (delete tag current))))
14203 (org-set-tags (nreverse current))
14204 res)))
14206 (defun org--align-tags-here (to-col)
14207 "Align tags on the current headline to TO-COL.
14208 Assume point is on a headline."
14209 (when (and (org-match-line org-tag-line-re)
14210 (< (point) (match-beginning 1)))
14211 (let ((pos (point))
14212 (shift (if (>= to-col 0) to-col
14213 (- (abs to-col) (string-width (match-string 1))))))
14214 ;; Delete all blanks before tags.
14215 (goto-char (match-beginning 1))
14216 (skip-chars-backward " \t")
14217 (delete-region (point) (match-beginning 1))
14218 ;; Insert new blanks.
14219 (insert (make-string (max 1 (- shift (current-column))) ?\s))
14220 ;; Preserve initial position, if possible. In any case, stop
14221 ;; before tags.
14222 (when (< pos (point)) (goto-char pos)))))
14224 (defun org-set-tags-command (&optional arg)
14225 "Set the tags for the current visible entry.
14227 When called with `\\[universal-argument]' prefix argument ARG, \
14228 realign all tags
14229 in the current buffer. If a region is active, set tags for
14230 all headlines in the region.
14232 This function is for interactive use only;
14233 in Lisp code use `org-set-tags' instead."
14234 (interactive "P")
14235 (cond
14236 (arg (org-align-tags t))
14237 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14238 ;; Disable `org-loop-over-headlines-in-active-region' for
14239 ;; successive calls.
14240 (let (org-loop-over-headlines-in-active-region)
14241 (org-map-entries
14242 #'org-set-tags-command
14244 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14245 'region-start-level
14246 'region)
14247 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14249 (org-back-to-heading)
14250 (let* ((all-tags (org-get-tags))
14251 (table (setq org-last-tags-completion-table
14252 (org--tag-add-to-alist
14253 (and org-complete-tags-always-offer-all-agenda-tags
14254 (org-global-tags-completion-table
14255 (org-agenda-files)))
14256 (or org-current-tag-alist (org-get-buffer-tags)))))
14257 (current-tags
14258 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14259 all-tags))
14260 (inherited-tags
14261 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14262 all-tags))
14263 (tags
14264 (replace-regexp-in-string
14265 ;; Ignore all forbidden characters in tags.
14266 "[^[:alnum:]_@#%]+" ":"
14267 (if (or (eq t org-use-fast-tag-selection)
14268 (and org-use-fast-tag-selection
14269 (delq nil (mapcar #'cdr table))))
14270 (org-fast-tag-selection
14271 current-tags
14272 inherited-tags
14273 table
14274 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14275 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14276 (org-trim (completing-read
14277 "Tags: "
14278 #'org-tags-completion-function
14279 nil nil (org-make-tag-string current-tags)
14280 'org-tags-history)))))))
14281 (org-set-tags tags)))))
14283 (defun org-align-tags (&optional all)
14284 "Align tags in current entry.
14285 When optional argument ALL is non-nil, align all tags in the
14286 visible part of the buffer."
14287 (save-excursion
14288 (if all (goto-char (point-min)) (org-back-to-heading t))
14289 (catch :single
14290 (while (re-search-forward org-tag-line-re nil t)
14291 (let* ((offset (if (bound-and-true-p org-indent-mode)
14292 (* (1- org-indent-indentation-per-level)
14293 (1- (org-current-level)))
14295 (tags-column (+ org-tags-column
14296 (if (> org-tags-column 0) (- offset) offset))))
14297 (beginning-of-line)
14298 (org--align-tags-here tags-column)
14299 (if all (forward-line) (throw :single nil)))))))
14301 (defun org-set-tags (tags)
14302 "Set the tags of the current entry to TAGS, replacing current tags.
14304 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14305 If TAGS is nil or the empty string, all tags are removed.
14307 This function assumes point is on a headline."
14308 (let ((tags (pcase tags
14309 ((pred listp) tags)
14310 ((pred stringp) (split-string (org-trim tags) ":" t))
14311 (_ (error "Invalid tag specification: %S" tags))))
14312 (change-flag nil))
14313 (when (functionp org-tags-sort-function)
14314 (setq tags (sort tags org-tags-sort-function)))
14315 (org-with-wide-buffer
14316 (unless (equal tags (org-get-tags nil t))
14317 (setq change-flag t)
14318 ;; Delete previous tags and any trailing white space.
14319 (goto-char (if (looking-at org-tag-line-re) (match-beginning 1)
14320 (line-end-position)))
14321 (skip-chars-backward " \t")
14322 (delete-region (point) (line-end-position))
14323 (when tags
14324 (save-excursion (insert " " (org-make-tag-string tags)))
14325 ;; When text is being inserted on an invisible region
14326 ;; boundary, it can be inadvertently sucked into
14327 ;; invisibility.
14328 (unless (org-invisible-p (line-beginning-position))
14329 (org-flag-region (point) (line-end-position) nil 'outline))))
14330 ;; Align tags, if any. Fix tags column if `org-indent-mode' is
14331 ;; on.
14332 (when tags (org-align-tags))
14333 (when change-flag (run-hooks 'org-after-tags-change-hook)))))
14335 (defun org-change-tag-in-region (beg end tag off)
14336 "Add or remove TAG for each entry in the region.
14337 This works in the agenda, and also in an Org buffer."
14338 (interactive
14339 (list (region-beginning) (region-end)
14340 (let ((org-last-tags-completion-table
14341 (if (derived-mode-p 'org-mode)
14342 (org--tag-add-to-alist
14343 (org-get-buffer-tags)
14344 (org-global-tags-completion-table))
14345 (org-global-tags-completion-table))))
14346 (completing-read
14347 "Tag: " 'org-tags-completion-function nil nil nil
14348 'org-tags-history))
14349 (progn
14350 (message "[s]et or [r]emove? ")
14351 (equal (read-char-exclusive) ?r))))
14352 (when (fboundp 'deactivate-mark) (deactivate-mark))
14353 (let ((agendap (equal major-mode 'org-agenda-mode))
14354 l1 l2 m buf pos newhead (cnt 0))
14355 (goto-char end)
14356 (setq l2 (1- (org-current-line)))
14357 (goto-char beg)
14358 (setq l1 (org-current-line))
14359 (cl-loop for l from l1 to l2 do
14360 (org-goto-line l)
14361 (setq m (get-text-property (point) 'org-hd-marker))
14362 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14363 (and agendap m))
14364 (setq buf (if agendap (marker-buffer m) (current-buffer))
14365 pos (if agendap m (point)))
14366 (with-current-buffer buf
14367 (save-excursion
14368 (save-restriction
14369 (goto-char pos)
14370 (setq cnt (1+ cnt))
14371 (org-toggle-tag tag (if off 'off 'on))
14372 (setq newhead (org-get-heading)))))
14373 (and agendap (org-agenda-change-all-lines newhead m))))
14374 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14376 (defun org-tags-completion-function (string _predicate &optional flag)
14377 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14378 (confirm (lambda (x) (stringp (car x)))))
14379 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14380 (setq s1 (match-string 1 string)
14381 s2 (match-string 2 string))
14382 (setq s1 "" s2 string))
14383 (cond
14384 ((eq flag nil)
14385 ;; try completion
14386 (setq rtn (try-completion s2 ctable confirm))
14387 (when (stringp rtn)
14388 (setq rtn
14389 (concat s1 s2 (substring rtn (length s2))
14390 (if (and org-add-colon-after-tag-completion
14391 (assoc rtn ctable))
14392 ":" ""))))
14393 rtn)
14394 ((eq flag t)
14395 ;; all-completions
14396 (all-completions s2 ctable confirm))
14397 ((eq flag 'lambda)
14398 ;; exact match?
14399 (assoc s2 ctable)))))
14401 (defun org-fast-tag-insert (kwd tags face &optional end)
14402 "Insert KDW, and the TAGS, the latter with face FACE.
14403 Also insert END."
14404 (insert (format "%-12s" (concat kwd ":"))
14405 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14406 (or end "")))
14408 (defun org-fast-tag-show-exit (flag)
14409 (save-excursion
14410 (org-goto-line 3)
14411 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14412 (replace-match ""))
14413 (when flag
14414 (end-of-line 1)
14415 (org-move-to-column (- (window-width) 19) t)
14416 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14418 (defun org-set-current-tags-overlay (current prefix)
14419 "Add an overlay to CURRENT tag with PREFIX."
14420 (let ((s (org-make-tag-string current)))
14421 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14422 (org-overlay-display org-tags-overlay (concat prefix s))))
14424 (defvar org-last-tag-selection-key nil)
14425 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14426 "Fast tag selection with single keys.
14427 CURRENT is the current list of tags in the headline, INHERITED is the
14428 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14429 possibly with grouping information. TODO-TABLE is a similar table with
14430 TODO keywords, should these have keys assigned to them.
14431 If the keys are nil, a-z are automatically assigned.
14432 Returns the new tags string, or nil to not change the current settings."
14433 (let* ((fulltable (append table todo-table))
14434 (maxlen (if (null fulltable) 0
14435 (apply #'max
14436 (mapcar (lambda (x)
14437 (if (stringp (car x)) (string-width (car x))
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-toggle-narrow-to-subtree)
19108 ("k" . org-cut-subtree)
19109 ("=" . org-columns)
19110 ("Outline Structure Editing")
19111 ("U" . org-metaup)
19112 ("D" . org-metadown)
19113 ("r" . org-metaright)
19114 ("l" . org-metaleft)
19115 ("R" . org-shiftmetaright)
19116 ("L" . org-shiftmetaleft)
19117 ("i" . (progn (forward-char 1) (call-interactively
19118 'org-insert-heading-respect-content)))
19119 ("^" . org-sort)
19120 ("w" . org-refile)
19121 ("a" . org-archive-subtree-default-with-confirmation)
19122 ("@" . org-mark-subtree)
19123 ("#" . org-toggle-comment)
19124 ("Clock Commands")
19125 ("I" . org-clock-in)
19126 ("O" . org-clock-out)
19127 ("Meta Data Editing")
19128 ("t" . org-todo)
19129 ("," . (org-priority))
19130 ("0" . (org-priority ?\ ))
19131 ("1" . (org-priority ?A))
19132 ("2" . (org-priority ?B))
19133 ("3" . (org-priority ?C))
19134 (":" . org-set-tags-command)
19135 ("e" . org-set-effort)
19136 ("E" . org-inc-effort)
19137 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19138 (org-entry-put (point) "APPT_WARNTIME" m)))
19139 ("Agenda Views etc")
19140 ("v" . org-agenda)
19141 ("/" . org-sparse-tree)
19142 ("Misc")
19143 ("o" . org-open-at-point)
19144 ("?" . org-speed-command-help)
19145 ("<" . (org-agenda-set-restriction-lock 'subtree))
19146 (">" . (org-agenda-remove-restriction-lock))
19148 "The default speed commands.")
19150 (defun org-print-speed-command (e)
19151 (if (> (length (car e)) 1)
19152 (progn
19153 (princ "\n")
19154 (princ (car e))
19155 (princ "\n")
19156 (princ (make-string (length (car e)) ?-))
19157 (princ "\n"))
19158 (princ (car e))
19159 (princ " ")
19160 (if (symbolp (cdr e))
19161 (princ (symbol-name (cdr e)))
19162 (prin1 (cdr e)))
19163 (princ "\n")))
19165 (defun org-speed-command-help ()
19166 "Show the available speed commands."
19167 (interactive)
19168 (if (not org-use-speed-commands)
19169 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19170 (with-output-to-temp-buffer "*Help*"
19171 (princ "User-defined Speed commands\n===========================\n")
19172 (mapc #'org-print-speed-command org-speed-commands-user)
19173 (princ "\n")
19174 (princ "Built-in Speed commands\n=======================\n")
19175 (mapc #'org-print-speed-command org-speed-commands-default))
19176 (with-current-buffer "*Help*"
19177 (setq truncate-lines t))))
19179 (defun org-speed-move-safe (cmd)
19180 "Execute CMD, but make sure that the cursor always ends up in a headline.
19181 If not, return to the original position and throw an error."
19182 (interactive)
19183 (let ((pos (point)))
19184 (call-interactively cmd)
19185 (unless (and (bolp) (org-at-heading-p))
19186 (goto-char pos)
19187 (error "Boundary reached while executing %s" cmd))))
19189 (defvar org-self-insert-command-undo-counter 0)
19191 (defvar org-table-auto-blank-field) ; defined in org-table.el
19192 (defvar org-speed-command nil)
19194 (defun org-speed-command-activate (keys)
19195 "Hook for activating single-letter speed commands.
19196 `org-speed-commands-default' specifies a minimal command set.
19197 Use `org-speed-commands-user' for further customization."
19198 (when (or (and (bolp) (looking-at org-outline-regexp))
19199 (and (functionp org-use-speed-commands)
19200 (funcall org-use-speed-commands)))
19201 (cdr (assoc keys (append org-speed-commands-user
19202 org-speed-commands-default)))))
19204 (defun org-babel-speed-command-activate (keys)
19205 "Hook for activating single-letter code block commands."
19206 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19207 (cdr (assoc keys org-babel-key-bindings))))
19209 (defcustom org-speed-command-hook
19210 '(org-speed-command-activate org-babel-speed-command-activate)
19211 "Hook for activating speed commands at strategic locations.
19212 Hook functions are called in sequence until a valid handler is
19213 found.
19215 Each hook takes a single argument, a user-pressed command key
19216 which is also a `self-insert-command' from the global map.
19218 Within the hook, examine the cursor position and the command key
19219 and return nil or a valid handler as appropriate. Handler could
19220 be one of an interactive command, a function, or a form.
19222 Set `org-use-speed-commands' to non-nil value to enable this
19223 hook. The default setting is `org-speed-command-activate'."
19224 :group 'org-structure
19225 :version "24.1"
19226 :type 'hook)
19228 (defun org-self-insert-command (N)
19229 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19230 If the cursor is in a table looking at whitespace, the whitespace is
19231 overwritten, and the table is not marked as requiring realignment."
19232 (interactive "p")
19233 (org-check-before-invisible-edit 'insert)
19234 (cond
19235 ((and org-use-speed-commands
19236 (let ((kv (this-command-keys-vector)))
19237 (setq org-speed-command
19238 (run-hook-with-args-until-success
19239 'org-speed-command-hook
19240 (make-string 1 (aref kv (1- (length kv))))))))
19241 (cond
19242 ((commandp org-speed-command)
19243 (setq this-command org-speed-command)
19244 (call-interactively org-speed-command))
19245 ((functionp org-speed-command)
19246 (funcall org-speed-command))
19247 ((and org-speed-command (listp org-speed-command))
19248 (eval org-speed-command))
19249 (t (let (org-use-speed-commands)
19250 (call-interactively 'org-self-insert-command)))))
19251 ((and
19252 (= N 1)
19253 (not (org-region-active-p))
19254 (org-at-table-p)
19255 (progn
19256 ;; Check if we blank the field, and if that triggers align.
19257 (and (featurep 'org-table)
19258 org-table-auto-blank-field
19259 (memq last-command
19260 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19261 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19262 ;; Got extra space, this field does not determine
19263 ;; column width.
19264 (let (org-table-may-need-update) (org-table-blank-field))
19265 ;; No extra space, this field may determine column
19266 ;; width.
19267 (org-table-blank-field)))
19269 (looking-at "[^|\n]* |"))
19270 ;; There is room for insertion without re-aligning the table.
19271 (self-insert-command N)
19272 (org-table-with-shrunk-field
19273 (save-excursion
19274 (skip-chars-forward "^|")
19275 ;; Do not delete last space, which is
19276 ;; `org-table-separator-space', but the regular space before
19277 ;; it.
19278 (delete-region (- (point) 2) (1- (point))))))
19280 (setq org-table-may-need-update t)
19281 (self-insert-command N)
19282 (org-fix-tags-on-the-fly)
19283 (when org-self-insert-cluster-for-undo
19284 (if (not (eq last-command 'org-self-insert-command))
19285 (setq org-self-insert-command-undo-counter 1)
19286 (if (>= org-self-insert-command-undo-counter 20)
19287 (setq org-self-insert-command-undo-counter 1)
19288 (and (> org-self-insert-command-undo-counter 0)
19289 buffer-undo-list (listp buffer-undo-list)
19290 (not (cadr buffer-undo-list)) ; remove nil entry
19291 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19292 (setq org-self-insert-command-undo-counter
19293 (1+ org-self-insert-command-undo-counter))))))))
19295 (defun org-check-before-invisible-edit (kind)
19296 "Check is editing if kind KIND would be dangerous with invisible text around.
19297 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19298 ;; First, try to get out of here as quickly as possible, to reduce overhead
19299 (when (and org-catch-invisible-edits
19300 (or (not (boundp 'visible-mode)) (not visible-mode))
19301 (or (get-char-property (point) 'invisible)
19302 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19303 ;; OK, we need to take a closer look. Do not consider
19304 ;; invisibility obtained through text properties (e.g., link
19305 ;; fontification), as it cannot be toggled.
19306 (let* ((invisible-at-point
19307 (pcase (get-char-property-and-overlay (point) 'invisible)
19308 (`(,_ . ,(and (pred overlayp) o)) o)))
19309 ;; Assume that point cannot land in the middle of an
19310 ;; overlay, or between two overlays.
19311 (invisible-before-point
19312 (and (not invisible-at-point)
19313 (not (bobp))
19314 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19315 (`(,_ . ,(and (pred overlayp) o)) o))))
19316 (border-and-ok-direction
19318 ;; Check if we are acting predictably before invisible
19319 ;; text.
19320 (and invisible-at-point
19321 (memq kind '(insert delete-backward)))
19322 ;; Check if we are acting predictably after invisible text
19323 ;; This works not well, and I have turned it off. It seems
19324 ;; better to always show and stop after invisible text.
19325 ;; (and (not invisible-at-point) invisible-before-point
19326 ;; (memq kind '(insert delete)))
19328 (when (or invisible-at-point invisible-before-point)
19329 (when (eq org-catch-invisible-edits 'error)
19330 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19331 (if (and org-custom-properties-overlays
19332 (y-or-n-p "Display invisible properties in this buffer? "))
19333 (org-toggle-custom-properties-visibility)
19334 ;; Make the area visible
19335 (save-excursion
19336 (when invisible-before-point
19337 (goto-char
19338 (previous-single-char-property-change (point) 'invisible)))
19339 ;; Remove whatever overlay is currently making yet-to-be
19340 ;; edited text invisible. Also remove nested invisibility
19341 ;; related overlays.
19342 (delete-overlay (or invisible-at-point invisible-before-point))
19343 (let ((origin (if invisible-at-point (point) (1- (point)))))
19344 (while (pcase (get-char-property-and-overlay origin 'invisible)
19345 (`(,_ . ,(and (pred overlayp) o))
19346 (delete-overlay o)
19347 t)))))
19348 (cond
19349 ((eq org-catch-invisible-edits 'show)
19350 ;; That's it, we do the edit after showing
19351 (message
19352 "Unfolding invisible region around point before editing")
19353 (sit-for 1))
19354 ((and (eq org-catch-invisible-edits 'smart)
19355 border-and-ok-direction)
19356 (message "Unfolding invisible region around point before editing"))
19358 ;; Don't do the edit, make the user repeat it in full visibility
19359 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19361 (defun org-fix-tags-on-the-fly ()
19362 "Align tags in headline at point.
19363 Unlike `org-align-tags', this function does nothing if point is
19364 either not currently on a tagged headline or on a tag."
19365 (when (and (org-match-line org-tag-line-re)
19366 (< (point) (match-beginning 1)))
19367 (org-align-tags)))
19369 (defun org-delete-backward-char (N)
19370 "Like `delete-backward-char', insert whitespace at field end in tables.
19371 When deleting backwards, in tables this function will insert whitespace in
19372 front of the next \"|\" separator, to keep the table aligned. The table will
19373 still be marked for re-alignment if the field did fill the entire column,
19374 because, in this case the deletion might narrow the column."
19375 (interactive "p")
19376 (save-match-data
19377 (org-check-before-invisible-edit 'delete-backward)
19378 (if (and (= N 1)
19379 (not overwrite-mode)
19380 (not (org-region-active-p))
19381 (not (eq (char-before) ?|))
19382 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19383 (looking-at-p ".*?|")
19384 (org-at-table-p))
19385 (progn (forward-char -1) (org-delete-char 1))
19386 (backward-delete-char N)
19387 (org-fix-tags-on-the-fly))))
19389 (defun org-delete-char (N)
19390 "Like `delete-char', but insert whitespace at field end in tables.
19391 When deleting characters, in tables this function will insert whitespace in
19392 front of the next \"|\" separator, to keep the table aligned. The table will
19393 still be marked for re-alignment if the field did fill the entire column,
19394 because, in this case the deletion might narrow the column."
19395 (interactive "p")
19396 (save-match-data
19397 (org-check-before-invisible-edit 'delete)
19398 (cond
19399 ((or (/= N 1)
19400 (eq (char-after) ?|)
19401 (save-excursion (skip-chars-backward " \t") (bolp))
19402 (not (org-at-table-p)))
19403 (delete-char N)
19404 (org-fix-tags-on-the-fly))
19405 ((looking-at ".\\(.*?\\)|")
19406 (let* ((update? org-table-may-need-update)
19407 (noalign (looking-at-p ".*? |")))
19408 (delete-char 1)
19409 (org-table-with-shrunk-field
19410 (save-excursion
19411 ;; Last space is `org-table-separator-space', so insert
19412 ;; a regular one before it instead.
19413 (goto-char (- (match-end 0) 2))
19414 (insert " ")))
19415 ;; If there were two spaces at the end, this field does not
19416 ;; determine the width of the column.
19417 (when noalign (setq org-table-may-need-update update?))))
19419 (delete-char N)))))
19421 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19422 (put 'org-self-insert-command 'delete-selection
19423 (lambda ()
19424 (not (run-hook-with-args-until-success
19425 'self-insert-uses-region-functions))))
19426 (put 'orgtbl-self-insert-command 'delete-selection
19427 (lambda ()
19428 (not (run-hook-with-args-until-success
19429 'self-insert-uses-region-functions))))
19430 (put 'org-delete-char 'delete-selection 'supersede)
19431 (put 'org-delete-backward-char 'delete-selection 'supersede)
19432 (put 'org-yank 'delete-selection 'yank)
19434 ;; Make `flyspell-mode' delay after some commands
19435 (put 'org-self-insert-command 'flyspell-delayed t)
19436 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19437 (put 'org-delete-char 'flyspell-delayed t)
19438 (put 'org-delete-backward-char 'flyspell-delayed t)
19440 ;; Make pabbrev-mode expand after Org mode commands
19441 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19442 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19444 (defun org-transpose-words ()
19445 "Transpose words for Org.
19446 This uses the `org-mode-transpose-word-syntax-table' syntax
19447 table, which interprets characters in `org-emphasis-alist' as
19448 word constituents."
19449 (interactive)
19450 (with-syntax-table org-mode-transpose-word-syntax-table
19451 (call-interactively 'transpose-words)))
19453 (defvar org-ctrl-c-ctrl-c-hook nil
19454 "Hook for functions attaching themselves to `C-c C-c'.
19456 This can be used to add additional functionality to the C-c C-c
19457 key which executes context-dependent commands. This hook is run
19458 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19459 run after the last test.
19461 Each function will be called with no arguments. The function
19462 must check if the context is appropriate for it to act. If yes,
19463 it should do its thing and then return a non-nil value. If the
19464 context is wrong, just do nothing and return nil.")
19466 (defvar org-ctrl-c-ctrl-c-final-hook nil
19467 "Hook for functions attaching themselves to `C-c C-c'.
19469 This can be used to add additional functionality to the C-c C-c
19470 key which executes context-dependent commands. This hook is run
19471 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19472 before the first test.
19474 Each function will be called with no arguments. The function
19475 must check if the context is appropriate for it to act. If yes,
19476 it should do its thing and then return a non-nil value. If the
19477 context is wrong, just do nothing and return nil.")
19479 (defvar org-tab-first-hook nil
19480 "Hook for functions to attach themselves to TAB.
19481 See `org-ctrl-c-ctrl-c-hook' for more information.
19482 This hook runs as the first action when TAB is pressed, even before
19483 `org-cycle' messes around with the `outline-regexp' to cater for
19484 inline tasks and plain list item folding.
19485 If any function in this hook returns t, any other actions that
19486 would have been caused by TAB (such as table field motion or visibility
19487 cycling) will not occur.")
19489 (defvar org-tab-after-check-for-table-hook nil
19490 "Hook for functions to attach themselves to TAB.
19491 See `org-ctrl-c-ctrl-c-hook' for more information.
19492 This hook runs after it has been established that the cursor is not in a
19493 table, but before checking if the cursor is in a headline or if global cycling
19494 should be done.
19495 If any function in this hook returns t, not other actions like visibility
19496 cycling will be done.")
19498 (defvar org-tab-after-check-for-cycling-hook nil
19499 "Hook for functions to attach themselves to TAB.
19500 See `org-ctrl-c-ctrl-c-hook' for more information.
19501 This hook runs after it has been established that not table field motion and
19502 not visibility should be done because of current context. This is probably
19503 the place where a package like yasnippets can hook in.")
19505 (defvar org-tab-before-tab-emulation-hook nil
19506 "Hook for functions to attach themselves to TAB.
19507 See `org-ctrl-c-ctrl-c-hook' for more information.
19508 This hook runs after every other options for TAB have been exhausted, but
19509 before indentation and \t insertion takes place.")
19511 (defvar org-metaleft-hook nil
19512 "Hook for functions attaching themselves to `M-left'.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.")
19514 (defvar org-metaright-hook nil
19515 "Hook for functions attaching themselves to `M-right'.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.")
19517 (defvar org-metaup-hook nil
19518 "Hook for functions attaching themselves to `M-up'.
19519 See `org-ctrl-c-ctrl-c-hook' for more information.")
19520 (defvar org-metadown-hook nil
19521 "Hook for functions attaching themselves to `M-down'.
19522 See `org-ctrl-c-ctrl-c-hook' for more information.")
19523 (defvar org-shiftmetaleft-hook nil
19524 "Hook for functions attaching themselves to `M-S-left'.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.")
19526 (defvar org-shiftmetaright-hook nil
19527 "Hook for functions attaching themselves to `M-S-right'.
19528 See `org-ctrl-c-ctrl-c-hook' for more information.")
19529 (defvar org-shiftmetaup-hook nil
19530 "Hook for functions attaching themselves to `M-S-up'.
19531 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defvar org-shiftmetadown-hook nil
19533 "Hook for functions attaching themselves to `M-S-down'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-metareturn-hook nil
19536 "Hook for functions attaching themselves to `M-RET'.
19537 See `org-ctrl-c-ctrl-c-hook' for more information.")
19538 (defvar org-shiftup-hook nil
19539 "Hook for functions attaching themselves to `S-up'.
19540 See `org-ctrl-c-ctrl-c-hook' for more information.")
19541 (defvar org-shiftup-final-hook nil
19542 "Hook for functions attaching themselves to `S-up'.
19543 This one runs after all other options except shift-select have been excluded.
19544 See `org-ctrl-c-ctrl-c-hook' for more information.")
19545 (defvar org-shiftdown-hook nil
19546 "Hook for functions attaching themselves to `S-down'.
19547 See `org-ctrl-c-ctrl-c-hook' for more information.")
19548 (defvar org-shiftdown-final-hook nil
19549 "Hook for functions attaching themselves to `S-down'.
19550 This one runs after all other options except shift-select have been excluded.
19551 See `org-ctrl-c-ctrl-c-hook' for more information.")
19552 (defvar org-shiftleft-hook nil
19553 "Hook for functions attaching themselves to `S-left'.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defvar org-shiftleft-final-hook nil
19556 "Hook for functions attaching themselves to `S-left'.
19557 This one runs after all other options except shift-select have been excluded.
19558 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defvar org-shiftright-hook nil
19560 "Hook for functions attaching themselves to `S-right'.
19561 See `org-ctrl-c-ctrl-c-hook' for more information.")
19562 (defvar org-shiftright-final-hook nil
19563 "Hook for functions attaching themselves to `S-right'.
19564 This one runs after all other options except shift-select have been excluded.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19567 (defun org-modifier-cursor-error ()
19568 "Throw an error, a modified cursor command was applied in wrong context."
19569 (user-error "This command is active in special context like tables, headlines or items"))
19571 (defun org-shiftselect-error ()
19572 "Throw an error because Shift-Cursor command was applied in wrong context."
19573 (if (and (boundp 'shift-select-mode) shift-select-mode)
19574 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19575 (user-error "This command works only in special context like headlines or timestamps")))
19577 (defun org-call-for-shift-select (cmd)
19578 (let ((this-command-keys-shift-translated t))
19579 (call-interactively cmd)))
19581 (defun org-shifttab (&optional arg)
19582 "Global visibility cycling or move to previous table field.
19583 Call `org-table-previous-field' within a table.
19584 When ARG is nil, cycle globally through visibility states.
19585 When ARG is a numeric prefix, show contents of this level."
19586 (interactive "P")
19587 (cond
19588 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19589 ((integerp arg)
19590 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19591 (message "Content view to level: %d" arg)
19592 (org-content (prefix-numeric-value arg2))
19593 (org-cycle-show-empty-lines t)
19594 (setq org-cycle-global-status 'overview)))
19595 (t (call-interactively 'org-global-cycle))))
19597 (defun org-shiftmetaleft ()
19598 "Promote subtree or delete table column.
19599 Calls `org-promote-subtree', `org-outdent-item-tree', or
19600 `org-table-delete-column', depending on context. See the
19601 individual commands for more information."
19602 (interactive)
19603 (cond
19604 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19605 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19606 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19607 ((if (not (org-region-active-p)) (org-at-item-p)
19608 (save-excursion (goto-char (region-beginning))
19609 (org-at-item-p)))
19610 (call-interactively 'org-outdent-item-tree))
19611 (t (org-modifier-cursor-error))))
19613 (defun org-shiftmetaright ()
19614 "Demote subtree or insert table column.
19615 Calls `org-demote-subtree', `org-indent-item-tree', or
19616 `org-table-insert-column', depending on context. See the
19617 individual commands for more information."
19618 (interactive)
19619 (cond
19620 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19621 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19622 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19623 ((if (not (org-region-active-p)) (org-at-item-p)
19624 (save-excursion (goto-char (region-beginning))
19625 (org-at-item-p)))
19626 (call-interactively 'org-indent-item-tree))
19627 (t (org-modifier-cursor-error))))
19629 (defun org-shiftmetaup (&optional _arg)
19630 "Drag the line at point up.
19631 In a table, kill the current row.
19632 On a clock timestamp, update the value of the timestamp like `S-<up>'
19633 but also adjust the previous clocked item in the clock history.
19634 Everywhere else, drag the line at point up."
19635 (interactive "P")
19636 (cond
19637 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19638 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19639 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19640 (call-interactively 'org-timestamp-up)))
19641 (t (call-interactively 'org-drag-line-backward))))
19643 (defun org-shiftmetadown (&optional _arg)
19644 "Drag the line at point down.
19645 In a table, insert an empty row at the current line.
19646 On a clock timestamp, update the value of the timestamp like `S-<down>'
19647 but also adjust the previous clocked item in the clock history.
19648 Everywhere else, drag the line at point down."
19649 (interactive "P")
19650 (cond
19651 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19652 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19653 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19654 (call-interactively 'org-timestamp-down)))
19655 (t (call-interactively 'org-drag-line-forward))))
19657 (defsubst org-hidden-tree-error ()
19658 (user-error
19659 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19661 (defun org-metaleft (&optional _arg)
19662 "Promote heading, list item at point or move table column left.
19664 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19665 depending on context. With no specific context, calls the Emacs
19666 default `backward-word'. See the individual commands for more
19667 information.
19669 This function runs the hook `org-metaleft-hook' as a first step,
19670 and returns at first non-nil value."
19671 (interactive "P")
19672 (cond
19673 ((run-hook-with-args-until-success 'org-metaleft-hook))
19674 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19675 ((org-with-limited-levels
19676 (or (org-at-heading-p)
19677 (and (org-region-active-p)
19678 (save-excursion
19679 (goto-char (region-beginning))
19680 (org-at-heading-p)))))
19681 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19682 (call-interactively 'org-do-promote))
19683 ;; At an inline task.
19684 ((org-at-heading-p)
19685 (call-interactively 'org-inlinetask-promote))
19686 ((or (org-at-item-p)
19687 (and (org-region-active-p)
19688 (save-excursion
19689 (goto-char (region-beginning))
19690 (org-at-item-p))))
19691 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19692 (call-interactively 'org-outdent-item))
19693 (t (call-interactively 'backward-word))))
19695 (defun org-metaright (&optional _arg)
19696 "Demote heading, list item at point or move table column right.
19698 In front of a drawer or a block keyword, indent it correctly.
19700 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19701 `org-indent-drawer' or `org-indent-block' depending on context.
19702 With no specific context, calls the Emacs default `forward-word'.
19703 See the individual commands for more information.
19705 This function runs the hook `org-metaright-hook' as a first step,
19706 and returns at first non-nil value."
19707 (interactive "P")
19708 (cond
19709 ((run-hook-with-args-until-success 'org-metaright-hook))
19710 ((org-at-table-p) (call-interactively 'org-table-move-column))
19711 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19712 ((org-at-block-p) (call-interactively 'org-indent-block))
19713 ((org-with-limited-levels
19714 (or (org-at-heading-p)
19715 (and (org-region-active-p)
19716 (save-excursion
19717 (goto-char (region-beginning))
19718 (org-at-heading-p)))))
19719 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19720 (call-interactively 'org-do-demote))
19721 ;; At an inline task.
19722 ((org-at-heading-p)
19723 (call-interactively 'org-inlinetask-demote))
19724 ((or (org-at-item-p)
19725 (and (org-region-active-p)
19726 (save-excursion
19727 (goto-char (region-beginning))
19728 (org-at-item-p))))
19729 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19730 (call-interactively 'org-indent-item))
19731 (t (call-interactively 'forward-word))))
19733 (defun org-check-for-hidden (what)
19734 "Check if there are hidden headlines/items in the current visual line.
19735 WHAT can be either `headlines' or `items'. If the current line is
19736 an outline or item heading and it has a folded subtree below it,
19737 this function returns t, nil otherwise."
19738 (let ((re (cond
19739 ((eq what 'headlines) org-outline-regexp-bol)
19740 ((eq what 'items) (org-item-beginning-re))
19741 (t (error "This should not happen"))))
19742 beg end)
19743 (save-excursion
19744 (catch 'exit
19745 (unless (org-region-active-p)
19746 (setq beg (point-at-bol))
19747 (beginning-of-line 2)
19748 (while (and (not (eobp)) ;; this is like `next-line'
19749 (get-char-property (1- (point)) 'invisible))
19750 (beginning-of-line 2))
19751 (setq end (point))
19752 (goto-char beg)
19753 (goto-char (point-at-eol))
19754 (setq end (max end (point)))
19755 (while (re-search-forward re end t)
19756 (when (get-char-property (match-beginning 0) 'invisible)
19757 (throw 'exit t))))
19758 nil))))
19760 (defun org-metaup (&optional _arg)
19761 "Move subtree up or move table row up.
19762 Calls `org-move-subtree-up' or `org-table-move-row' or
19763 `org-move-item-up', depending on context. See the individual commands
19764 for more information."
19765 (interactive "P")
19766 (cond
19767 ((run-hook-with-args-until-success 'org-metaup-hook))
19768 ((org-region-active-p)
19769 (let* ((a (min (region-beginning) (region-end)))
19770 (b (1- (max (region-beginning) (region-end))))
19771 (c (save-excursion (goto-char a)
19772 (move-beginning-of-line 0)))
19773 (d (save-excursion (goto-char a)
19774 (move-end-of-line 0) (point))))
19775 (transpose-regions a b c d)
19776 (goto-char c)))
19777 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19778 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19779 ((org-at-item-p) (call-interactively 'org-move-item-up))
19780 (t (org-drag-element-backward))))
19782 (defun org-metadown (&optional _arg)
19783 "Move subtree down or move table row down.
19784 Calls `org-move-subtree-down' or `org-table-move-row' or
19785 `org-move-item-down', depending on context. See the individual
19786 commands for more information."
19787 (interactive "P")
19788 (cond
19789 ((run-hook-with-args-until-success 'org-metadown-hook))
19790 ((org-region-active-p)
19791 (let* ((a (min (region-beginning) (region-end)))
19792 (b (max (region-beginning) (region-end)))
19793 (c (save-excursion (goto-char b)
19794 (move-beginning-of-line 1)))
19795 (d (save-excursion (goto-char b)
19796 (move-end-of-line 1) (1+ (point)))))
19797 (transpose-regions a b c d)
19798 (goto-char d)))
19799 ((org-at-table-p) (call-interactively 'org-table-move-row))
19800 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19801 ((org-at-item-p) (call-interactively 'org-move-item-down))
19802 (t (org-drag-element-forward))))
19804 (defun org-shiftup (&optional arg)
19805 "Increase item in timestamp or increase priority of current headline.
19806 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19807 depending on context. See the individual commands for more information."
19808 (interactive "P")
19809 (cond
19810 ((run-hook-with-args-until-success 'org-shiftup-hook))
19811 ((and org-support-shift-select (org-region-active-p))
19812 (org-call-for-shift-select 'previous-line))
19813 ((org-at-timestamp-p 'lax)
19814 (call-interactively (if org-edit-timestamp-down-means-later
19815 'org-timestamp-down 'org-timestamp-up)))
19816 ((and (not (eq org-support-shift-select 'always))
19817 org-enable-priority-commands
19818 (org-at-heading-p))
19819 (call-interactively 'org-priority-up))
19820 ((and (not org-support-shift-select) (org-at-item-p))
19821 (call-interactively 'org-previous-item))
19822 ((org-clocktable-try-shift 'up arg))
19823 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19824 (org-support-shift-select
19825 (org-call-for-shift-select 'previous-line))
19826 (t (org-shiftselect-error))))
19828 (defun org-shiftdown (&optional arg)
19829 "Decrease item in timestamp or decrease priority of current headline.
19830 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19831 depending on context. See the individual commands for more information."
19832 (interactive "P")
19833 (cond
19834 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19835 ((and org-support-shift-select (org-region-active-p))
19836 (org-call-for-shift-select 'next-line))
19837 ((org-at-timestamp-p 'lax)
19838 (call-interactively (if org-edit-timestamp-down-means-later
19839 'org-timestamp-up 'org-timestamp-down)))
19840 ((and (not (eq org-support-shift-select 'always))
19841 org-enable-priority-commands
19842 (org-at-heading-p))
19843 (call-interactively 'org-priority-down))
19844 ((and (not org-support-shift-select) (org-at-item-p))
19845 (call-interactively 'org-next-item))
19846 ((org-clocktable-try-shift 'down arg))
19847 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19848 (org-support-shift-select
19849 (org-call-for-shift-select 'next-line))
19850 (t (org-shiftselect-error))))
19852 (defun org-shiftright (&optional arg)
19853 "Cycle the thing at point or in the current line, depending on context.
19854 Depending on context, this does one of the following:
19856 - switch a timestamp at point one day into the future
19857 - on a headline, switch to the next TODO keyword.
19858 - on an item, switch entire list to the next bullet type
19859 - on a property line, switch to the next allowed value
19860 - on a clocktable definition line, move time block into the future"
19861 (interactive "P")
19862 (cond
19863 ((run-hook-with-args-until-success 'org-shiftright-hook))
19864 ((and org-support-shift-select (org-region-active-p))
19865 (org-call-for-shift-select 'forward-char))
19866 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19867 ((and (not (eq org-support-shift-select 'always))
19868 (org-at-heading-p))
19869 (let ((org-inhibit-logging
19870 (not org-treat-S-cursor-todo-selection-as-state-change))
19871 (org-inhibit-blocking
19872 (not org-treat-S-cursor-todo-selection-as-state-change)))
19873 (org-call-with-arg 'org-todo 'right)))
19874 ((or (and org-support-shift-select
19875 (not (eq org-support-shift-select 'always))
19876 (org-at-item-bullet-p))
19877 (and (not org-support-shift-select) (org-at-item-p)))
19878 (org-call-with-arg 'org-cycle-list-bullet nil))
19879 ((and (not (eq org-support-shift-select 'always))
19880 (org-at-property-p))
19881 (call-interactively 'org-property-next-allowed-value))
19882 ((org-clocktable-try-shift 'right arg))
19883 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19884 (org-support-shift-select
19885 (org-call-for-shift-select 'forward-char))
19886 (t (org-shiftselect-error))))
19888 (defun org-shiftleft (&optional arg)
19889 "Cycle the thing at point or in the current line, depending on context.
19890 Depending on context, this does one of the following:
19892 - switch a timestamp at point one day into the past
19893 - on a headline, switch to the previous TODO keyword.
19894 - on an item, switch entire list to the previous bullet type
19895 - on a property line, switch to the previous allowed value
19896 - on a clocktable definition line, move time block into the past"
19897 (interactive "P")
19898 (cond
19899 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19900 ((and org-support-shift-select (org-region-active-p))
19901 (org-call-for-shift-select 'backward-char))
19902 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19903 ((and (not (eq org-support-shift-select 'always))
19904 (org-at-heading-p))
19905 (let ((org-inhibit-logging
19906 (not org-treat-S-cursor-todo-selection-as-state-change))
19907 (org-inhibit-blocking
19908 (not org-treat-S-cursor-todo-selection-as-state-change)))
19909 (org-call-with-arg 'org-todo 'left)))
19910 ((or (and org-support-shift-select
19911 (not (eq org-support-shift-select 'always))
19912 (org-at-item-bullet-p))
19913 (and (not org-support-shift-select) (org-at-item-p)))
19914 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19915 ((and (not (eq org-support-shift-select 'always))
19916 (org-at-property-p))
19917 (call-interactively 'org-property-previous-allowed-value))
19918 ((org-clocktable-try-shift 'left arg))
19919 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19920 (org-support-shift-select
19921 (org-call-for-shift-select 'backward-char))
19922 (t (org-shiftselect-error))))
19924 (defun org-shiftcontrolright ()
19925 "Switch to next TODO set."
19926 (interactive)
19927 (cond
19928 ((and org-support-shift-select (org-region-active-p))
19929 (org-call-for-shift-select 'forward-word))
19930 ((and (not (eq org-support-shift-select 'always))
19931 (org-at-heading-p))
19932 (org-call-with-arg 'org-todo 'nextset))
19933 (org-support-shift-select
19934 (org-call-for-shift-select 'forward-word))
19935 (t (org-shiftselect-error))))
19937 (defun org-shiftcontrolleft ()
19938 "Switch to previous TODO set."
19939 (interactive)
19940 (cond
19941 ((and org-support-shift-select (org-region-active-p))
19942 (org-call-for-shift-select 'backward-word))
19943 ((and (not (eq org-support-shift-select 'always))
19944 (org-at-heading-p))
19945 (org-call-with-arg 'org-todo 'previousset))
19946 (org-support-shift-select
19947 (org-call-for-shift-select 'backward-word))
19948 (t (org-shiftselect-error))))
19950 (defun org-shiftcontrolup (&optional n)
19951 "Change timestamps synchronously up in CLOCK log lines.
19952 Optional argument N tells to change by that many units."
19953 (interactive "P")
19954 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19955 (let (org-support-shift-select)
19956 (org-clock-timestamps-up n))
19957 (user-error "Not at a clock log")))
19959 (defun org-shiftcontroldown (&optional n)
19960 "Change timestamps synchronously down in CLOCK log lines.
19961 Optional argument N tells to change by that many units."
19962 (interactive "P")
19963 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19964 (let (org-support-shift-select)
19965 (org-clock-timestamps-down n))
19966 (user-error "Not at a clock log")))
19968 (defun org-increase-number-at-point (&optional inc)
19969 "Increment the number at point.
19970 With an optional prefix numeric argument INC, increment using
19971 this numeric value."
19972 (interactive "p")
19973 (if (not (number-at-point))
19974 (user-error "Not on a number")
19975 (unless inc (setq inc 1))
19976 (let ((pos (point))
19977 (beg (skip-chars-backward "-+^/*0-9eE."))
19978 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19979 (setq nap (buffer-substring-no-properties
19980 (+ pos beg) (+ pos beg end)))
19981 (delete-region (+ pos beg) (+ pos beg end))
19982 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19983 (when (org-at-table-p)
19984 (org-table-align)
19985 (org-table-end-of-field 1))))
19987 (defun org-decrease-number-at-point (&optional inc)
19988 "Decrement the number at point.
19989 With an optional prefix numeric argument INC, decrement using
19990 this numeric value."
19991 (interactive "p")
19992 (org-increase-number-at-point (- (or inc 1))))
19994 (defun org-ctrl-c-ret ()
19995 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19996 (interactive)
19997 (cond
19998 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19999 (t (call-interactively 'org-insert-heading))))
20001 (defun org-find-visible ()
20002 (let ((s (point)))
20003 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20004 (get-char-property s 'invisible)))
20006 (defun org-find-invisible ()
20007 (let ((s (point)))
20008 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20009 (not (get-char-property s 'invisible))))
20012 (defun org-copy-visible (beg end)
20013 "Copy the visible parts of the region."
20014 (interactive "r")
20015 (let ((result ""))
20016 (while (/= beg end)
20017 (when (get-char-property beg 'invisible)
20018 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20019 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20020 (setq result (concat result (buffer-substring beg next)))
20021 (setq beg next)))
20022 (kill-new result)
20023 (message "Visible strings have been copied to the kill ring.")))
20025 (defun org-copy-special ()
20026 "Copy region in table or copy current subtree.
20027 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20028 context. See the individual commands for more information."
20029 (interactive)
20030 (call-interactively
20031 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20033 (defun org-cut-special ()
20034 "Cut region in table or cut current subtree.
20035 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20036 context. See the individual commands for more information."
20037 (interactive)
20038 (call-interactively
20039 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20041 (defun org-paste-special (arg)
20042 "Paste rectangular region into table, or past subtree relative to level.
20043 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20044 See the individual commands for more information."
20045 (interactive "P")
20046 (if (org-at-table-p)
20047 (org-table-paste-rectangle)
20048 (org-paste-subtree arg)))
20050 (defun org-edit-special (&optional arg)
20051 "Call a special editor for the element at point.
20052 When at a table, call the formula editor with `org-table-edit-formulas'.
20053 When in a source code block, call `org-edit-src-code'.
20054 When in a fixed-width region, call `org-edit-fixed-width-region'.
20055 When in an export block, call `org-edit-export-block'.
20056 When in a LaTeX environment, call `org-edit-latex-environment'.
20057 When at an #+INCLUDE keyword, visit the included file.
20058 When at a footnote reference, call `org-edit-footnote-reference'
20059 On a link, call `ffap' to visit the link at point.
20060 Otherwise, return a user error."
20061 (interactive "P")
20062 (let ((element (org-element-at-point)))
20063 (barf-if-buffer-read-only)
20064 (pcase (org-element-type element)
20065 (`src-block
20066 (if (not arg) (org-edit-src-code)
20067 (let* ((info (org-babel-get-src-block-info))
20068 (lang (nth 0 info))
20069 (params (nth 2 info))
20070 (session (cdr (assq :session params))))
20071 (if (not session) (org-edit-src-code)
20072 ;; At a src-block with a session and function called with
20073 ;; an ARG: switch to the buffer related to the inferior
20074 ;; process.
20075 (switch-to-buffer
20076 (funcall (intern (concat "org-babel-prep-session:" lang))
20077 session params))))))
20078 (`keyword
20079 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20080 (org-open-link-from-string
20081 (format "[[%s]]"
20082 (expand-file-name
20083 (let ((value (org-element-property :value element)))
20084 (cond ((org-file-url-p value)
20085 (user-error "The file is specified as a URL, cannot be edited"))
20086 ((not (org-string-nw-p value))
20087 (user-error "No file to edit"))
20088 ((string-match "\\`\"\\(.*?\\)\"" value)
20089 (match-string 1 value))
20090 ((string-match "\\`[^ \t\"]\\S-*" value)
20091 (match-string 0 value))
20092 (t (user-error "No valid file specified")))))))
20093 (user-error "No special environment to edit here")))
20094 (`table
20095 (if (eq (org-element-property :type element) 'table.el)
20096 (org-edit-table.el)
20097 (call-interactively 'org-table-edit-formulas)))
20098 ;; Only Org tables contain `table-row' type elements.
20099 (`table-row (call-interactively 'org-table-edit-formulas))
20100 (`example-block (org-edit-src-code))
20101 (`export-block (org-edit-export-block))
20102 (`fixed-width (org-edit-fixed-width-region))
20103 (`latex-environment (org-edit-latex-environment))
20105 ;; No notable element at point. Though, we may be at a link or
20106 ;; a footnote reference, which are objects. Thus, scan deeper.
20107 (let ((context (org-element-context element)))
20108 (pcase (org-element-type context)
20109 (`footnote-reference (org-edit-footnote-reference))
20110 (`inline-src-block (org-edit-inline-src-code))
20111 (`link (call-interactively #'ffap))
20112 (_ (user-error "No special environment to edit here"))))))))
20114 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20115 (defun org-ctrl-c-ctrl-c (&optional arg)
20116 "Set tags in headline, or update according to changed information at point.
20118 This command does many different things, depending on context:
20120 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20121 this is what we do.
20123 - If the cursor is on a statistics cookie, update it.
20125 - If the cursor is in a headline, prompt for tags and insert them
20126 into the current line, aligned to `org-tags-column'. When called
20127 with prefix arg, realign all tags in the current buffer.
20129 - If the cursor is in one of the special #+KEYWORD lines, this
20130 triggers scanning the buffer for these lines and updating the
20131 information.
20133 - If the cursor is inside a table, realign the table. This command
20134 works even if the automatic table editor has been turned off.
20136 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20137 the entire table.
20139 - If the cursor is at a footnote reference or definition, jump to
20140 the corresponding definition or references, respectively.
20142 - If the cursor is a the beginning of a dynamic block, update it.
20144 - If the current buffer is a capture buffer, close note and file it.
20146 - If the cursor is on a <<<target>>>, update radio targets and
20147 corresponding links in this buffer.
20149 - If the cursor is on a numbered item in a plain list, renumber the
20150 ordered list.
20152 - If the cursor is on a checkbox, toggle it.
20154 - If the cursor is on a code block, evaluate it. The variable
20155 `org-confirm-babel-evaluate' can be used to control prompting
20156 before code block evaluation, by default every code block
20157 evaluation requires confirmation. Code block evaluation can be
20158 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20159 (interactive "P")
20160 (cond
20161 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20162 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20163 (org-remove-occur-highlights)
20164 (message "Temporary highlights/overlays removed from current buffer"))
20165 ((and (local-variable-p 'org-finish-function)
20166 (fboundp org-finish-function))
20167 (funcall org-finish-function))
20168 ((org-babel-hash-at-point))
20169 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20171 (let* ((context
20172 (org-element-lineage
20173 (org-element-context)
20174 ;; Limit to supported contexts.
20175 '(babel-call clock dynamic-block footnote-definition
20176 footnote-reference inline-babel-call inline-src-block
20177 inlinetask item keyword node-property paragraph
20178 plain-list planning property-drawer radio-target
20179 src-block statistics-cookie table table-cell table-row
20180 timestamp)
20182 (type (org-element-type context)))
20183 ;; For convenience: at the first line of a paragraph on the same
20184 ;; line as an item, apply function on that item instead.
20185 (when (eq type 'paragraph)
20186 (let ((parent (org-element-property :parent context)))
20187 (when (and (eq (org-element-type parent) 'item)
20188 (= (line-beginning-position)
20189 (org-element-property :begin parent)))
20190 (setq context parent)
20191 (setq type 'item))))
20192 ;; Act according to type of element or object at point.
20194 ;; Do nothing on a blank line, except if it is contained in
20195 ;; a src block. Hence, we first check if point is in such
20196 ;; a block and then if it is at a blank line.
20197 (pcase type
20198 ((or `inline-src-block `src-block)
20199 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20200 (org-babel-eval-wipe-error-buffer)
20201 (org-babel-execute-src-block
20202 current-prefix-arg (org-babel-get-src-block-info nil context))))
20203 ((guard (org-match-line "[ \t]*$"))
20204 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20205 (user-error
20206 (substitute-command-keys
20207 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20208 ((or `babel-call `inline-babel-call)
20209 (let ((info (org-babel-lob-get-info context)))
20210 (when info (org-babel-execute-src-block nil info))))
20211 (`clock (org-clock-update-time-maybe))
20212 (`dynamic-block
20213 (save-excursion
20214 (goto-char (org-element-property :post-affiliated context))
20215 (org-update-dblock)))
20216 (`footnote-definition
20217 (goto-char (org-element-property :post-affiliated context))
20218 (call-interactively 'org-footnote-action))
20219 (`footnote-reference (call-interactively #'org-footnote-action))
20220 ((or `headline `inlinetask)
20221 (save-excursion (goto-char (org-element-property :begin context))
20222 (call-interactively #'org-set-tags-command)))
20223 (`item
20224 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20225 ;; unconditionally, whereas `C-u' will toggle its presence.
20226 ;; Without a universal argument, if the item has a checkbox,
20227 ;; toggle it. Otherwise repair the list.
20228 (let* ((box (org-element-property :checkbox context))
20229 (struct (org-element-property :structure context))
20230 (old-struct (copy-tree struct))
20231 (parents (org-list-parents-alist struct))
20232 (prevs (org-list-prevs-alist struct))
20233 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20234 (org-list-set-checkbox
20235 (org-element-property :begin context) struct
20236 (cond ((equal arg '(16)) "[-]")
20237 ((and (not box) (equal arg '(4))) "[ ]")
20238 ((or (not box) (equal arg '(4))) nil)
20239 ((eq box 'on) "[ ]")
20240 (t "[X]")))
20241 ;; Mimic `org-list-write-struct' but with grabbing a return
20242 ;; value from `org-list-struct-fix-box'.
20243 (org-list-struct-fix-ind struct parents 2)
20244 (org-list-struct-fix-item-end struct)
20245 (org-list-struct-fix-bul struct prevs)
20246 (org-list-struct-fix-ind struct parents)
20247 (let ((block-item
20248 (org-list-struct-fix-box struct parents prevs orderedp)))
20249 (if (and box (equal struct old-struct))
20250 (if (equal arg '(16))
20251 (message "Checkboxes already reset")
20252 (user-error "Cannot toggle this checkbox: %s"
20253 (if (eq box 'on)
20254 "all subitems checked"
20255 "unchecked subitems")))
20256 (org-list-struct-apply-struct struct old-struct)
20257 (org-update-checkbox-count-maybe))
20258 (when block-item
20259 (message "Checkboxes were removed due to empty box at line %d"
20260 (org-current-line block-item))))))
20261 (`keyword
20262 (let ((org-inhibit-startup-visibility-stuff t)
20263 (org-startup-align-all-tables nil))
20264 (when (boundp 'org-table-coordinate-overlays)
20265 (mapc #'delete-overlay org-table-coordinate-overlays)
20266 (setq org-table-coordinate-overlays nil))
20267 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20268 (message "Local setup has been refreshed"))
20269 (`plain-list
20270 ;; At a plain list, with a double C-u argument, set
20271 ;; checkboxes of each item to "[-]", whereas a single one
20272 ;; will toggle their presence according to the state of the
20273 ;; first item in the list. Without an argument, repair the
20274 ;; list.
20275 (let* ((begin (org-element-property :contents-begin context))
20276 (struct (org-element-property :structure context))
20277 (old-struct (copy-tree struct))
20278 (first-box (save-excursion
20279 (goto-char begin)
20280 (looking-at org-list-full-item-re)
20281 (match-string-no-properties 3)))
20282 (new-box (cond ((equal arg '(16)) "[-]")
20283 ((equal arg '(4)) (unless first-box "[ ]"))
20284 ((equal first-box "[X]") "[ ]")
20285 (t "[X]"))))
20286 (cond
20287 (arg
20288 (dolist (pos
20289 (org-list-get-all-items
20290 begin struct (org-list-prevs-alist struct)))
20291 (org-list-set-checkbox pos struct new-box)))
20292 ((and first-box (eq (point) begin))
20293 ;; For convenience, when point is at bol on the first
20294 ;; item of the list and no argument is provided, simply
20295 ;; toggle checkbox of that item, if any.
20296 (org-list-set-checkbox begin struct new-box)))
20297 (when (equal
20298 (org-list-write-struct
20299 struct (org-list-parents-alist struct) old-struct)
20300 old-struct)
20301 (message "Cannot update this checkbox"))
20302 (org-update-checkbox-count-maybe)))
20303 ((or `property-drawer `node-property)
20304 (call-interactively #'org-property-action))
20305 (`radio-target
20306 (call-interactively #'org-update-radio-target-regexp))
20307 (`statistics-cookie
20308 (call-interactively #'org-update-statistics-cookies))
20309 ((or `table `table-cell `table-row)
20310 ;; At a table, recalculate every field and align it. Also
20311 ;; send the table if necessary. If the table has
20312 ;; a `table.el' type, just give up. At a table row or cell,
20313 ;; maybe recalculate line but always align table.
20314 (if (eq (org-element-property :type context) 'table.el)
20315 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20316 Use `\\[org-edit-special]' to edit table.el tables"))
20317 (if (or (eq type 'table)
20318 ;; Check if point is at a TBLFM line.
20319 (and (eq type 'table-row)
20320 (= (point) (org-element-property :end context))))
20321 (save-excursion
20322 (if (org-at-TBLFM-p)
20323 (progn (require 'org-table)
20324 (org-table-calc-current-TBLFM))
20325 (goto-char (org-element-property :contents-begin context))
20326 (org-call-with-arg 'org-table-recalculate (or arg t))
20327 (orgtbl-send-table 'maybe)))
20328 (org-table-maybe-eval-formula)
20329 (cond (arg (call-interactively #'org-table-recalculate))
20330 ((org-table-maybe-recalculate-line))
20331 (t (org-table-align))))))
20332 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20333 (org-timestamp-change 0 'day))
20334 ((and `nil (guard (org-at-heading-p)))
20335 ;; When point is on an unsupported object type, we can miss
20336 ;; the fact that it also is at a heading. Handle it here.
20337 (call-interactively #'org-set-tags-command))
20338 ((guard
20339 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20341 (user-error
20342 (substitute-command-keys
20343 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20345 (defun org-mode-restart ()
20346 (interactive)
20347 (let ((indent-status (bound-and-true-p org-indent-mode)))
20348 (funcall major-mode)
20349 (hack-local-variables)
20350 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20351 (org-indent-mode -1))
20352 (org-reset-file-cache))
20353 (message "%s restarted" major-mode))
20355 (defun org-kill-note-or-show-branches ()
20356 "Abort storing current note, or call `outline-show-branches'."
20357 (interactive)
20358 (if (not org-finish-function)
20359 (save-excursion
20360 (save-restriction
20361 (org-narrow-to-subtree)
20362 (org-flag-subtree t)
20363 (call-interactively 'outline-show-branches)
20364 (org-hide-archived-subtrees (point-min) (point-max))))
20365 (let ((org-note-abort t))
20366 (funcall org-finish-function))))
20368 (defun org-delete-indentation (&optional arg)
20369 "Join current line to previous and fix whitespace at join.
20371 If previous line is a headline add to headline title. Otherwise
20372 the function calls `delete-indentation'.
20374 With a non-nil optional argument, join it to the following one."
20375 (interactive "*P")
20376 (if (save-excursion
20377 (beginning-of-line (if arg 1 0))
20378 (let ((case-fold-search nil))
20379 (looking-at org-complex-heading-regexp)))
20380 ;; At headline.
20381 (let ((tags-column (when (match-beginning 5)
20382 (save-excursion (goto-char (match-beginning 5))
20383 (current-column))))
20384 (string (concat " " (progn (when arg (forward-line 1))
20385 (org-trim (delete-and-extract-region
20386 (line-beginning-position)
20387 (line-end-position)))))))
20388 (unless (bobp) (delete-region (point) (1- (point))))
20389 (goto-char (or (match-end 4)
20390 (match-beginning 5)
20391 (match-end 0)))
20392 (skip-chars-backward " \t")
20393 (save-excursion (insert string))
20394 ;; Adjust alignment of tags.
20395 (cond
20396 ((not tags-column)) ;no tags
20397 (org-auto-align-tags (org-align-tags))
20398 (t (org--align-tags-here tags-column)))) ;preserve tags column
20399 (delete-indentation arg)))
20401 (defun org-open-line (n)
20402 "Insert a new row in tables, call `open-line' elsewhere.
20403 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20404 As a special case, when a document starts with a table, allow to
20405 call `open-line' on the very first character."
20406 (interactive "*p")
20407 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20408 (org-table-insert-row)
20409 (open-line n)))
20411 (defun org-return (&optional indent)
20412 "Goto next table row or insert a newline.
20414 Calls `org-table-next-row' or `newline', depending on context.
20416 When optional INDENT argument is non-nil, call
20417 `newline-and-indent' instead of `newline'.
20419 When `org-return-follows-link' is non-nil and point is on
20420 a timestamp or a link, call `org-open-at-point'. However, it
20421 will not happen if point is in a table or on a \"dead\"
20422 object (e.g., within a comment). In these case, you need to use
20423 `org-open-at-point' directly."
20424 (interactive)
20425 (let ((context (if org-return-follows-link (org-element-context)
20426 (org-element-at-point))))
20427 (cond
20428 ;; In a table, call `org-table-next-row'. However, before first
20429 ;; column or after last one, split the table.
20430 ((or (and (eq (org-element-type context) 'table)
20431 (>= (point) (org-element-property :contents-begin context))
20432 (< (point) (org-element-property :contents-end context)))
20433 (org-element-lineage context '(table-row table-cell) t))
20434 (if (or (looking-at-p "[ \t]*$")
20435 (save-excursion (skip-chars-backward " \t") (bolp)))
20436 (insert "\n")
20437 (org-table-justify-field-maybe)
20438 (call-interactively #'org-table-next-row)))
20439 ;; On a link or a timestamp, call `org-open-at-point' if
20440 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20441 ;; locations, e.g., in a comment, as `org-open-at-point'.
20442 ((and org-return-follows-link
20443 (or (and (eq 'link (org-element-type context))
20444 ;; Ensure point is not on the white spaces after
20445 ;; the link.
20446 (let ((origin (point)))
20447 (org-with-point-at (org-element-property :end context)
20448 (skip-chars-backward " \t")
20449 (> (point) origin))))
20450 (org-in-regexp org-ts-regexp-both nil t)
20451 (org-in-regexp org-tsr-regexp-both nil t)
20452 (org-in-regexp org-any-link-re nil t)))
20453 (call-interactively #'org-open-at-point))
20454 ;; Insert newline in heading, but preserve tags.
20455 ((and (not (bolp))
20456 (save-excursion (beginning-of-line)
20457 (let ((case-fold-search nil))
20458 (looking-at org-complex-heading-regexp))))
20459 ;; At headline. Split line. However, if point is on keyword,
20460 ;; priority cookie or tags, do not break any of them: add
20461 ;; a newline after the headline instead.
20462 (let ((tags-column (and (match-beginning 5)
20463 (save-excursion (goto-char (match-beginning 5))
20464 (current-column))))
20465 (string
20466 (when (and (match-end 4) (org-point-in-group (point) 4))
20467 (delete-and-extract-region (point) (match-end 4)))))
20468 ;; Adjust tag alignment.
20469 (cond
20470 ((not (and tags-column string)))
20471 (org-auto-align-tags (org-align-tags))
20472 (t (org--align-tags-here tags-column))) ;preserve tags column
20473 (end-of-line)
20474 (org-show-entry)
20475 (if indent (newline-and-indent) (newline))
20476 (when string (save-excursion (insert (org-trim string))))))
20477 ;; In a list, make sure indenting keeps trailing text within.
20478 ((and indent
20479 (not (eolp))
20480 (org-element-lineage context '(item)))
20481 (let ((trailing-data
20482 (delete-and-extract-region (point) (line-end-position))))
20483 (newline-and-indent)
20484 (save-excursion (insert trailing-data))))
20486 ;; Do not auto-fill when point is in an Org property drawer.
20487 (let ((auto-fill-function (and (not (org-at-property-p))
20488 auto-fill-function)))
20489 (if indent
20490 (newline-and-indent)
20491 (newline)))))))
20493 (defun org-return-indent ()
20494 "Goto next table row or insert a newline and indent.
20495 Calls `org-table-next-row' or `newline-and-indent', depending on
20496 context. See the individual commands for more information."
20497 (interactive)
20498 (org-return t))
20500 (defun org-ctrl-c-tab (&optional _arg)
20501 "Toggle columns width in a table, or show children.
20502 Call `org-table-toggle-column-width' if point is in a table.
20503 Otherwise, call `org-show-children'."
20504 (interactive "p")
20505 (call-interactively
20506 (if (org-at-table-p) #'org-table-toggle-column-width
20507 #'org-show-children)))
20509 (defun org-ctrl-c-star ()
20510 "Compute table, or change heading status of lines.
20511 Calls `org-table-recalculate' or `org-toggle-heading',
20512 depending on context."
20513 (interactive)
20514 (cond
20515 ((org-at-table-p)
20516 (call-interactively 'org-table-recalculate))
20518 ;; Convert all lines in region to list items
20519 (call-interactively 'org-toggle-heading))))
20521 (defun org-ctrl-c-minus ()
20522 "Insert separator line in table or modify bullet status of line.
20523 Also turns a plain line or a region of lines into list items.
20524 Calls `org-table-insert-hline', `org-toggle-item', or
20525 `org-cycle-list-bullet', depending on context."
20526 (interactive)
20527 (cond
20528 ((org-at-table-p)
20529 (call-interactively 'org-table-insert-hline))
20530 ((org-region-active-p)
20531 (call-interactively 'org-toggle-item))
20532 ((org-in-item-p)
20533 (call-interactively 'org-cycle-list-bullet))
20535 (call-interactively 'org-toggle-item))))
20537 (defun org-toggle-heading (&optional nstars)
20538 "Convert headings to normal text, or items or text to headings.
20539 If there is no active region, only convert the current line.
20541 With a `\\[universal-argument]' prefix, convert the whole list at
20542 point into heading.
20544 In a region:
20546 - If the first non blank line is a headline, remove the stars
20547 from all headlines in the region.
20549 - If it is a normal line, turn each and every normal line (i.e.,
20550 not an heading or an item) in the region into headings. If you
20551 want to convert only the first line of this region, use one
20552 universal prefix argument.
20554 - If it is a plain list item, turn all plain list items into headings.
20556 When converting a line into a heading, the number of stars is chosen
20557 such that the lines become children of the current entry. However,
20558 when a numeric prefix argument is given, its value determines the
20559 number of stars to add."
20560 (interactive "P")
20561 (let ((skip-blanks
20562 (function
20563 ;; Return beginning of first non-blank line, starting from
20564 ;; line at POS.
20565 (lambda (pos)
20566 (save-excursion
20567 (goto-char pos)
20568 (while (org-at-comment-p) (forward-line))
20569 (skip-chars-forward " \r\t\n")
20570 (point-at-bol)))))
20571 beg end toggled)
20572 ;; Determine boundaries of changes. If a universal prefix has
20573 ;; been given, put the list in a region. If region ends at a bol,
20574 ;; do not consider the last line to be in the region.
20576 (when (and current-prefix-arg (org-at-item-p))
20577 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20578 (org-mark-element))
20580 (if (org-region-active-p)
20581 (setq beg (funcall skip-blanks (region-beginning))
20582 end (copy-marker (save-excursion
20583 (goto-char (region-end))
20584 (if (bolp) (point) (point-at-eol)))))
20585 (setq beg (funcall skip-blanks (point-at-bol))
20586 end (copy-marker (point-at-eol))))
20587 ;; Ensure inline tasks don't count as headings.
20588 (org-with-limited-levels
20589 (save-excursion
20590 (goto-char beg)
20591 (cond
20592 ;; Case 1. Started at an heading: de-star headings.
20593 ((org-at-heading-p)
20594 (while (< (point) end)
20595 (when (org-at-heading-p t)
20596 (looking-at org-outline-regexp) (replace-match "")
20597 (setq toggled t))
20598 (forward-line)))
20599 ;; Case 2. Started at an item: change items into headlines.
20600 ;; One star will be added by `org-list-to-subtree'.
20601 ((org-at-item-p)
20602 (while (< (point) end)
20603 (when (org-at-item-p)
20604 ;; Pay attention to cases when region ends before list.
20605 (let* ((struct (org-list-struct))
20606 (list-end
20607 (min (org-list-get-bottom-point struct) (1+ end))))
20608 (save-restriction
20609 (narrow-to-region (point) list-end)
20610 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20611 (setq toggled t))
20612 (forward-line)))
20613 ;; Case 3. Started at normal text: make every line an heading,
20614 ;; skipping headlines and items.
20615 (t (let* ((stars
20616 (make-string
20617 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20618 (add-stars
20619 (cond (nstars "") ; stars from prefix only
20620 ((equal stars "") "*") ; before first heading
20621 (org-odd-levels-only "**") ; inside heading, odd
20622 (t "*"))) ; inside heading, oddeven
20623 (rpl (concat stars add-stars " "))
20624 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20625 (while (< (point) (if (equal nstars '(4)) lend end))
20626 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20627 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20628 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20629 (forward-line)))))))
20630 (unless toggled (message "Cannot toggle heading from here"))))
20632 (defun org-meta-return (&optional arg)
20633 "Insert a new heading or wrap a region in a table.
20634 Calls `org-insert-heading', `org-insert-item' or
20635 `org-table-wrap-region', depending on context. When called with
20636 an argument, unconditionally call `org-insert-heading'."
20637 (interactive "P")
20638 (org-check-before-invisible-edit 'insert)
20639 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20640 (call-interactively (cond (arg #'org-insert-heading)
20641 ((org-at-table-p) #'org-table-wrap-region)
20642 ((org-in-item-p) #'org-insert-item)
20643 (t #'org-insert-heading)))))
20645 ;;; Menu entries
20647 (defsubst org-in-subtree-not-table-p ()
20648 "Are we in a subtree and not in a table?"
20649 (and (not (org-before-first-heading-p))
20650 (not (org-at-table-p))))
20652 ;; Define the Org mode menus
20653 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20654 '("Tbl"
20655 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20656 ["Next Field" org-cycle (org-at-table-p)]
20657 ["Previous Field" org-shifttab (org-at-table-p)]
20658 ["Next Row" org-return (org-at-table-p)]
20659 "--"
20660 ["Blank Field" org-table-blank-field (org-at-table-p)]
20661 ["Edit Field" org-table-edit-field (org-at-table-p)]
20662 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20663 "--"
20664 ("Column"
20665 ["Move Column Left" org-metaleft (org-at-table-p)]
20666 ["Move Column Right" org-metaright (org-at-table-p)]
20667 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20668 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20669 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20670 ("Row"
20671 ["Move Row Up" org-metaup (org-at-table-p)]
20672 ["Move Row Down" org-metadown (org-at-table-p)]
20673 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20674 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20675 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20676 "--"
20677 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20678 ("Rectangle"
20679 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20680 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20681 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20682 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20683 "--"
20684 ("Calculate"
20685 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20686 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20687 ["Edit Formulas" org-edit-special (org-at-table-p)]
20688 "--"
20689 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20690 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20691 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20692 "--"
20693 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20694 "--"
20695 ["Sum Column/Rectangle" org-table-sum
20696 (or (org-at-table-p) (org-region-active-p))]
20697 ["Which Column?" org-table-current-column (org-at-table-p)])
20698 ["Debug Formulas"
20699 org-table-toggle-formula-debugger
20700 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20701 ["Show Col/Row Numbers"
20702 org-table-toggle-coordinate-overlays
20703 :style toggle
20704 :selected (bound-and-true-p org-table-overlay-coordinates)]
20705 "--"
20706 ["Create" org-table-create (not (org-at-table-p))]
20707 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20708 ["Import from File" org-table-import (not (org-at-table-p))]
20709 ["Export to File" org-table-export (org-at-table-p)]
20710 "--"
20711 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20712 "--"
20713 ("Plot"
20714 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20715 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20717 (easy-menu-define org-org-menu org-mode-map "Org menu"
20718 '("Org"
20719 ("Show/Hide"
20720 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20721 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20722 ["Sparse Tree..." org-sparse-tree t]
20723 ["Reveal Context" org-reveal t]
20724 ["Show All" org-show-all t]
20725 "--"
20726 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20727 "--"
20728 ["New Heading" org-insert-heading t]
20729 ("Navigate Headings"
20730 ["Up" outline-up-heading t]
20731 ["Next" outline-next-visible-heading t]
20732 ["Previous" outline-previous-visible-heading t]
20733 ["Next Same Level" outline-forward-same-level t]
20734 ["Previous Same Level" outline-backward-same-level t]
20735 "--"
20736 ["Jump" org-goto t])
20737 ("Edit Structure"
20738 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20739 "--"
20740 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20741 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20742 "--"
20743 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20744 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20745 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20746 "--"
20747 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20748 "--"
20749 ["Copy visible text" org-copy-visible t]
20750 "--"
20751 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20752 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20753 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20754 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20755 "--"
20756 ["Sort Region/Children" org-sort t]
20757 "--"
20758 ["Convert to odd levels" org-convert-to-odd-levels t]
20759 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20760 ("Editing"
20761 ["Emphasis..." org-emphasize t]
20762 ["Edit Source Example" org-edit-special t]
20763 "--"
20764 ["Footnote new/jump" org-footnote-action t]
20765 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20766 ("Archive"
20767 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20768 "--"
20769 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20770 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20771 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20773 "--"
20774 ("Hyperlinks"
20775 ["Store Link (Global)" org-store-link t]
20776 ["Find existing link to here" org-occur-link-in-agenda-files t]
20777 ["Insert Link" org-insert-link t]
20778 ["Follow Link" org-open-at-point t]
20779 "--"
20780 ["Next link" org-next-link t]
20781 ["Previous link" org-previous-link t]
20782 "--"
20783 ["Descriptive Links"
20784 org-toggle-link-display
20785 :style radio
20786 :selected org-descriptive-links
20788 ["Literal Links"
20789 org-toggle-link-display
20790 :style radio
20791 :selected (not org-descriptive-links)])
20792 "--"
20793 ("TODO Lists"
20794 ["TODO/DONE/-" org-todo t]
20795 ("Select keyword"
20796 ["Next keyword" org-shiftright (org-at-heading-p)]
20797 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20798 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20799 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20800 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20801 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20802 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20803 "--"
20804 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20805 :selected org-enforce-todo-dependencies :style toggle :active t]
20806 "Settings for tree at point"
20807 ["Do Children sequentially" org-toggle-ordered-property :style radio
20808 :selected (org-entry-get nil "ORDERED")
20809 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20810 ["Do Children parallel" org-toggle-ordered-property :style radio
20811 :selected (not (org-entry-get nil "ORDERED"))
20812 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20813 "--"
20814 ["Set Priority" org-priority t]
20815 ["Priority Up" org-shiftup t]
20816 ["Priority Down" org-shiftdown t]
20817 "--"
20818 ["Get news from all feeds" org-feed-update-all t]
20819 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20820 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20821 ("TAGS and Properties"
20822 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20823 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20824 "--"
20825 ["Set property" org-set-property (not (org-before-first-heading-p))]
20826 ["Column view of properties" org-columns t]
20827 ["Insert Column View DBlock" org-columns-insert-dblock t])
20828 ("Dates and Scheduling"
20829 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20830 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20831 ("Change Date"
20832 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20833 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20834 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20835 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20836 ["Compute Time Range" org-evaluate-time-range t]
20837 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20838 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20839 "--"
20840 ["Custom time format" org-toggle-time-stamp-overlays
20841 :style radio :selected org-display-custom-times]
20842 "--"
20843 ["Goto Calendar" org-goto-calendar t]
20844 ["Date from Calendar" org-date-from-calendar t]
20845 "--"
20846 ["Start/Restart Timer" org-timer-start t]
20847 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20848 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20849 ["Insert Timer String" org-timer t]
20850 ["Insert Timer Item" org-timer-item t])
20851 ("Logging work"
20852 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20853 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20854 ["Clock out" org-clock-out t]
20855 ["Clock cancel" org-clock-cancel t]
20856 "--"
20857 ["Mark as default task" org-clock-mark-default-task t]
20858 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20859 ["Goto running clock" org-clock-goto t]
20860 "--"
20861 ["Display times" org-clock-display t]
20862 ["Create clock table" org-clock-report t]
20863 "--"
20864 ["Record DONE time"
20865 (progn (setq org-log-done (not org-log-done))
20866 (message "Switching to %s will %s record a timestamp"
20867 (car org-done-keywords)
20868 (if org-log-done "automatically" "not")))
20869 :style toggle :selected org-log-done])
20870 "--"
20871 ["Agenda Command..." org-agenda t]
20872 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20873 ("File List for Agenda")
20874 ("Special views current file"
20875 ["TODO Tree" org-show-todo-tree t]
20876 ["Check Deadlines" org-check-deadlines t]
20877 ["Tags/Property tree" org-match-sparse-tree t])
20878 "--"
20879 ["Export/Publish..." org-export-dispatch t]
20880 ("LaTeX"
20881 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20882 :style toggle :selected org-cdlatex-mode]
20883 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20884 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20885 ["Modify math symbol" org-cdlatex-math-modify
20886 (org-inside-LaTeX-fragment-p)]
20887 ["Insert citation" org-reftex-citation t])
20888 "--"
20889 ("MobileOrg"
20890 ["Push Files and Views" org-mobile-push t]
20891 ["Get Captured and Flagged" org-mobile-pull t]
20892 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20893 "--"
20894 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20895 "--"
20896 ("Documentation"
20897 ["Show Version" org-version t]
20898 ["Info Documentation" org-info t])
20899 ("Customize"
20900 ["Browse Org Group" org-customize t]
20901 "--"
20902 ["Expand This Menu" org-create-customize-menu
20903 (fboundp 'customize-menu-create)])
20904 ["Send bug report" org-submit-bug-report t]
20905 "--"
20906 ("Refresh/Reload"
20907 ["Refresh setup current buffer" org-mode-restart t]
20908 ["Reload Org (after update)" org-reload t]
20909 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20912 (defun org-info (&optional node)
20913 "Read documentation for Org in the info system.
20914 With optional NODE, go directly to that node."
20915 (interactive)
20916 (info (format "(org)%s" (or node ""))))
20918 ;;;###autoload
20919 (defun org-submit-bug-report ()
20920 "Submit a bug report on Org via mail.
20922 Don't hesitate to report any problems or inaccurate documentation.
20924 If you don't have setup sending mail from (X)Emacs, please copy the
20925 output buffer into your mail program, as it gives us important
20926 information about your Org version and configuration."
20927 (interactive)
20928 (require 'reporter)
20929 (defvar reporter-prompt-for-summary-p)
20930 (org-load-modules-maybe)
20931 (org-require-autoloaded-modules)
20932 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20933 (reporter-submit-bug-report
20934 "emacs-orgmode@gnu.org"
20935 (org-version nil 'full)
20936 (let (list)
20937 (save-window-excursion
20938 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20939 (delete-other-windows)
20940 (erase-buffer)
20941 (insert "You are about to submit a bug report to the Org mailing list.
20943 We would like to add your full Org and Outline configuration to the
20944 bug report. This greatly simplifies the work of the maintainer and
20945 other experts on the mailing list.
20947 HOWEVER, some variables you have customized may contain private
20948 information. The names of customers, colleagues, or friends, might
20949 appear in the form of file names, tags, todo states, or search strings.
20950 If you answer yes to the prompt, you might want to check and remove
20951 such private information before sending the email.")
20952 (add-text-properties (point-min) (point-max) '(face org-warning))
20953 (when (yes-or-no-p "Include your Org configuration ")
20954 (mapatoms
20955 (lambda (v)
20956 (and (boundp v)
20957 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20958 (or (and (symbol-value v)
20959 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20960 (and
20961 (get v 'custom-type) (get v 'standard-value)
20962 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20963 (push v list)))))
20964 (kill-buffer (get-buffer "*Warn about privacy*"))
20965 list))
20966 nil nil
20967 "Remember to cover the basics, that is, what you expected to happen and
20968 what in fact did happen. You don't know how to make a good report? See
20970 https://orgmode.org/manual/Feedback.html#Feedback
20972 Your bug report will be posted to the Org mailing list.
20973 ------------------------------------------------------------------------")
20974 (save-excursion
20975 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20976 (replace-match "\\1Bug: \\3 [\\2]")))))
20979 (defun org-install-agenda-files-menu ()
20980 (let ((bl (buffer-list)))
20981 (save-excursion
20982 (while bl
20983 (set-buffer (pop bl))
20984 (when (derived-mode-p 'org-mode) (setq bl nil)))
20985 (when (derived-mode-p 'org-mode)
20986 (easy-menu-change
20987 '("Org") "File List for Agenda"
20988 (append
20989 (list
20990 ["Edit File List" (org-edit-agenda-file-list) t]
20991 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20992 ["Remove Current File from List" org-remove-file t]
20993 ["Cycle through agenda files" org-cycle-agenda-files t]
20994 ["Occur in all agenda files" org-occur-in-agenda-files t]
20995 "--")
20996 (mapcar 'org-file-menu-entry
20997 ;; Prevent initialization from failing.
20998 (ignore-errors (org-agenda-files t)))))))))
21000 ;;;; Documentation
21002 (defun org-require-autoloaded-modules ()
21003 (interactive)
21004 (mapc #'require
21005 '(org-agenda org-archive org-attach org-clock org-colview org-id
21006 org-table org-timer)))
21008 ;;;###autoload
21009 (defun org-reload (&optional uncompiled)
21010 "Reload all Org Lisp files.
21011 With prefix arg UNCOMPILED, load the uncompiled versions."
21012 (interactive "P")
21013 (require 'loadhist)
21014 (let* ((org-dir (org-find-library-dir "org"))
21015 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21016 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21017 (remove-re (format "\\`%s\\'"
21018 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21019 (feats (delete-dups
21020 (mapcar 'file-name-sans-extension
21021 (mapcar 'file-name-nondirectory
21022 (delq nil
21023 (mapcar 'feature-file
21024 features))))))
21025 (lfeat (append
21026 (sort
21027 (setq feats
21028 (delq nil (mapcar
21029 (lambda (f)
21030 (if (and (string-match feature-re f)
21031 (not (string-match remove-re f)))
21032 f nil))
21033 feats)))
21034 'string-lessp)
21035 (list "org-version" "org")))
21036 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21037 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21038 load-uncore load-misses)
21039 (setq load-misses
21040 (delq 't
21041 (mapcar (lambda (f)
21042 (or (org-load-noerror-mustsuffix (concat org-dir f))
21043 (and (string= org-dir contrib-dir)
21044 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21045 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21046 (add-to-list 'load-uncore f 'append)
21049 lfeat)))
21050 (when load-uncore
21051 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21052 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21053 (if load-misses
21054 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21055 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21056 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21058 ;;;###autoload
21059 (defun org-customize ()
21060 "Call the customize function with org as argument."
21061 (interactive)
21062 (org-load-modules-maybe)
21063 (org-require-autoloaded-modules)
21064 (customize-browse 'org))
21066 (defun org-create-customize-menu ()
21067 "Create a full customization menu for Org mode, insert it into the menu."
21068 (interactive)
21069 (org-load-modules-maybe)
21070 (org-require-autoloaded-modules)
21071 (if (fboundp 'customize-menu-create)
21072 (progn
21073 (easy-menu-change
21074 '("Org") "Customize"
21075 `(["Browse Org group" org-customize t]
21076 "--"
21077 ,(customize-menu-create 'org)
21078 ["Set" Custom-set t]
21079 ["Save" Custom-save t]
21080 ["Reset to Current" Custom-reset-current t]
21081 ["Reset to Saved" Custom-reset-saved t]
21082 ["Reset to Standard Settings" Custom-reset-standard t]))
21083 (message "\"Org\"-menu now contains full customization menu"))
21084 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21086 ;;;; Miscellaneous stuff
21088 ;;; Generally useful functions
21090 (defun org-link-display-format (s)
21091 "Replace links in string S with their description.
21092 If there is no description, use the link target."
21093 (save-match-data
21094 (replace-regexp-in-string
21095 org-bracket-link-analytic-regexp
21096 (lambda (m)
21097 (if (match-end 5) (match-string 5 m)
21098 (concat (match-string 1 m) (match-string 3 m))))
21099 s nil t)))
21101 (defun org-toggle-link-display ()
21102 "Toggle the literal or descriptive display of links."
21103 (interactive)
21104 (if org-descriptive-links
21105 (progn (org-remove-from-invisibility-spec '(org-link))
21106 (org-restart-font-lock)
21107 (setq org-descriptive-links nil))
21108 (progn (add-to-invisibility-spec '(org-link))
21109 (org-restart-font-lock)
21110 (setq org-descriptive-links t))))
21112 (defun org-in-clocktable-p ()
21113 "Check if the cursor is in a clocktable."
21114 (let ((pos (point)) start)
21115 (save-excursion
21116 (end-of-line 1)
21117 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21118 (setq start (match-beginning 0))
21119 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21120 (>= (match-end 0) pos)
21121 start))))
21123 (defun org-in-verbatim-emphasis ()
21124 (save-match-data
21125 (and (org-in-regexp org-verbatim-re 2)
21126 (>= (point) (match-beginning 3))
21127 (<= (point) (match-end 4)))))
21129 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21130 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21131 (if (and marker (marker-buffer marker)
21132 (buffer-live-p (marker-buffer marker)))
21133 (progn
21134 (pop-to-buffer-same-window (marker-buffer marker))
21135 (when (or (> marker (point-max)) (< marker (point-min)))
21136 (widen))
21137 (goto-char marker)
21138 (org-show-context 'org-goto))
21139 (if bookmark
21140 (bookmark-jump bookmark)
21141 (error "Cannot find location"))))
21143 (defun org-quote-csv-field (s)
21144 "Quote field for inclusion in CSV material."
21145 (if (string-match "[\",]" s)
21146 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21149 (defun org-force-self-insert (N)
21150 "Needed to enforce self-insert under remapping."
21151 (interactive "p")
21152 (self-insert-command N))
21154 (defun org-fill-template (template alist)
21155 "Find each %key of ALIST in TEMPLATE and replace it."
21156 (let ((case-fold-search nil))
21157 (dolist (entry (sort (copy-sequence alist)
21158 (lambda (a b) (< (length (car a)) (length (car b))))))
21159 (setq template
21160 (replace-regexp-in-string
21161 (concat "%" (regexp-quote (car entry)))
21162 (or (cdr entry) "") template t t)))
21163 template))
21165 (defun org-quote-vert (s)
21166 "Replace \"|\" with \"\\vert\"."
21167 (while (string-match "|" s)
21168 (setq s (replace-match "\\vert" t t s)))
21171 (defun org-uuidgen-p (s)
21172 "Is S an ID created by UUIDGEN?"
21173 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21175 (defun org-in-src-block-p (&optional inside)
21176 "Whether point is in a code source block.
21177 When INSIDE is non-nil, don't consider we are within a src block
21178 when point is at #+BEGIN_SRC or #+END_SRC."
21179 (let ((case-fold-search t))
21180 (or (and (eq (get-char-property (point) 'src-block) t))
21181 (and (not inside)
21182 (save-match-data
21183 (save-excursion
21184 (beginning-of-line)
21185 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21187 (defun org-context ()
21188 "Return a list of contexts of the current cursor position.
21189 If several contexts apply, all are returned.
21190 Each context entry is a list with a symbol naming the context, and
21191 two positions indicating start and end of the context. Possible
21192 contexts are:
21194 :headline anywhere in a headline
21195 :headline-stars on the leading stars in a headline
21196 :todo-keyword on a TODO keyword (including DONE) in a headline
21197 :tags on the TAGS in a headline
21198 :priority on the priority cookie in a headline
21199 :item on the first line of a plain list item
21200 :item-bullet on the bullet/number of a plain list item
21201 :checkbox on the checkbox in a plain list item
21202 :table in an Org table
21203 :table-special on a special filed in a table
21204 :table-table in a table.el table
21205 :clocktable in a clocktable
21206 :src-block in a source block
21207 :link on a hyperlink
21208 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21209 :target on a <<target>>
21210 :radio-target on a <<<radio-target>>>
21211 :latex-fragment on a LaTeX fragment
21212 :latex-preview on a LaTeX fragment with overlaid preview image
21214 This function expects the position to be visible because it uses font-lock
21215 faces as a help to recognize the following contexts: :table-special, :link,
21216 and :keyword."
21217 (let* ((f (get-text-property (point) 'face))
21218 (faces (if (listp f) f (list f)))
21219 (case-fold-search t)
21220 (p (point)) clist o)
21221 ;; First the large context
21222 (cond
21223 ((org-at-heading-p t)
21224 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21225 (when (progn
21226 (beginning-of-line 1)
21227 (looking-at org-todo-line-tags-regexp))
21228 (push (org-point-in-group p 1 :headline-stars) clist)
21229 (push (org-point-in-group p 2 :todo-keyword) clist)
21230 (push (org-point-in-group p 4 :tags) clist))
21231 (goto-char p)
21232 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21233 (when (looking-at "\\[#[A-Z0-9]\\]")
21234 (push (org-point-in-group p 0 :priority) clist)))
21236 ((org-at-item-p)
21237 (push (org-point-in-group p 2 :item-bullet) clist)
21238 (push (list :item (point-at-bol)
21239 (save-excursion (org-end-of-item) (point)))
21240 clist)
21241 (and (org-at-item-checkbox-p)
21242 (push (org-point-in-group p 0 :checkbox) clist)))
21244 ((org-at-table-p)
21245 (push (list :table (org-table-begin) (org-table-end)) clist)
21246 (when (memq 'org-formula faces)
21247 (push (list :table-special
21248 (previous-single-property-change p 'face)
21249 (next-single-property-change p 'face)) clist)))
21250 ((org-at-table-p 'any)
21251 (push (list :table-table) clist)))
21252 (goto-char p)
21254 (let ((case-fold-search t))
21255 ;; New the "medium" contexts: clocktables, source blocks
21256 (cond ((org-in-clocktable-p)
21257 (push (list :clocktable
21258 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21259 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21260 (match-beginning 1))
21261 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21262 (match-end 0))) clist))
21263 ((org-in-src-block-p)
21264 (push (list :src-block
21265 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21266 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21267 (match-beginning 1))
21268 (and (search-forward "#+END_SRC" nil t)
21269 (match-beginning 0))) clist))))
21270 (goto-char p)
21272 ;; Now the small context
21273 (cond
21274 ((org-at-timestamp-p)
21275 (push (org-point-in-group p 0 :timestamp) clist))
21276 ((memq 'org-link faces)
21277 (push (list :link
21278 (previous-single-property-change p 'face)
21279 (next-single-property-change p 'face)) clist))
21280 ((memq 'org-special-keyword faces)
21281 (push (list :keyword
21282 (previous-single-property-change p 'face)
21283 (next-single-property-change p 'face)) clist))
21284 ((org-at-target-p)
21285 (push (org-point-in-group p 0 :target) clist)
21286 (goto-char (1- (match-beginning 0)))
21287 (when (looking-at org-radio-target-regexp)
21288 (push (org-point-in-group p 0 :radio-target) clist))
21289 (goto-char p))
21290 ((setq o (cl-some
21291 (lambda (o)
21292 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21294 (overlays-at (point))))
21295 (push (list :latex-fragment
21296 (overlay-start o) (overlay-end o)) clist)
21297 (push (list :latex-preview
21298 (overlay-start o) (overlay-end o)) clist))
21299 ((org-inside-LaTeX-fragment-p)
21300 ;; FIXME: positions wrong.
21301 (push (list :latex-fragment (point) (point)) clist)))
21303 (setq clist (nreverse (delq nil clist)))
21304 clist))
21306 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21307 "Non-nil when point is between matches of START-RE and END-RE.
21309 Also return a non-nil value when point is on one of the matches.
21311 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21312 buffer positions. Default values are the positions of headlines
21313 surrounding the point.
21315 The functions returns a cons cell whose car (resp. cdr) is the
21316 position before START-RE (resp. after END-RE)."
21317 (save-match-data
21318 (let ((pos (point))
21319 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21320 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21321 beg end)
21322 (save-excursion
21323 ;; Point is on a block when on START-RE or if START-RE can be
21324 ;; found before it...
21325 (and (or (org-in-regexp start-re)
21326 (re-search-backward start-re limit-up t))
21327 (setq beg (match-beginning 0))
21328 ;; ... and END-RE after it...
21329 (goto-char (match-end 0))
21330 (re-search-forward end-re limit-down t)
21331 (> (setq end (match-end 0)) pos)
21332 ;; ... without another START-RE in-between.
21333 (goto-char (match-beginning 0))
21334 (not (re-search-backward start-re (1+ beg) t))
21335 ;; Return value.
21336 (cons beg end))))))
21338 (defun org-in-block-p (names)
21339 "Non-nil when point belongs to a block whose name belongs to NAMES.
21341 NAMES is a list of strings containing names of blocks.
21343 Return first block name matched, or nil. Beware that in case of
21344 nested blocks, the returned name may not belong to the closest
21345 block from point."
21346 (save-match-data
21347 (catch 'exit
21348 (let ((case-fold-search t)
21349 (lim-up (save-excursion (outline-previous-heading)))
21350 (lim-down (save-excursion (outline-next-heading))))
21351 (dolist (name names)
21352 (let ((n (regexp-quote name)))
21353 (when (org-between-regexps-p
21354 (concat "^[ \t]*#\\+begin_" n)
21355 (concat "^[ \t]*#\\+end_" n)
21356 lim-up lim-down)
21357 (throw 'exit n)))))
21358 nil)))
21360 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21361 "Call `multi-occur' with buffers for all agenda files."
21362 (interactive "sOrg-files matching: ")
21363 (let* ((files (org-agenda-files))
21364 (tnames (mapcar #'file-truename files))
21365 (extra org-agenda-text-search-extra-files))
21366 (when (eq (car extra) 'agenda-archives)
21367 (setq extra (cdr extra))
21368 (setq files (org-add-archive-files files)))
21369 (dolist (f extra)
21370 (unless (member (file-truename f) tnames)
21371 (unless (member f files) (setq files (append files (list f))))
21372 (setq tnames (append tnames (list (file-truename f))))))
21373 (multi-occur
21374 (mapcar (lambda (x)
21375 (with-current-buffer
21376 ;; FIXME: Why not just (find-file-noselect x)?
21377 ;; Is it to avoid the "revert buffer" prompt?
21378 (or (get-file-buffer x) (find-file-noselect x))
21379 (widen)
21380 (current-buffer)))
21381 files)
21382 regexp)))
21384 (add-hook 'occur-mode-find-occurrence-hook
21385 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21387 (defun org-occur-link-in-agenda-files ()
21388 "Create a link and search for it in the agendas.
21389 The link is not stored in `org-stored-links', it is just created
21390 for the search purpose."
21391 (interactive)
21392 (let ((link (condition-case nil
21393 (org-store-link nil)
21394 (error "Unable to create a link to here"))))
21395 (org-occur-in-agenda-files (regexp-quote link))))
21397 (defun org-back-over-empty-lines ()
21398 "Move backwards over whitespace, to the beginning of the first empty line.
21399 Returns the number of empty lines passed."
21400 (let ((pos (point)))
21401 (if (cdr (assq 'heading org-blank-before-new-entry))
21402 (skip-chars-backward " \t\n\r")
21403 (unless (eobp)
21404 (forward-line -1)))
21405 (beginning-of-line 2)
21406 (goto-char (min (point) pos))
21407 (count-lines (point) pos)))
21409 (defun org-switch-to-buffer-other-window (&rest args)
21410 "Switch to buffer in a second window on the current frame.
21411 In particular, do not allow pop-up frames.
21412 Returns the newly created buffer."
21413 (org-no-popups
21414 (apply 'switch-to-buffer-other-window args)))
21416 (defun org-replace-escapes (string table)
21417 "Replace %-escapes in STRING with values in TABLE.
21418 TABLE is an association list with keys like \"%a\" and string values.
21419 The sequences in STRING may contain normal field width and padding information,
21420 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21421 so values can contain further %-escapes if they are define later in TABLE."
21422 (let ((tbl (copy-alist table))
21423 (case-fold-search nil)
21424 (pchg 0)
21425 re rpl)
21426 (dolist (e tbl)
21427 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21428 (when (and (cdr e) (string-match re (cdr e)))
21429 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21430 (safe "SREF"))
21431 (add-text-properties 0 3 (list 'sref sref) safe)
21432 (setcdr e (replace-match safe t t (cdr e)))))
21433 (while (string-match re string)
21434 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21435 (cdr e)))
21436 (setq string (replace-match rpl t t string))))
21437 (while (setq pchg (next-property-change pchg string))
21438 (let ((sref (get-text-property pchg 'sref string)))
21439 (when (and sref (string-match "SREF" string pchg))
21440 (setq string (replace-match sref t t string)))))
21441 string))
21443 ;;; TODO: Only called once, from ox-odt which should probably use
21444 ;;; org-export-inline-image-p or something.
21445 (defun org-file-image-p (file)
21446 "Return non-nil if FILE is an image."
21447 (save-match-data
21448 (string-match (image-file-name-regexp) file)))
21450 (defun org-get-cursor-date (&optional with-time)
21451 "Return the date at cursor in as a time.
21452 This works in the calendar and in the agenda, anywhere else it just
21453 returns the current time.
21454 If WITH-TIME is non-nil, returns the time of the event at point (in
21455 the agenda) or the current time of the day."
21456 (let (date day defd tp hod mod)
21457 (when with-time
21458 (setq tp (get-text-property (point) 'time))
21459 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21460 (setq hod (string-to-number (match-string 1 tp))
21461 mod (string-to-number (match-string 2 tp))))
21462 (or tp (let ((now (decode-time)))
21463 (setq hod (nth 2 now)
21464 mod (nth 1 now)))))
21465 (cond
21466 ((eq major-mode 'calendar-mode)
21467 (setq date (calendar-cursor-to-date)
21468 defd (encode-time 0 (or mod 0) (or hod 0)
21469 (nth 1 date) (nth 0 date) (nth 2 date))))
21470 ((eq major-mode 'org-agenda-mode)
21471 (setq day (get-text-property (point) 'day))
21472 (when day
21473 (setq date (calendar-gregorian-from-absolute day)
21474 defd (encode-time 0 (or mod 0) (or hod 0)
21475 (nth 1 date) (nth 0 date) (nth 2 date))))))
21476 (or defd (current-time))))
21478 (defun org-mark-subtree (&optional up)
21479 "Mark the current subtree.
21480 This puts point at the start of the current subtree, and mark at
21481 the end. If a numeric prefix UP is given, move up into the
21482 hierarchy of headlines by UP levels before marking the subtree."
21483 (interactive "P")
21484 (org-with-limited-levels
21485 (cond ((org-at-heading-p) (beginning-of-line))
21486 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21487 (t (outline-previous-visible-heading 1))))
21488 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21489 (if (called-interactively-p 'any)
21490 (call-interactively 'org-mark-element)
21491 (org-mark-element)))
21493 ;;; Indentation
21495 (defvar org-element-greater-elements)
21496 (defun org--get-expected-indentation (element contentsp)
21497 "Expected indentation column for current line, according to ELEMENT.
21498 ELEMENT is an element containing point. CONTENTSP is non-nil
21499 when indentation is to be computed according to contents of
21500 ELEMENT."
21501 (let ((type (org-element-type element))
21502 (start (org-element-property :begin element))
21503 (post-affiliated (org-element-property :post-affiliated element)))
21504 (org-with-wide-buffer
21505 (cond
21506 (contentsp
21507 (cl-case type
21508 ((diary-sexp footnote-definition) 0)
21509 ((headline inlinetask nil)
21510 (if (not org-adapt-indentation) 0
21511 (let ((level (org-current-level)))
21512 (if level (1+ level) 0))))
21513 ((item plain-list) (org-list-item-body-column post-affiliated))
21515 (goto-char start)
21516 (org-get-indentation))))
21517 ((memq type '(headline inlinetask nil))
21518 (if (org-match-line "[ \t]*$")
21519 (org--get-expected-indentation element t)
21521 ((memq type '(diary-sexp footnote-definition)) 0)
21522 ;; First paragraph of a footnote definition or an item.
21523 ;; Indent like parent.
21524 ((< (line-beginning-position) start)
21525 (org--get-expected-indentation
21526 (org-element-property :parent element) t))
21527 ;; At first line: indent according to previous sibling, if any,
21528 ;; ignoring footnote definitions and inline tasks, or parent's
21529 ;; contents.
21530 ((= (line-beginning-position) start)
21531 (catch 'exit
21532 (while t
21533 (if (= (point-min) start) (throw 'exit 0)
21534 (goto-char (1- start))
21535 (let* ((previous (org-element-at-point))
21536 (parent previous))
21537 (while (and parent (<= (org-element-property :end parent) start))
21538 (setq previous parent
21539 parent (org-element-property :parent parent)))
21540 (cond
21541 ((not previous) (throw 'exit 0))
21542 ((> (org-element-property :end previous) start)
21543 (throw 'exit (org--get-expected-indentation previous t)))
21544 ((memq (org-element-type previous)
21545 '(footnote-definition inlinetask))
21546 (setq start (org-element-property :begin previous)))
21547 (t (goto-char (org-element-property :begin previous))
21548 (throw 'exit
21549 (if (bolp) (org-get-indentation)
21550 ;; At first paragraph in an item or
21551 ;; a footnote definition.
21552 (org--get-expected-indentation
21553 (org-element-property :parent previous) t))))))))))
21554 ;; Otherwise, move to the first non-blank line above.
21556 (beginning-of-line)
21557 (let ((pos (point)))
21558 (skip-chars-backward " \r\t\n")
21559 (cond
21560 ;; Two blank lines end a footnote definition or a plain
21561 ;; list. When we indent an empty line after them, the
21562 ;; containing list or footnote definition is over, so it
21563 ;; qualifies as a previous sibling. Therefore, we indent
21564 ;; like its first line.
21565 ((and (memq type '(footnote-definition plain-list))
21566 (> (count-lines (point) pos) 2))
21567 (goto-char start)
21568 (org-get-indentation))
21569 ;; Line above is the first one of a paragraph at the
21570 ;; beginning of an item or a footnote definition. Indent
21571 ;; like parent.
21572 ((< (line-beginning-position) start)
21573 (org--get-expected-indentation
21574 (org-element-property :parent element) t))
21575 ;; Line above is the beginning of an element, i.e., point
21576 ;; was originally on the blank lines between element's start
21577 ;; and contents.
21578 ((= (line-beginning-position) post-affiliated)
21579 (org--get-expected-indentation element t))
21580 ;; POS is after contents in a greater element. Indent like
21581 ;; the beginning of the element.
21582 ((and (memq type org-element-greater-elements)
21583 (let ((cend (org-element-property :contents-end element)))
21584 (and cend (<= cend pos))))
21585 ;; As a special case, if point is at the end of a footnote
21586 ;; definition or an item, indent like the very last element
21587 ;; within. If that last element is an item, indent like
21588 ;; its contents.
21589 (if (memq type '(footnote-definition item plain-list))
21590 (let ((last (org-element-at-point)))
21591 (goto-char pos)
21592 (org--get-expected-indentation
21593 last (eq (org-element-type last) 'item)))
21594 (goto-char start)
21595 (org-get-indentation)))
21596 ;; In any other case, indent like the current line.
21597 (t (org-get-indentation)))))))))
21599 (defun org--align-node-property ()
21600 "Align node property at point.
21601 Alignment is done according to `org-property-format', which see."
21602 (when (save-excursion
21603 (beginning-of-line)
21604 (looking-at org-property-re))
21605 (replace-match
21606 (concat (match-string 4)
21607 (org-trim
21608 (format org-property-format (match-string 1) (match-string 3))))
21609 t t)))
21611 (defun org-indent-line ()
21612 "Indent line depending on context.
21614 Indentation is done according to the following rules:
21616 - Footnote definitions, diary sexps, headlines and inline tasks
21617 have to start at column 0.
21619 - On the very first line of an element, consider, in order, the
21620 next rules until one matches:
21622 1. If there's a sibling element before, ignoring footnote
21623 definitions and inline tasks, indent like its first line.
21625 2. If element has a parent, indent like its contents. More
21626 precisely, if parent is an item, indent after the
21627 description part, if any, or the bullet (see
21628 `org-list-description-max-indent'). Else, indent like
21629 parent's first line.
21631 3. Otherwise, indent relatively to current level, if
21632 `org-adapt-indentation' is non-nil, or to left margin.
21634 - On a blank line at the end of an element, indent according to
21635 the type of the element. More precisely
21637 1. If element is a plain list, an item, or a footnote
21638 definition, indent like the very last element within.
21640 2. If element is a paragraph, indent like its last non blank
21641 line.
21643 3. Otherwise, indent like its very first line.
21645 - In the code part of a source block, use language major mode
21646 to indent current line if `org-src-tab-acts-natively' is
21647 non-nil. If it is nil, do nothing.
21649 - Otherwise, indent like the first non-blank line above.
21651 The function doesn't indent an item as it could break the whole
21652 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21653 `\\[org-shiftmetaright]'.
21655 Also align node properties according to `org-property-format'."
21656 (interactive)
21657 (cond
21658 ((org-at-heading-p) 'noindent)
21660 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21661 (type (org-element-type element)))
21662 (cond ((and (memq type '(plain-list item))
21663 (= (line-beginning-position)
21664 (org-element-property :post-affiliated element)))
21665 'noindent)
21666 ((and (eq type 'latex-environment)
21667 (>= (point) (org-element-property :post-affiliated element))
21668 (< (point) (org-with-wide-buffer
21669 (goto-char (org-element-property :end element))
21670 (skip-chars-backward " \r\t\n")
21671 (line-beginning-position 2))))
21672 'noindent)
21673 ((and (eq type 'src-block)
21674 org-src-tab-acts-natively
21675 (> (line-beginning-position)
21676 (org-element-property :post-affiliated element))
21677 (< (line-beginning-position)
21678 (org-with-wide-buffer
21679 (goto-char (org-element-property :end element))
21680 (skip-chars-backward " \r\t\n")
21681 (line-beginning-position))))
21682 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21684 (let ((column (org--get-expected-indentation element nil)))
21685 ;; Preserve current column.
21686 (if (<= (current-column) (current-indentation))
21687 (indent-line-to column)
21688 (save-excursion (indent-line-to column))))
21689 ;; Align node property. Also preserve current column.
21690 (when (eq type 'node-property)
21691 (let ((column (current-column)))
21692 (org--align-node-property)
21693 (org-move-to-column column)))))))))
21695 (defun org-indent-region (start end)
21696 "Indent each non-blank line in the region.
21697 Called from a program, START and END specify the region to
21698 indent. The function will not indent contents of example blocks,
21699 verse blocks and export blocks as leading white spaces are
21700 assumed to be significant there."
21701 (interactive "r")
21702 (save-excursion
21703 (goto-char start)
21704 (skip-chars-forward " \r\t\n")
21705 (unless (eobp) (beginning-of-line))
21706 (let ((indent-to
21707 (lambda (ind pos)
21708 ;; Set IND as indentation for all lines between point and
21709 ;; POS. Blank lines are ignored. Leave point after POS
21710 ;; once done.
21711 (let ((limit (copy-marker pos)))
21712 (while (< (point) limit)
21713 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21714 (forward-line))
21715 (set-marker limit nil))))
21716 (end (copy-marker end)))
21717 (while (< (point) end)
21718 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21719 (let* ((element (org-element-at-point))
21720 (type (org-element-type element))
21721 (element-end (copy-marker (org-element-property :end element)))
21722 (ind (org--get-expected-indentation element nil)))
21723 (cond
21724 ;; Element indented as a single block. Example blocks
21725 ;; preserving indentation are a special case since the
21726 ;; "contents" must not be indented whereas the block
21727 ;; boundaries can.
21728 ((or (memq type '(export-block latex-environment))
21729 (and (eq type 'example-block)
21730 (not
21731 (or org-src-preserve-indentation
21732 (org-element-property :preserve-indent element)))))
21733 (let ((offset (- ind (org-get-indentation))))
21734 (unless (zerop offset)
21735 (indent-rigidly (org-element-property :begin element)
21736 (org-element-property :end element)
21737 offset)))
21738 (goto-char element-end))
21739 ;; Elements indented line wise. Be sure to exclude
21740 ;; example blocks (preserving indentation) and source
21741 ;; blocks from this category as they are treated
21742 ;; specially later.
21743 ((or (memq type '(paragraph table table-row))
21744 (not (or (org-element-property :contents-begin element)
21745 (memq type '(example-block src-block)))))
21746 (when (eq type 'node-property)
21747 (org--align-node-property)
21748 (beginning-of-line))
21749 (funcall indent-to ind (min element-end end)))
21750 ;; Elements consisting of three parts: before the
21751 ;; contents, the contents, and after the contents. The
21752 ;; contents are treated specially, according to the
21753 ;; element type, or not indented at all. Other parts are
21754 ;; indented as a single block.
21756 (let* ((post (copy-marker
21757 (org-element-property :post-affiliated element)))
21758 (cbeg
21759 (copy-marker
21760 (cond
21761 ((not (org-element-property :contents-begin element))
21762 ;; Fake contents for source blocks.
21763 (org-with-wide-buffer
21764 (goto-char post)
21765 (line-beginning-position 2)))
21766 ((memq type '(footnote-definition item plain-list))
21767 ;; Contents in these elements could start on
21768 ;; the same line as the beginning of the
21769 ;; element. Make sure we start indenting
21770 ;; from the second line.
21771 (org-with-wide-buffer
21772 (goto-char post)
21773 (end-of-line)
21774 (skip-chars-forward " \r\t\n")
21775 (if (eobp) (point) (line-beginning-position))))
21776 (t (org-element-property :contents-begin element)))))
21777 (cend (copy-marker
21778 (or (org-element-property :contents-end element)
21779 ;; Fake contents for source blocks.
21780 (org-with-wide-buffer
21781 (goto-char element-end)
21782 (skip-chars-backward " \r\t\n")
21783 (line-beginning-position)))
21784 t)))
21785 ;; Do not change items indentation individually as it
21786 ;; might break the list as a whole. On the other
21787 ;; hand, when at a plain list, indent it as a whole.
21788 (cond ((eq type 'plain-list)
21789 (let ((offset (- ind (org-get-indentation))))
21790 (unless (zerop offset)
21791 (indent-rigidly (org-element-property :begin element)
21792 (org-element-property :end element)
21793 offset))
21794 (goto-char cbeg)))
21795 ((eq type 'item) (goto-char cbeg))
21796 (t (funcall indent-to ind (min cbeg end))))
21797 (when (< (point) end)
21798 (cl-case type
21799 ((example-block verse-block))
21800 (src-block
21801 ;; In a source block, indent source code
21802 ;; according to language major mode, but only if
21803 ;; `org-src-tab-acts-natively' is non-nil.
21804 (when (and (< (point) end) org-src-tab-acts-natively)
21805 (ignore-errors
21806 (org-babel-do-in-edit-buffer
21807 (indent-region (point-min) (point-max))))))
21808 (t (org-indent-region (point) (min cend end))))
21809 (goto-char (min cend end))
21810 (when (< (point) end)
21811 (funcall indent-to ind (min element-end end))))
21812 (set-marker post nil)
21813 (set-marker cbeg nil)
21814 (set-marker cend nil))))
21815 (set-marker element-end nil))))
21816 (set-marker end nil))))
21818 (defun org-indent-drawer ()
21819 "Indent the drawer at point."
21820 (interactive)
21821 (unless (save-excursion
21822 (beginning-of-line)
21823 (looking-at-p org-drawer-regexp))
21824 (user-error "Not at a drawer"))
21825 (let ((element (org-element-at-point)))
21826 (unless (memq (org-element-type element) '(drawer property-drawer))
21827 (user-error "Not at a drawer"))
21828 (org-with-wide-buffer
21829 (org-indent-region (org-element-property :begin element)
21830 (org-element-property :end element))))
21831 (message "Drawer at point indented"))
21833 (defun org-indent-block ()
21834 "Indent the block at point."
21835 (interactive)
21836 (unless (save-excursion
21837 (beginning-of-line)
21838 (let ((case-fold-search t))
21839 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21840 (user-error "Not at a block"))
21841 (let ((element (org-element-at-point)))
21842 (unless (memq (org-element-type element)
21843 '(comment-block center-block dynamic-block example-block
21844 export-block quote-block special-block
21845 src-block verse-block))
21846 (user-error "Not at a block"))
21847 (org-with-wide-buffer
21848 (org-indent-region (org-element-property :begin element)
21849 (org-element-property :end element))))
21850 (message "Block at point indented"))
21853 ;;; Filling
21855 ;; We use our own fill-paragraph and auto-fill functions.
21857 ;; `org-fill-paragraph' relies on adaptive filling and context
21858 ;; checking. Appropriate `fill-prefix' is computed with
21859 ;; `org-adaptive-fill-function'.
21861 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21862 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21863 ;; `org-adaptive-fill-function' value. Internally,
21864 ;; `org-comment-line-break-function' breaks the line.
21866 ;; `org-setup-filling' installs filling and auto-filling related
21867 ;; variables during `org-mode' initialization.
21869 (defun org-setup-filling ()
21870 (require 'org-element)
21871 ;; Prevent auto-fill from inserting unwanted new items.
21872 (when (boundp 'fill-nobreak-predicate)
21873 (setq-local
21874 fill-nobreak-predicate
21875 (org-uniquify
21876 (append fill-nobreak-predicate
21877 '(org-fill-line-break-nobreak-p
21878 org-fill-n-macro-as-item-nobreak-p
21879 org-fill-paragraph-with-timestamp-nobreak-p)))))
21880 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21881 (setq-local paragraph-start paragraph-ending)
21882 (setq-local paragraph-separate paragraph-ending))
21883 (setq-local fill-paragraph-function 'org-fill-paragraph)
21884 (setq-local auto-fill-inhibit-regexp nil)
21885 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21886 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21887 (setq-local comment-line-break-function 'org-comment-line-break-function))
21889 (defun org-fill-line-break-nobreak-p ()
21890 "Non-nil when a new line at point would create an Org line break."
21891 (save-excursion
21892 (skip-chars-backward "[ \t]")
21893 (skip-chars-backward "\\\\")
21894 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21896 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21897 "Non-nil when a new line at point would split a timestamp."
21898 (and (org-at-timestamp-p 'lax)
21899 (not (looking-at org-ts-regexp-both))))
21901 (defun org-fill-n-macro-as-item-nobreak-p ()
21902 "Non-nil when a new line at point would create a new list."
21903 ;; During export, a "n" macro followed by a dot or a closing
21904 ;; parenthesis can end up being parsed as a new list item.
21905 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21907 (defvar orgtbl-line-start-regexp) ; From org-table.el
21908 (defun org-adaptive-fill-function ()
21909 "Compute a fill prefix for the current line.
21910 Return fill prefix, as a string, or nil if current line isn't
21911 meant to be filled. For convenience, if `adaptive-fill-regexp'
21912 matches in paragraphs or comments, use it."
21913 (org-with-wide-buffer
21914 (unless (org-at-heading-p)
21915 (let* ((p (line-beginning-position))
21916 (element (save-excursion
21917 (beginning-of-line)
21918 (org-element-at-point)))
21919 (type (org-element-type element))
21920 (post-affiliated (org-element-property :post-affiliated element)))
21921 (unless (< p post-affiliated)
21922 (cl-case type
21923 (comment
21924 (save-excursion
21925 (beginning-of-line)
21926 (looking-at "[ \t]*")
21927 (concat (match-string 0) "# ")))
21928 (footnote-definition "")
21929 ((item plain-list)
21930 (make-string (org-list-item-body-column post-affiliated) ?\s))
21931 (paragraph
21932 ;; Fill prefix is usually the same as the current line,
21933 ;; unless the paragraph is at the beginning of an item.
21934 (let ((parent (org-element-property :parent element)))
21935 (save-excursion
21936 (beginning-of-line)
21937 (cond ((eq (org-element-type parent) 'item)
21938 (make-string (org-list-item-body-column
21939 (org-element-property :begin parent))
21940 ?\s))
21941 ((and adaptive-fill-regexp
21942 ;; Locally disable
21943 ;; `adaptive-fill-function' to let
21944 ;; `fill-context-prefix' handle
21945 ;; `adaptive-fill-regexp' variable.
21946 (let (adaptive-fill-function)
21947 (fill-context-prefix
21948 post-affiliated
21949 (org-element-property :end element)))))
21950 ((looking-at "[ \t]+") (match-string 0))
21951 (t "")))))
21952 (comment-block
21953 ;; Only fill contents if P is within block boundaries.
21954 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21955 (forward-line)
21956 (point)))
21957 (cend (save-excursion
21958 (goto-char (org-element-property :end element))
21959 (skip-chars-backward " \r\t\n")
21960 (line-beginning-position))))
21961 (when (and (>= p cbeg) (< p cend))
21962 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21963 (match-string 0)
21964 ""))))))))))
21966 (defun org-fill-element (&optional justify)
21967 "Fill element at point, when applicable.
21969 This function only applies to comment blocks, comments, example
21970 blocks and paragraphs. Also, as a special case, re-align table
21971 when point is at one.
21973 If JUSTIFY is non-nil (interactively, with prefix argument),
21974 justify as well. If `sentence-end-double-space' is non-nil, then
21975 period followed by one space does not end a sentence, so don't
21976 break a line there. The variable `fill-column' controls the
21977 width for filling.
21979 For convenience, when point is at a plain list, an item or
21980 a footnote definition, try to fill the first paragraph within."
21981 (with-syntax-table org-mode-transpose-word-syntax-table
21982 ;; Move to end of line in order to get the first paragraph within
21983 ;; a plain list or a footnote definition.
21984 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21985 ;; First check if point is in a blank line at the beginning of
21986 ;; the buffer. In that case, ignore filling.
21987 (cl-case (org-element-type element)
21988 ;; Use major mode filling function is src blocks.
21989 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21990 ;; Align Org tables, leave table.el tables as-is.
21991 (table-row (org-table-align) t)
21992 (table
21993 (when (eq (org-element-property :type element) 'org)
21994 (save-excursion
21995 (goto-char (org-element-property :post-affiliated element))
21996 (org-table-align)))
21998 (paragraph
21999 ;; Paragraphs may contain `line-break' type objects.
22000 (let ((beg (max (point-min)
22001 (org-element-property :contents-begin element)))
22002 (end (min (point-max)
22003 (org-element-property :contents-end element))))
22004 ;; Do nothing if point is at an affiliated keyword.
22005 (if (< (line-end-position) beg) t
22006 ;; Fill paragraph, taking line breaks into account.
22007 (save-excursion
22008 (goto-char beg)
22009 (let ((cuts (list beg)))
22010 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22011 (when (eq 'line-break
22012 (org-element-type
22013 (save-excursion (backward-char)
22014 (org-element-context))))
22015 (push (point) cuts)))
22016 (dolist (c (delq end cuts))
22017 (fill-region-as-paragraph c end justify)
22018 (setq end c))))
22019 t)))
22020 ;; Contents of `comment-block' type elements should be
22021 ;; filled as plain text, but only if point is within block
22022 ;; markers.
22023 (comment-block
22024 (let* ((case-fold-search t)
22025 (beg (save-excursion
22026 (goto-char (org-element-property :begin element))
22027 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22028 (forward-line)
22029 (point)))
22030 (end (save-excursion
22031 (goto-char (org-element-property :end element))
22032 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22033 (line-beginning-position))))
22034 (if (or (< (point) beg) (> (point) end)) t
22035 (fill-region-as-paragraph
22036 (save-excursion (end-of-line)
22037 (re-search-backward "^[ \t]*$" beg 'move)
22038 (line-beginning-position))
22039 (save-excursion (beginning-of-line)
22040 (re-search-forward "^[ \t]*$" end 'move)
22041 (line-beginning-position))
22042 justify))))
22043 ;; Fill comments.
22044 (comment
22045 (let ((begin (org-element-property :post-affiliated element))
22046 (end (org-element-property :end element)))
22047 (when (and (>= (point) begin) (<= (point) end))
22048 (let ((begin (save-excursion
22049 (end-of-line)
22050 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22051 (progn (forward-line) (point))
22052 begin)))
22053 (end (save-excursion
22054 (end-of-line)
22055 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22056 (1- (line-beginning-position))
22057 (skip-chars-backward " \r\t\n")
22058 (line-end-position)))))
22059 ;; Do not fill comments when at a blank line.
22060 (when (> end begin)
22061 (let ((fill-prefix
22062 (save-excursion
22063 (beginning-of-line)
22064 (looking-at "[ \t]*#")
22065 (let ((comment-prefix (match-string 0)))
22066 (goto-char (match-end 0))
22067 (if (looking-at adaptive-fill-regexp)
22068 (concat comment-prefix (match-string 0))
22069 (concat comment-prefix " "))))))
22070 (save-excursion
22071 (fill-region-as-paragraph begin end justify))))))
22073 ;; Ignore every other element.
22074 (otherwise t)))))
22076 (defun org-fill-paragraph (&optional justify region)
22077 "Fill element at point, when applicable.
22079 This function only applies to comment blocks, comments, example
22080 blocks and paragraphs. Also, as a special case, re-align table
22081 when point is at one.
22083 For convenience, when point is at a plain list, an item or
22084 a footnote definition, try to fill the first paragraph within.
22086 If JUSTIFY is non-nil (interactively, with prefix argument),
22087 justify as well. If `sentence-end-double-space' is non-nil, then
22088 period followed by one space does not end a sentence, so don't
22089 break a line there. The variable `fill-column' controls the
22090 width for filling.
22092 The REGION argument is non-nil if called interactively; in that
22093 case, if Transient Mark mode is enabled and the mark is active,
22094 fill each of the elements in the active region, instead of just
22095 filling the current element."
22096 (interactive (progn
22097 (barf-if-buffer-read-only)
22098 (list (if current-prefix-arg 'full) t)))
22099 (cond
22100 ((and region transient-mark-mode mark-active
22101 (not (eq (region-beginning) (region-end))))
22102 (let ((origin (point-marker))
22103 (start (region-beginning)))
22104 (unwind-protect
22105 (progn
22106 (goto-char (region-end))
22107 (while (> (point) start)
22108 (org-backward-paragraph)
22109 (org-fill-element justify)))
22110 (goto-char origin)
22111 (set-marker origin nil))))
22112 (t (org-fill-element justify))))
22114 (defun org-auto-fill-function ()
22115 "Auto-fill function."
22116 ;; Check if auto-filling is meaningful.
22117 (let ((fc (current-fill-column)))
22118 (when (and fc (> (current-column) fc))
22119 (let* ((fill-prefix (org-adaptive-fill-function))
22120 ;; Enforce empty fill prefix, if required. Otherwise, it
22121 ;; will be computed again.
22122 (adaptive-fill-mode (not (equal fill-prefix ""))))
22123 (when fill-prefix (do-auto-fill))))))
22125 (defun org-comment-line-break-function (&optional soft)
22126 "Break line at point and indent, continuing comment if within one.
22127 The inserted newline is marked hard if variable
22128 `use-hard-newlines' is true, unless optional argument SOFT is
22129 non-nil."
22130 (if soft (insert-and-inherit ?\n) (newline 1))
22131 (save-excursion (forward-char -1) (delete-horizontal-space))
22132 (delete-horizontal-space)
22133 (indent-to-left-margin)
22134 (insert-before-markers-and-inherit fill-prefix))
22137 ;;; Fixed Width Areas
22139 (defun org-toggle-fixed-width ()
22140 "Toggle fixed-width markup.
22142 Add or remove fixed-width markup on current line, whenever it
22143 makes sense. Return an error otherwise.
22145 If a region is active and if it contains only fixed-width areas
22146 or blank lines, remove all fixed-width markup in it. If the
22147 region contains anything else, convert all non-fixed-width lines
22148 to fixed-width ones.
22150 Blank lines at the end of the region are ignored unless the
22151 region only contains such lines."
22152 (interactive)
22153 (if (not (org-region-active-p))
22154 ;; No region:
22156 ;; Remove fixed width marker only in a fixed-with element.
22158 ;; Add fixed width maker in paragraphs, in blank lines after
22159 ;; elements or at the beginning of a headline or an inlinetask,
22160 ;; and before any one-line elements (e.g., a clock).
22161 (progn
22162 (beginning-of-line)
22163 (let* ((element (org-element-at-point))
22164 (type (org-element-type element)))
22165 (cond
22166 ((and (eq type 'fixed-width)
22167 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22168 (replace-match
22169 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22170 ((and (memq type '(babel-call clock comment diary-sexp headline
22171 horizontal-rule keyword paragraph
22172 planning))
22173 (<= (org-element-property :post-affiliated element) (point)))
22174 (skip-chars-forward " \t")
22175 (insert ": "))
22176 ((and (looking-at-p "[ \t]*$")
22177 (or (eq type 'inlinetask)
22178 (save-excursion
22179 (skip-chars-forward " \r\t\n")
22180 (<= (org-element-property :end element) (point)))))
22181 (delete-region (point) (line-end-position))
22182 (org-indent-line)
22183 (insert ": "))
22184 (t (user-error "Cannot insert a fixed-width line here")))))
22185 ;; Region active.
22186 (let* ((begin (save-excursion
22187 (goto-char (region-beginning))
22188 (line-beginning-position)))
22189 (end (copy-marker
22190 (save-excursion
22191 (goto-char (region-end))
22192 (unless (eolp) (beginning-of-line))
22193 (if (save-excursion (re-search-backward "\\S-" begin t))
22194 (progn (skip-chars-backward " \r\t\n") (point))
22195 (point)))))
22196 (all-fixed-width-p
22197 (catch 'not-all-p
22198 (save-excursion
22199 (goto-char begin)
22200 (skip-chars-forward " \r\t\n")
22201 (when (eobp) (throw 'not-all-p nil))
22202 (while (< (point) end)
22203 (let ((element (org-element-at-point)))
22204 (if (eq (org-element-type element) 'fixed-width)
22205 (goto-char (org-element-property :end element))
22206 (throw 'not-all-p nil))))
22207 t))))
22208 (if all-fixed-width-p
22209 (save-excursion
22210 (goto-char begin)
22211 (while (< (point) end)
22212 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22213 (replace-match
22214 "" nil nil nil
22215 (if (= (line-end-position) (match-end 0)) 0 1)))
22216 (forward-line)))
22217 (let ((min-ind (point-max)))
22218 ;; Find minimum indentation across all lines.
22219 (save-excursion
22220 (goto-char begin)
22221 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22222 (setq min-ind 0)
22223 (catch 'zerop
22224 (while (< (point) end)
22225 (unless (looking-at-p "[ \t]*$")
22226 (let ((ind (org-get-indentation)))
22227 (setq min-ind (min min-ind ind))
22228 (when (zerop ind) (throw 'zerop t))))
22229 (forward-line)))))
22230 ;; Loop over all lines and add fixed-width markup everywhere
22231 ;; but in fixed-width lines.
22232 (save-excursion
22233 (goto-char begin)
22234 (while (< (point) end)
22235 (cond
22236 ((org-at-heading-p)
22237 (insert ": ")
22238 (forward-line)
22239 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22240 (insert ":")
22241 (forward-line)))
22242 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22243 (let* ((element (org-element-at-point))
22244 (element-end (org-element-property :end element)))
22245 (if (eq (org-element-type element) 'fixed-width)
22246 (progn (goto-char element-end)
22247 (skip-chars-backward " \r\t\n")
22248 (forward-line))
22249 (let ((limit (min end element-end)))
22250 (while (< (point) limit)
22251 (org-move-to-column min-ind t)
22252 (insert ": ")
22253 (forward-line))))))
22255 (org-move-to-column min-ind t)
22256 (insert ": ")
22257 (forward-line)))))))
22258 (set-marker end nil))))
22261 ;;; Blocks
22263 (defun org-block-map (function &optional start end)
22264 "Call FUNCTION at the head of all source blocks in the current buffer.
22265 Optional arguments START and END can be used to limit the range."
22266 (let ((start (or start (point-min)))
22267 (end (or end (point-max))))
22268 (save-excursion
22269 (goto-char start)
22270 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22271 (save-excursion
22272 (save-match-data
22273 (goto-char (match-beginning 0))
22274 (funcall function)))))))
22276 (defun org-next-block (arg &optional backward block-regexp)
22277 "Jump to the next block.
22279 With a prefix argument ARG, jump forward ARG many blocks.
22281 When BACKWARD is non-nil, jump to the previous block.
22283 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22284 Match data is set according to this regexp when the function
22285 returns.
22287 Return point at beginning of the opening line of found block.
22288 Throw an error if no block is found."
22289 (interactive "p")
22290 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22291 (case-fold-search t)
22292 (search-fn (if backward #'re-search-backward #'re-search-forward))
22293 (count (or arg 1))
22294 (origin (point))
22295 last-element)
22296 (if backward (beginning-of-line) (end-of-line))
22297 (while (and (> count 0) (funcall search-fn re nil t))
22298 (let ((element (save-excursion
22299 (goto-char (match-beginning 0))
22300 (save-match-data (org-element-at-point)))))
22301 (when (and (memq (org-element-type element)
22302 '(center-block comment-block dynamic-block
22303 example-block export-block quote-block
22304 special-block src-block verse-block))
22305 (<= (match-beginning 0)
22306 (org-element-property :post-affiliated element)))
22307 (setq last-element element)
22308 (cl-decf count))))
22309 (if (= count 0)
22310 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22311 (save-match-data (org-show-context)))
22312 (goto-char origin)
22313 (user-error "No %s code blocks" (if backward "previous" "further")))))
22315 (defun org-previous-block (arg &optional block-regexp)
22316 "Jump to the previous block.
22317 With a prefix argument ARG, jump backward ARG many source blocks.
22318 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22319 (interactive "p")
22320 (org-next-block arg t block-regexp))
22323 ;;; Comments
22325 ;; Org comments syntax is quite complex. It requires the entire line
22326 ;; to be just a comment. Also, even with the right syntax at the
22327 ;; beginning of line, some elements (e.g., verse-block or
22328 ;; example-block) don't accept comments. Usual Emacs comment commands
22329 ;; cannot cope with those requirements. Therefore, Org replaces them.
22331 ;; Org still relies on `comment-dwim', but cannot trust
22332 ;; `comment-only-p'. So, `comment-region-function' and
22333 ;; `uncomment-region-function' both point
22334 ;; to`org-comment-or-uncomment-region'. Eventually,
22335 ;; `org-insert-comment' takes care of insertion of comments at the
22336 ;; beginning of line.
22338 ;; `org-setup-comments-handling' install comments related variables
22339 ;; during `org-mode' initialization.
22341 (defun org-setup-comments-handling ()
22342 (interactive)
22343 (setq-local comment-use-syntax nil)
22344 (setq-local comment-start "# ")
22345 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22346 (setq-local comment-insert-comment-function 'org-insert-comment)
22347 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22348 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22350 (defun org-insert-comment ()
22351 "Insert an empty comment above current line.
22352 If the line is empty, insert comment at its beginning. When
22353 point is within a source block, comment according to the related
22354 major mode."
22355 (if (let ((element (org-element-at-point)))
22356 (and (eq (org-element-type element) 'src-block)
22357 (< (save-excursion
22358 (goto-char (org-element-property :post-affiliated element))
22359 (line-end-position))
22360 (point))
22361 (> (save-excursion
22362 (goto-char (org-element-property :end element))
22363 (skip-chars-backward " \r\t\n")
22364 (line-beginning-position))
22365 (point))))
22366 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22367 (beginning-of-line)
22368 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22369 (open-line 1))
22370 (org-indent-line)
22371 (insert "# ")))
22373 (defvar comment-empty-lines) ; From newcomment.el.
22374 (defun org-comment-or-uncomment-region (beg end &rest _)
22375 "Comment or uncomment each non-blank line in the region.
22376 Uncomment each non-blank line between BEG and END if it only
22377 contains commented lines. Otherwise, comment them. If region is
22378 strictly within a source block, use appropriate comment syntax."
22379 (if (let ((element (org-element-at-point)))
22380 (and (eq (org-element-type element) 'src-block)
22381 (< (save-excursion
22382 (goto-char (org-element-property :post-affiliated element))
22383 (line-end-position))
22384 beg)
22385 (>= (save-excursion
22386 (goto-char (org-element-property :end element))
22387 (skip-chars-backward " \r\t\n")
22388 (line-beginning-position))
22389 end)))
22390 ;; Translate region boundaries for the Org buffer to the source
22391 ;; buffer.
22392 (let ((offset (- end beg)))
22393 (save-excursion
22394 (goto-char beg)
22395 (org-babel-do-in-edit-buffer
22396 (comment-or-uncomment-region (point) (+ offset (point))))))
22397 (save-restriction
22398 ;; Restrict region
22399 (narrow-to-region (save-excursion (goto-char beg)
22400 (skip-chars-forward " \r\t\n" end)
22401 (line-beginning-position))
22402 (save-excursion (goto-char end)
22403 (skip-chars-backward " \r\t\n" beg)
22404 (line-end-position)))
22405 (let ((uncommentp
22406 ;; UNCOMMENTP is non-nil when every non blank line between
22407 ;; BEG and END is a comment.
22408 (save-excursion
22409 (goto-char (point-min))
22410 (while (and (not (eobp))
22411 (let ((element (org-element-at-point)))
22412 (and (eq (org-element-type element) 'comment)
22413 (goto-char (min (point-max)
22414 (org-element-property
22415 :end element)))))))
22416 (eobp))))
22417 (if uncommentp
22418 ;; Only blank lines and comments in region: uncomment it.
22419 (save-excursion
22420 (goto-char (point-min))
22421 (while (not (eobp))
22422 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22423 (replace-match "" nil nil nil 1))
22424 (forward-line)))
22425 ;; Comment each line in region.
22426 (let ((min-indent (point-max)))
22427 ;; First find the minimum indentation across all lines.
22428 (save-excursion
22429 (goto-char (point-min))
22430 (while (and (not (eobp)) (not (zerop min-indent)))
22431 (unless (looking-at "[ \t]*$")
22432 (setq min-indent (min min-indent (current-indentation))))
22433 (forward-line)))
22434 ;; Then loop over all lines.
22435 (save-excursion
22436 (goto-char (point-min))
22437 (while (not (eobp))
22438 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22439 ;; Don't get fooled by invisible text (e.g. link path)
22440 ;; when moving to column MIN-INDENT.
22441 (let ((buffer-invisibility-spec nil))
22442 (org-move-to-column min-indent t))
22443 (insert comment-start))
22444 (forward-line)))))))))
22446 (defun org-comment-dwim (_arg)
22447 "Call the comment command you mean.
22448 Call `org-toggle-comment' if on a heading, otherwise call
22449 `comment-dwim', within a source edit buffer if needed."
22450 (interactive "*P")
22451 (cond ((org-at-heading-p)
22452 (call-interactively #'org-toggle-comment))
22453 ((org-in-src-block-p)
22454 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22455 (t (call-interactively #'comment-dwim))))
22458 ;;; Timestamps API
22460 ;; This section contains tools to operate on, or create, timestamp
22461 ;; objects, as returned by, e.g. `org-element-context'.
22463 (defun org-timestamp-from-string (s)
22464 "Convert Org timestamp S, as a string, into a timestamp object.
22465 Return nil if S is not a valid timestamp string."
22466 (when (org-string-nw-p s)
22467 (with-temp-buffer
22468 (save-excursion (insert s))
22469 (org-element-timestamp-parser))))
22471 (defun org-timestamp-from-time (time &optional with-time inactive)
22472 "Convert a time value into a timestamp object.
22474 TIME is an Emacs internal time representation, as returned, e.g.,
22475 by `current-time'.
22477 When optional argument WITH-TIME is non-nil, return a timestamp
22478 object with a time part, i.e., with hours and minutes.
22480 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22481 return an active timestamp."
22482 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22483 (org-element-create 'timestamp
22484 (list :type (if inactive 'inactive 'active)
22485 :year-start year
22486 :month-start month
22487 :day-start day
22488 :hour-start (and with-time hour)
22489 :minute-start (and with-time minute)))))
22491 (defun org-timestamp-to-time (timestamp &optional end)
22492 "Convert TIMESTAMP object into an Emacs internal time value.
22493 Use end of date range or time range when END is non-nil.
22494 Otherwise, use its start."
22495 (apply #'encode-time
22496 (cons 0
22497 (mapcar
22498 (lambda (prop) (or (org-element-property prop timestamp) 0))
22499 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22500 '(:minute-start :hour-start :day-start :month-start
22501 :year-start))))))
22503 (defun org-timestamp-has-time-p (timestamp)
22504 "Non-nil when TIMESTAMP has a time specified."
22505 (org-element-property :hour-start timestamp))
22507 (defun org-timestamp-format (timestamp format &optional end utc)
22508 "Format a TIMESTAMP object into a string.
22510 FORMAT is a format specifier to be passed to
22511 `format-time-string'.
22513 When optional argument END is non-nil, use end of date-range or
22514 time-range, if possible.
22516 When optional argument UTC is non-nil, time is be expressed as
22517 Universal Time."
22518 (format-time-string format (org-timestamp-to-time timestamp end)
22519 (and utc t)))
22521 (defun org-timestamp-split-range (timestamp &optional end)
22522 "Extract a TIMESTAMP object from a date or time range.
22524 END, when non-nil, means extract the end of the range.
22525 Otherwise, extract its start.
22527 Return a new timestamp object."
22528 (let ((type (org-element-property :type timestamp)))
22529 (if (memq type '(active inactive diary)) timestamp
22530 (let ((split-ts (org-element-copy timestamp)))
22531 ;; Set new type.
22532 (org-element-put-property
22533 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22534 ;; Copy start properties over end properties if END is
22535 ;; non-nil. Otherwise, copy end properties over `start' ones.
22536 (let ((p-alist '((:minute-start . :minute-end)
22537 (:hour-start . :hour-end)
22538 (:day-start . :day-end)
22539 (:month-start . :month-end)
22540 (:year-start . :year-end))))
22541 (dolist (p-cell p-alist)
22542 (org-element-put-property
22543 split-ts
22544 (funcall (if end #'car #'cdr) p-cell)
22545 (org-element-property
22546 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22547 ;; Eventually refresh `:raw-value'.
22548 (org-element-put-property split-ts :raw-value nil)
22549 (org-element-put-property
22550 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22552 (defun org-timestamp-translate (timestamp &optional boundary)
22553 "Translate TIMESTAMP object to custom format.
22555 Format string is defined in `org-time-stamp-custom-formats',
22556 which see.
22558 When optional argument BOUNDARY is non-nil, it is either the
22559 symbol `start' or `end'. In this case, only translate the
22560 starting or ending part of TIMESTAMP if it is a date or time
22561 range. Otherwise, translate both parts.
22563 Return timestamp as-is if `org-display-custom-times' is nil or if
22564 it has a `diary' type."
22565 (let ((type (org-element-property :type timestamp)))
22566 (if (or (not org-display-custom-times) (eq type 'diary))
22567 (org-element-interpret-data timestamp)
22568 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22569 org-time-stamp-custom-formats)))
22570 (if (and (not boundary) (memq type '(active-range inactive-range)))
22571 (concat (org-timestamp-format timestamp fmt)
22572 "--"
22573 (org-timestamp-format timestamp fmt t))
22574 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22576 ;;; Other stuff
22578 (defvar reftex-docstruct-symbol)
22579 (defvar org--rds)
22581 (defun org-reftex-citation ()
22582 "Use reftex-citation to insert a citation into the buffer.
22583 This looks for a line like
22585 #+BIBLIOGRAPHY: foo plain option:-d
22587 and derives from it that foo.bib is the bibliography file relevant
22588 for this document. It then installs the necessary environment for RefTeX
22589 to work in this buffer and calls `reftex-citation' to insert a citation
22590 into the buffer.
22592 Export of such citations to both LaTeX and HTML is handled by the contributed
22593 package ox-bibtex by Taru Karttunen."
22594 (interactive)
22595 (let ((reftex-docstruct-symbol 'org--rds)
22596 org--rds bib)
22597 (org-with-wide-buffer
22598 (let ((case-fold-search t)
22599 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22600 (if (not (save-excursion
22601 (or (re-search-forward re nil t)
22602 (re-search-backward re nil t))))
22603 (user-error "No bibliography defined in file")
22604 (setq bib (concat (match-string 1) ".bib")
22605 org--rds (list (list 'bib bib))))))
22606 (call-interactively 'reftex-citation)))
22608 ;;;; Functions extending outline functionality
22610 (defun org-beginning-of-line (&optional n)
22611 "Go to the beginning of the current visible line.
22613 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22614 symbol `reversed', on the first attempt move to where the
22615 headline text starts, and only move to beginning of line when the
22616 cursor is already before the start of the text of the headline.
22618 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22619 start of the text on the second attempt.
22621 With argument N not nil or 1, move forward N - 1 lines first."
22622 (interactive "^p")
22623 (let ((origin (point))
22624 (special (pcase org-special-ctrl-a/e
22625 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22626 deactivate-mark)
22627 ;; First move to a visible line.
22628 (if (bound-and-true-p visual-line-mode)
22629 (beginning-of-visual-line n)
22630 (move-beginning-of-line n)
22631 ;; `move-beginning-of-line' may leave point after invisible
22632 ;; characters if line starts with such of these (e.g., with
22633 ;; a link at column 0). Really move to the beginning of the
22634 ;; current visible line.
22635 (beginning-of-line))
22636 (cond
22637 ;; No special behavior. Point is already at the beginning of
22638 ;; a line, logical or visual.
22639 ((not special))
22640 ;; `beginning-of-visual-line' left point before logical beginning
22641 ;; of line: point is at the beginning of a visual line. Bail
22642 ;; out.
22643 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22644 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22645 ;; At a headline, special position is before the title, but
22646 ;; after any TODO keyword or priority cookie.
22647 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22648 (line-end-position)))
22649 (bol (point)))
22650 (if (eq special 'reversed)
22651 (when (and (= origin bol) (eq last-command this-command))
22652 (goto-char refpos))
22653 (when (or (> origin refpos) (= origin bol))
22654 (goto-char refpos)))))
22655 ((and (looking-at org-list-full-item-re)
22656 (memq (org-element-type (save-match-data (org-element-at-point)))
22657 '(item plain-list)))
22658 ;; Set special position at first white space character after
22659 ;; bullet, and check-box, if any.
22660 (let ((after-bullet
22661 (let ((box (match-end 3)))
22662 (cond ((not box) (match-end 1))
22663 ((eq (char-after box) ?\s) (1+ box))
22664 (t box)))))
22665 (if (eq special 'reversed)
22666 (when (and (= (point) origin) (eq last-command this-command))
22667 (goto-char after-bullet))
22668 (when (or (> origin after-bullet) (= (point) origin))
22669 (goto-char after-bullet)))))
22670 ;; No special context. Point is already at beginning of line.
22671 (t nil))))
22673 (defun org-end-of-line (&optional n)
22674 "Go to the end of the line, but before ellipsis, if any.
22676 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22677 symbol `reversed', ignore tags on the first attempt, and only
22678 move to after the tags when the cursor is already beyond the end
22679 of the headline.
22681 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22682 on the second attempt.
22684 With argument N not nil or 1, move forward N - 1 lines first."
22685 (interactive "^p")
22686 (let ((origin (point))
22687 (special (pcase org-special-ctrl-a/e
22688 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22689 deactivate-mark)
22690 ;; First move to a visible line.
22691 (if (bound-and-true-p visual-line-mode)
22692 (beginning-of-visual-line n)
22693 (move-beginning-of-line n))
22694 (cond
22695 ;; At a headline, with tags.
22696 ((and special
22697 (save-excursion
22698 (beginning-of-line)
22699 (let ((case-fold-search nil))
22700 (looking-at org-complex-heading-regexp)))
22701 (match-end 5))
22702 (let ((tags (save-excursion
22703 (goto-char (match-beginning 5))
22704 (skip-chars-backward " \t")
22705 (point)))
22706 (visual-end (and (bound-and-true-p visual-line-mode)
22707 (save-excursion
22708 (end-of-visual-line)
22709 (point)))))
22710 ;; If `end-of-visual-line' brings us before end of line or
22711 ;; even tags, i.e., the headline spans over multiple visual
22712 ;; lines, move there.
22713 (cond ((and visual-end
22714 (< visual-end tags)
22715 (<= origin visual-end))
22716 (goto-char visual-end))
22717 ((eq special 'reversed)
22718 (if (and (= origin (line-end-position))
22719 (eq this-command last-command))
22720 (goto-char tags)
22721 (end-of-line)))
22723 (if (or (< origin tags) (= origin (line-end-position)))
22724 (goto-char tags)
22725 (end-of-line))))))
22726 ((bound-and-true-p visual-line-mode)
22727 (let ((bol (line-beginning-position)))
22728 (end-of-visual-line)
22729 ;; If `end-of-visual-line' gets us past the ellipsis at the
22730 ;; end of a line, backtrack and use `end-of-line' instead.
22731 (when (/= bol (line-beginning-position))
22732 (goto-char bol)
22733 (end-of-line))))
22734 (t (end-of-line)))))
22736 (defun org-backward-sentence (&optional _arg)
22737 "Go to beginning of sentence, or beginning of table field.
22738 This will call `backward-sentence' or `org-table-beginning-of-field',
22739 depending on context."
22740 (interactive)
22741 (let* ((element (org-element-at-point))
22742 (contents-begin (org-element-property :contents-begin element))
22743 (table (org-element-lineage element '(table) t)))
22744 (if (and table
22745 (> (point) contents-begin)
22746 (<= (point) (org-element-property :contents-end table)))
22747 (call-interactively #'org-table-beginning-of-field)
22748 (save-restriction
22749 (when (and contents-begin
22750 (< (point-min) contents-begin)
22751 (> (point) contents-begin))
22752 (narrow-to-region contents-begin
22753 (org-element-property :contents-end element)))
22754 (call-interactively #'backward-sentence)))))
22756 (defun org-forward-sentence (&optional _arg)
22757 "Go to end of sentence, or end of table field.
22758 This will call `forward-sentence' or `org-table-end-of-field',
22759 depending on context."
22760 (interactive)
22761 (if (and (org-at-heading-p)
22762 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22763 (save-restriction
22764 (narrow-to-region (line-beginning-position) (line-end-position))
22765 (call-interactively #'forward-sentence))
22766 (let* ((element (org-element-at-point))
22767 (contents-end (org-element-property :contents-end element))
22768 (table (org-element-lineage element '(table) t)))
22769 (if (and table
22770 (>= (point) (org-element-property :contents-begin table))
22771 (< (point) contents-end))
22772 (call-interactively #'org-table-end-of-field)
22773 (save-restriction
22774 (when (and contents-end
22775 (> (point-max) contents-end)
22776 ;; Skip blank lines between elements.
22777 (< (org-element-property :end element)
22778 (save-excursion (goto-char contents-end)
22779 (skip-chars-forward " \r\t\n"))))
22780 (narrow-to-region (org-element-property :contents-begin element)
22781 contents-end))
22782 ;; End of heading is considered as the end of a sentence.
22783 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22784 (call-interactively #'forward-sentence)))))))
22786 (defun org-kill-line (&optional _arg)
22787 "Kill line, to tags or end of line."
22788 (interactive)
22789 (cond
22790 ((or (not org-special-ctrl-k)
22791 (bolp)
22792 (not (org-at-heading-p)))
22793 (when (and (get-char-property (line-end-position) 'invisible)
22794 org-ctrl-k-protect-subtree
22795 (or (eq org-ctrl-k-protect-subtree 'error)
22796 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22797 (user-error
22798 (substitute-command-keys
22799 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22800 (call-interactively
22801 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22802 ((looking-at org-tag-line-re)
22803 (let ((end (save-excursion
22804 (goto-char (match-beginning 1))
22805 (skip-chars-backward " \t"))))
22806 (if (<= end (point)) ;on tags part
22807 (kill-region (point) (line-end-position))
22808 (kill-region (point) end)))
22809 (org-align-tags))
22810 (t (kill-region (point) (line-end-position)))))
22812 (defun org-yank (&optional arg)
22813 "Yank. If the kill is a subtree, treat it specially.
22814 This command will look at the current kill and check if is a single
22815 subtree, or a series of subtrees[1]. If it passes the test, and if the
22816 cursor is at the beginning of a line or after the stars of a currently
22817 empty headline, then the yank is handled specially. How exactly depends
22818 on the value of the following variables.
22820 `org-yank-folded-subtrees'
22821 By default, this variable is non-nil, which results in
22822 subtree(s) being folded after insertion, except if doing so
22823 would swallow text after the yanked text.
22825 `org-yank-adjusted-subtrees'
22826 When non-nil (the default value is nil), the subtree will be
22827 promoted or demoted in order to fit into the local outline tree
22828 structure, which means that the level will be adjusted so that it
22829 becomes the smaller one of the two *visible* surrounding headings.
22831 Any prefix to this command will cause `yank' to be called directly with
22832 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22833 will just
22834 plainly yank the text as it is.
22836 \[1] The test checks if the first non-white line is a heading
22837 and if there are no other headings with fewer stars."
22838 (interactive "P")
22839 (org-yank-generic 'yank arg))
22841 (defun org-yank-generic (command arg)
22842 "Perform some yank-like command.
22844 This function implements the behavior described in the `org-yank'
22845 documentation. However, it has been generalized to work for any
22846 interactive command with similar behavior."
22848 ;; pretend to be command COMMAND
22849 (setq this-command command)
22851 (if arg
22852 (call-interactively command)
22854 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22855 (and (org-kill-is-subtree-p)
22856 (or (bolp)
22857 (and (looking-at "[ \t]*$")
22858 (string-match
22859 "\\`\\*+\\'"
22860 (buffer-substring (point-at-bol) (point)))))))
22861 swallowp)
22862 (cond
22863 ((and subtreep org-yank-folded-subtrees)
22864 (let ((beg (point))
22865 end)
22866 (if (and subtreep org-yank-adjusted-subtrees)
22867 (org-paste-subtree nil nil 'for-yank)
22868 (call-interactively command))
22870 (setq end (point))
22871 (goto-char beg)
22872 (when (and (bolp) subtreep
22873 (not (setq swallowp
22874 (org-yank-folding-would-swallow-text beg end))))
22875 (org-with-limited-levels
22876 (or (looking-at org-outline-regexp)
22877 (re-search-forward org-outline-regexp-bol end t))
22878 (while (and (< (point) end) (looking-at org-outline-regexp))
22879 (outline-hide-subtree)
22880 (org-cycle-show-empty-lines 'folded)
22881 (condition-case nil
22882 (outline-forward-same-level 1)
22883 (error (goto-char end))))))
22884 (when swallowp
22885 (message
22886 "Inserted text not folded because that would swallow text"))
22888 (goto-char end)
22889 (skip-chars-forward " \t\n\r")
22890 (beginning-of-line 1)
22891 (push-mark beg 'nomsg)))
22892 ((and subtreep org-yank-adjusted-subtrees)
22893 (let ((beg (point-at-bol)))
22894 (org-paste-subtree nil nil 'for-yank)
22895 (push-mark beg 'nomsg)))
22897 (call-interactively command))))))
22899 (defun org-yank-folding-would-swallow-text (beg end)
22900 "Would hide-subtree at BEG swallow any text after END?"
22901 (let (level)
22902 (org-with-limited-levels
22903 (save-excursion
22904 (goto-char beg)
22905 (when (or (looking-at org-outline-regexp)
22906 (re-search-forward org-outline-regexp-bol end t))
22907 (setq level (org-outline-level)))
22908 (goto-char end)
22909 (skip-chars-forward " \t\r\n\v\f")
22910 (not (or (eobp)
22911 (and (bolp) (looking-at-p org-outline-regexp)
22912 (<= (org-outline-level) level))))))))
22914 (defun org-back-to-heading (&optional invisible-ok)
22915 "Call `outline-back-to-heading', but provide a better error message."
22916 (condition-case nil
22917 (outline-back-to-heading invisible-ok)
22918 (error (error "Before first headline at position %d in buffer %s"
22919 (point) (current-buffer)))))
22921 (defun org-before-first-heading-p ()
22922 "Before first heading?"
22923 (save-excursion
22924 (end-of-line)
22925 (null (re-search-backward org-outline-regexp-bol nil t))))
22927 (defun org-at-heading-p (&optional ignored)
22928 (outline-on-heading-p t))
22930 (defun org-in-commented-heading-p (&optional no-inheritance)
22931 "Non-nil if point is under a commented heading.
22932 This function also checks ancestors of the current headline,
22933 unless optional argument NO-INHERITANCE is non-nil."
22934 (cond
22935 ((org-before-first-heading-p) nil)
22936 ((let ((headline (nth 4 (org-heading-components))))
22937 (and headline
22938 (let ((case-fold-search nil))
22939 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22940 headline)))))
22941 (no-inheritance nil)
22943 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22945 (defun org-at-comment-p nil
22946 "Is cursor in a commented line?"
22947 (save-excursion
22948 (save-match-data
22949 (beginning-of-line)
22950 (looking-at "^[ \t]*# "))))
22952 (defun org-at-drawer-p nil
22953 "Is cursor at a drawer keyword?"
22954 (save-excursion
22955 (move-beginning-of-line 1)
22956 (looking-at org-drawer-regexp)))
22958 (defun org-at-block-p nil
22959 "Is cursor at a block keyword?"
22960 (save-excursion
22961 (move-beginning-of-line 1)
22962 (looking-at org-block-regexp)))
22964 (defun org-point-at-end-of-empty-headline ()
22965 "If point is at the end of an empty headline, return t, else nil.
22966 If the heading only contains a TODO keyword, it is still still considered
22967 empty."
22968 (let ((case-fold-search nil))
22969 (and (looking-at "[ \t]*$")
22970 org-todo-line-regexp
22971 (save-excursion
22972 (beginning-of-line)
22973 (looking-at org-todo-line-regexp)
22974 (string= (match-string 3) "")))))
22976 (defun org-at-heading-or-item-p ()
22977 (or (org-at-heading-p) (org-at-item-p)))
22979 (defun org-at-target-p ()
22980 (or (org-in-regexp org-radio-target-regexp)
22981 (org-in-regexp org-target-regexp)))
22982 ;; Compatibility alias with Org versions < 7.8.03
22983 (defalias 'org-on-target-p 'org-at-target-p)
22985 (defun org-up-heading-all (arg)
22986 "Move to the heading line of which the present line is a subheading.
22987 This function considers both visible and invisible heading lines.
22988 With argument, move up ARG levels."
22989 (outline-up-heading arg t))
22991 (defun org-up-heading-safe ()
22992 "Move to the heading line of which the present line is a subheading.
22993 This version will not throw an error. It will return the level of the
22994 headline found, or nil if no higher level is found.
22996 Also, this function will be a lot faster than `outline-up-heading',
22997 because it relies on stars being the outline starters. This can really
22998 make a significant difference in outlines with very many siblings."
22999 (when (ignore-errors (org-back-to-heading t))
23000 (let ((level-up (1- (funcall outline-level))))
23001 (and (> level-up 0)
23002 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23003 (funcall outline-level)))))
23005 (defun org-first-sibling-p ()
23006 "Is this heading the first child of its parents?"
23007 (interactive)
23008 (let ((re org-outline-regexp-bol)
23009 level l)
23010 (unless (org-at-heading-p t)
23011 (user-error "Not at a heading"))
23012 (setq level (funcall outline-level))
23013 (save-excursion
23014 (if (not (re-search-backward re nil t))
23016 (setq l (funcall outline-level))
23017 (< l level)))))
23019 (defun org-goto-sibling (&optional previous)
23020 "Goto the next sibling, even if it is invisible.
23021 When PREVIOUS is set, go to the previous sibling instead. Returns t
23022 when a sibling was found. When none is found, return nil and don't
23023 move point."
23024 (let ((fun (if previous 're-search-backward 're-search-forward))
23025 (pos (point))
23026 (re org-outline-regexp-bol)
23027 level l)
23028 (when (ignore-errors (org-back-to-heading t))
23029 (setq level (funcall outline-level))
23030 (catch 'exit
23031 (or previous (forward-char 1))
23032 (while (funcall fun re nil t)
23033 (setq l (funcall outline-level))
23034 (when (< l level) (goto-char pos) (throw 'exit nil))
23035 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23036 (goto-char pos)
23037 nil))))
23039 (defun org-show-siblings ()
23040 "Show all siblings of the current headline."
23041 (save-excursion
23042 (while (org-goto-sibling) (org-flag-heading nil)))
23043 (save-excursion
23044 (while (org-goto-sibling 'previous)
23045 (org-flag-heading nil))))
23047 (defun org-goto-first-child ()
23048 "Goto the first child, even if it is invisible.
23049 Return t when a child was found. Otherwise don't move point and
23050 return nil."
23051 (let (level (pos (point)) (re org-outline-regexp-bol))
23052 (when (ignore-errors (org-back-to-heading t))
23053 (setq level (outline-level))
23054 (forward-char 1)
23055 (if (and (re-search-forward re nil t) (> (outline-level) level))
23056 (progn (goto-char (match-beginning 0)) t)
23057 (goto-char pos) nil))))
23059 (defun org-show-hidden-entry ()
23060 "Show an entry where even the heading is hidden."
23061 (save-excursion
23062 (org-show-entry)))
23064 (defun org-flag-heading (flag &optional entry)
23065 "Flag the current heading. FLAG non-nil means make invisible.
23066 When ENTRY is non-nil, show the entire entry."
23067 (save-excursion
23068 (org-back-to-heading t)
23069 ;; Check if we should show the entire entry
23070 (if (not entry)
23071 (org-flag-region
23072 (line-end-position 0) (line-end-position) flag 'outline)
23073 (org-show-entry)
23074 (save-excursion
23075 (and (outline-next-heading)
23076 (org-flag-heading nil))))))
23078 (defun org-get-next-sibling ()
23079 "Move to next heading of the same level, and return point.
23080 If there is no such heading, return nil.
23081 This is like outline-next-sibling, but invisible headings are ok."
23082 (let ((level (funcall outline-level)))
23083 (outline-next-heading)
23084 (while (and (not (eobp)) (> (funcall outline-level) level))
23085 (outline-next-heading))
23086 (unless (or (eobp) (< (funcall outline-level) level))
23087 (point))))
23089 (defun org-get-last-sibling ()
23090 "Move to previous heading of the same level, and return point.
23091 If there is no such heading, return nil."
23092 (let ((opoint (point))
23093 (level (funcall outline-level)))
23094 (outline-previous-heading)
23095 (when (and (/= (point) opoint) (outline-on-heading-p t))
23096 (while (and (> (funcall outline-level) level)
23097 (not (bobp)))
23098 (outline-previous-heading))
23099 (unless (< (funcall outline-level) level)
23100 (point)))))
23102 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23103 "Goto to the end of a subtree."
23104 ;; This contains an exact copy of the original function, but it uses
23105 ;; `org-back-to-heading', to make it work also in invisible
23106 ;; trees. And is uses an invisible-ok argument.
23107 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23108 ;; Furthermore, when used inside Org, finding the end of a large subtree
23109 ;; with many children and grandchildren etc, this can be much faster
23110 ;; than the outline version.
23111 (org-back-to-heading invisible-ok)
23112 (let ((first t)
23113 (level (funcall outline-level)))
23114 (if (and (derived-mode-p 'org-mode) (< level 1000))
23115 ;; A true heading (not a plain list item), in Org
23116 ;; This means we can easily find the end by looking
23117 ;; only for the right number of stars. Using a regexp to do
23118 ;; this is so much faster than using a Lisp loop.
23119 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23120 (forward-char 1)
23121 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23122 ;; something else, do it the slow way
23123 (while (and (not (eobp))
23124 (or first (> (funcall outline-level) level)))
23125 (setq first nil)
23126 (outline-next-heading)))
23127 (unless to-heading
23128 (when (memq (preceding-char) '(?\n ?\^M))
23129 ;; Go to end of line before heading
23130 (forward-char -1)
23131 (when (memq (preceding-char) '(?\n ?\^M))
23132 ;; leave blank line before heading
23133 (forward-char -1)))))
23134 (point))
23136 (defun org-end-of-meta-data (&optional full)
23137 "Skip planning line and properties drawer in current entry.
23138 When optional argument FULL is non-nil, also skip empty lines,
23139 clocking lines and regular drawers at the beginning of the
23140 entry."
23141 (org-back-to-heading t)
23142 (forward-line)
23143 (when (looking-at-p org-planning-line-re) (forward-line))
23144 (when (looking-at org-property-drawer-re)
23145 (goto-char (match-end 0))
23146 (forward-line))
23147 (when (and full (not (org-at-heading-p)))
23148 (catch 'exit
23149 (let ((end (save-excursion (outline-next-heading) (point)))
23150 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23151 (while (not (eobp))
23152 (cond ((looking-at-p org-drawer-regexp)
23153 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23154 (forward-line)
23155 (throw 'exit t)))
23156 ((looking-at-p re) (forward-line))
23157 (t (throw 'exit t))))))))
23159 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23160 "Move forward to the ARG'th subheading at same level as this one.
23161 Stop at the first and last subheadings of a superior heading.
23162 Normally this only looks at visible headings, but when INVISIBLE-OK is
23163 non-nil it will also look at invisible ones."
23164 (interactive "p")
23165 (let ((backward? (and arg (< arg 0))))
23166 (if (org-before-first-heading-p)
23167 (if backward? (goto-char (point-min)) (outline-next-heading))
23168 (org-back-to-heading invisible-ok)
23169 (unless backward? (end-of-line)) ;do not match current headline
23170 (let ((level (- (match-end 0) (match-beginning 0) 1))
23171 (f (if backward? #'re-search-backward #'re-search-forward))
23172 (count (if arg (abs arg) 1))
23173 (result (point)))
23174 (while (and (> count 0)
23175 (funcall f org-outline-regexp-bol nil 'move))
23176 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23177 (cond ((< l level) (setq count 0))
23178 ((and (= l level)
23179 (or invisible-ok
23180 (not (org-invisible-p
23181 (line-beginning-position)))))
23182 (cl-decf count)
23183 (when (= l level) (setq result (point)))))))
23184 (goto-char result))
23185 (beginning-of-line))))
23187 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23188 "Move backward to the ARG'th subheading at same level as this one.
23189 Stop at the first and last subheadings of a superior heading."
23190 (interactive "p")
23191 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23193 (defun org-next-visible-heading (arg)
23194 "Move to the next visible heading.
23196 This function wraps `outline-next-visible-heading' with
23197 `org-with-limited-levels' in order to skip over inline tasks and
23198 respect customization of `org-odd-levels-only'."
23199 (interactive "p")
23200 (org-with-limited-levels
23201 (outline-next-visible-heading arg)))
23203 (defun org-previous-visible-heading (arg)
23204 "Move to the previous visible heading.
23206 This function wraps `outline-previous-visible-heading' with
23207 `org-with-limited-levels' in order to skip over inline tasks and
23208 respect customization of `org-odd-levels-only'."
23209 (interactive "p")
23210 (org-with-limited-levels
23211 (outline-previous-visible-heading arg)))
23213 (defun org-forward-paragraph ()
23214 "Move forward to beginning of next paragraph or equivalent.
23216 The function moves point to the beginning of the next visible
23217 structural element, which can be a paragraph, a table, a list
23218 item, etc. It also provides some special moves for convenience:
23220 - On an affiliated keyword, jump to the beginning of the
23221 relative element.
23222 - On an item or a footnote definition, move to the second
23223 element inside, if any.
23224 - On a table or a property drawer, jump after it.
23225 - On a verse or source block, stop after blank lines."
23226 (interactive)
23227 (unless (eobp)
23228 (let* ((deactivate-mark nil)
23229 (element (org-element-at-point))
23230 (type (org-element-type element))
23231 (post-affiliated (org-element-property :post-affiliated element))
23232 (contents-begin (org-element-property :contents-begin element))
23233 (contents-end (org-element-property :contents-end element))
23234 (end (let ((end (org-element-property :end element)) (parent element))
23235 (while (and (setq parent (org-element-property :parent parent))
23236 (= (org-element-property :contents-end parent) end))
23237 (setq end (org-element-property :end parent)))
23238 end)))
23239 (cond ((not element)
23240 (skip-chars-forward " \r\t\n")
23241 (or (eobp) (beginning-of-line)))
23242 ;; On affiliated keywords, move to element's beginning.
23243 ((< (point) post-affiliated)
23244 (goto-char post-affiliated))
23245 ;; At a table row, move to the end of the table. Similarly,
23246 ;; at a node property, move to the end of the property
23247 ;; drawer.
23248 ((memq type '(node-property table-row))
23249 (goto-char (org-element-property
23250 :end (org-element-property :parent element))))
23251 ((memq type '(property-drawer table)) (goto-char end))
23252 ;; Consider blank lines as separators in verse and source
23253 ;; blocks to ease editing.
23254 ((memq type '(src-block verse-block))
23255 (when (eq type 'src-block)
23256 (setq contents-end
23257 (save-excursion (goto-char end)
23258 (skip-chars-backward " \r\t\n")
23259 (line-beginning-position))))
23260 (beginning-of-line)
23261 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23262 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23263 (goto-char end)
23264 (skip-chars-forward " \r\t\n")
23265 (if (= (point) contents-end) (goto-char end)
23266 (beginning-of-line))))
23267 ;; With no contents, just skip element.
23268 ((not contents-begin) (goto-char end))
23269 ;; If contents are invisible, skip the element altogether.
23270 ((org-invisible-p (line-end-position))
23271 (cl-case type
23272 (headline
23273 (org-with-limited-levels (outline-next-visible-heading 1)))
23274 ;; At a plain list, make sure we move to the next item
23275 ;; instead of skipping the whole list.
23276 (plain-list (forward-char)
23277 (org-forward-paragraph))
23278 (otherwise (goto-char end))))
23279 ((>= (point) contents-end) (goto-char end))
23280 ((>= (point) contents-begin)
23281 ;; This can only happen on paragraphs and plain lists.
23282 (cl-case type
23283 (paragraph (goto-char end))
23284 ;; At a plain list, try to move to second element in
23285 ;; first item, if possible.
23286 (plain-list (end-of-line)
23287 (org-forward-paragraph))))
23288 ;; When contents start on the middle of a line (e.g. in
23289 ;; items and footnote definitions), try to reach first
23290 ;; element starting after current line.
23291 ((> (line-end-position) contents-begin)
23292 (end-of-line)
23293 (org-forward-paragraph))
23294 (t (goto-char contents-begin))))))
23296 (defun org-backward-paragraph ()
23297 "Move backward to start of previous paragraph or equivalent.
23299 The function moves point to the beginning of the current
23300 structural element, which can be a paragraph, a table, a list
23301 item, etc., or to the beginning of the previous visible one if
23302 point is already there. It also provides some special moves for
23303 convenience:
23305 - On an affiliated keyword, jump to the first one.
23306 - On a table or a property drawer, move to its beginning.
23307 - On comment, example, export, src and verse blocks, stop
23308 before blank lines."
23309 (interactive)
23310 (unless (bobp)
23311 (let* ((deactivate-mark nil)
23312 (element (org-element-at-point))
23313 (type (org-element-type element))
23314 (contents-end (org-element-property :contents-end element))
23315 (post-affiliated (org-element-property :post-affiliated element))
23316 (begin (org-element-property :begin element))
23317 (special? ;blocks handled specially
23318 (memq type '(comment-block example-block export-block src-block
23319 verse-block)))
23320 (contents-begin
23321 (if special?
23322 ;; These types have no proper contents. Fake line
23323 ;; below the block opening line as contents beginning.
23324 (save-excursion (goto-char begin) (line-beginning-position 2))
23325 (org-element-property :contents-begin element))))
23326 (cond
23327 ((not element) (goto-char (point-min)))
23328 ((= (point) begin)
23329 (backward-char)
23330 (org-backward-paragraph))
23331 ((<= (point) post-affiliated) (goto-char begin))
23332 ;; Special behavior: on a table or a property drawer, move to
23333 ;; its beginning.
23334 ((memq type '(node-property table-row))
23335 (goto-char (org-element-property
23336 :post-affiliated (org-element-property :parent element))))
23337 (special?
23338 (if (<= (point) contents-begin) (goto-char post-affiliated)
23339 ;; Inside a verse block, see blank lines as paragraph
23340 ;; separators.
23341 (let ((origin (point)))
23342 (skip-chars-backward " \r\t\n" contents-begin)
23343 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23344 (skip-chars-forward " \r\t\n" origin)
23345 (if (= (point) origin) (goto-char contents-begin)
23346 (beginning-of-line))))))
23347 ((eq type 'paragraph) (goto-char contents-begin)
23348 ;; When at first paragraph in an item or a footnote definition,
23349 ;; move directly to beginning of line.
23350 (let ((parent-contents
23351 (org-element-property
23352 :contents-begin (org-element-property :parent element))))
23353 (when (and parent-contents (= parent-contents contents-begin))
23354 (beginning-of-line))))
23355 ;; At the end of a greater element, move to the beginning of
23356 ;; the last element within.
23357 ((and contents-end (>= (point) contents-end))
23358 (goto-char (1- contents-end))
23359 (org-backward-paragraph))
23360 (t (goto-char (or post-affiliated begin))))
23361 ;; Ensure we never leave point invisible.
23362 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23364 (defun org-forward-element ()
23365 "Move forward by one element.
23366 Move to the next element at the same level, when possible."
23367 (interactive)
23368 (cond ((eobp) (user-error "Cannot move further down"))
23369 ((org-with-limited-levels (org-at-heading-p))
23370 (let ((origin (point)))
23371 (goto-char (org-end-of-subtree nil t))
23372 (unless (org-with-limited-levels (org-at-heading-p))
23373 (goto-char origin)
23374 (user-error "Cannot move further down"))))
23376 (let* ((elem (org-element-at-point))
23377 (end (org-element-property :end elem))
23378 (parent (org-element-property :parent elem)))
23379 (cond ((and parent (= (org-element-property :contents-end parent) end))
23380 (goto-char (org-element-property :end parent)))
23381 ((integer-or-marker-p end) (goto-char end))
23382 (t (message "No element at point")))))))
23384 (defun org-backward-element ()
23385 "Move backward by one element.
23386 Move to the previous element at the same level, when possible."
23387 (interactive)
23388 (cond ((bobp) (user-error "Cannot move further up"))
23389 ((org-with-limited-levels (org-at-heading-p))
23390 ;; At a headline, move to the previous one, if any, or stay
23391 ;; here.
23392 (let ((origin (point)))
23393 (org-with-limited-levels (org-backward-heading-same-level 1))
23394 ;; When current headline has no sibling above, move to its
23395 ;; parent.
23396 (when (= (point) origin)
23397 (or (org-with-limited-levels (org-up-heading-safe))
23398 (progn (goto-char origin)
23399 (user-error "Cannot move further up"))))))
23401 (let* ((elem (org-element-at-point))
23402 (beg (org-element-property :begin elem)))
23403 (cond
23404 ;; Move to beginning of current element if point isn't
23405 ;; there already.
23406 ((null beg) (message "No element at point"))
23407 ((/= (point) beg) (goto-char beg))
23408 (t (goto-char beg)
23409 (skip-chars-backward " \r\t\n")
23410 (unless (bobp)
23411 (let ((prev (org-element-at-point)))
23412 (goto-char (org-element-property :begin prev))
23413 (while (and (setq prev (org-element-property :parent prev))
23414 (<= (org-element-property :end prev) beg))
23415 (goto-char (org-element-property :begin prev)))))))))))
23417 (defun org-up-element ()
23418 "Move to upper element."
23419 (interactive)
23420 (if (org-with-limited-levels (org-at-heading-p))
23421 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23422 (let* ((elem (org-element-at-point))
23423 (parent (org-element-property :parent elem)))
23424 (if parent (goto-char (org-element-property :begin parent))
23425 (if (org-with-limited-levels (org-before-first-heading-p))
23426 (user-error "No surrounding element")
23427 (org-with-limited-levels (org-back-to-heading)))))))
23429 (defun org-down-element ()
23430 "Move to inner element."
23431 (interactive)
23432 (let ((element (org-element-at-point)))
23433 (cond
23434 ((memq (org-element-type element) '(plain-list table))
23435 (goto-char (org-element-property :contents-begin element))
23436 (forward-char))
23437 ((memq (org-element-type element) org-element-greater-elements)
23438 ;; If contents are hidden, first disclose them.
23439 (when (org-invisible-p (line-end-position)) (org-cycle))
23440 (goto-char (or (org-element-property :contents-begin element)
23441 (user-error "No content for this element"))))
23442 (t (user-error "No inner element")))))
23444 (defun org-drag-element-backward ()
23445 "Move backward element at point."
23446 (interactive)
23447 (let ((elem (or (org-element-at-point)
23448 (user-error "No element at point"))))
23449 (if (eq (org-element-type elem) 'headline)
23450 ;; Preserve point when moving a whole tree, even if point was
23451 ;; on blank lines below the headline.
23452 (let ((offset (skip-chars-backward " \t\n")))
23453 (unwind-protect (org-move-subtree-up)
23454 (forward-char (- offset))))
23455 (let ((prev-elem
23456 (save-excursion
23457 (goto-char (org-element-property :begin elem))
23458 (skip-chars-backward " \r\t\n")
23459 (unless (bobp)
23460 (let* ((beg (org-element-property :begin elem))
23461 (prev (org-element-at-point))
23462 (up prev))
23463 (while (and (setq up (org-element-property :parent up))
23464 (<= (org-element-property :end up) beg))
23465 (setq prev up))
23466 prev)))))
23467 ;; Error out if no previous element or previous element is
23468 ;; a parent of the current one.
23469 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23470 (user-error "Cannot drag element backward")
23471 (let ((pos (point)))
23472 (org-element-swap-A-B prev-elem elem)
23473 (goto-char (+ (org-element-property :begin prev-elem)
23474 (- pos (org-element-property :begin elem))))))))))
23476 (defun org-drag-element-forward ()
23477 "Move forward element at point."
23478 (interactive)
23479 (let* ((pos (point))
23480 (elem (or (org-element-at-point)
23481 (user-error "No element at point"))))
23482 (when (= (point-max) (org-element-property :end elem))
23483 (user-error "Cannot drag element forward"))
23484 (goto-char (org-element-property :end elem))
23485 (let ((next-elem (org-element-at-point)))
23486 (when (or (org-element-nested-p elem next-elem)
23487 (and (eq (org-element-type next-elem) 'headline)
23488 (not (eq (org-element-type elem) 'headline))))
23489 (goto-char pos)
23490 (user-error "Cannot drag element forward"))
23491 ;; Compute new position of point: it's shifted by NEXT-ELEM
23492 ;; body's length (without final blanks) and by the length of
23493 ;; blanks between ELEM and NEXT-ELEM.
23494 (let ((size-next (- (save-excursion
23495 (goto-char (org-element-property :end next-elem))
23496 (skip-chars-backward " \r\t\n")
23497 (forward-line)
23498 ;; Small correction if buffer doesn't end
23499 ;; with a newline character.
23500 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23501 (org-element-property :begin next-elem)))
23502 (size-blank (- (org-element-property :end elem)
23503 (save-excursion
23504 (goto-char (org-element-property :end elem))
23505 (skip-chars-backward " \r\t\n")
23506 (forward-line)
23507 (point)))))
23508 (org-element-swap-A-B elem next-elem)
23509 (goto-char (+ pos size-next size-blank))))))
23511 (defun org-drag-line-forward (arg)
23512 "Drag the line at point ARG lines forward."
23513 (interactive "p")
23514 (dotimes (_ (abs arg))
23515 (let ((c (current-column)))
23516 (if (< 0 arg)
23517 (progn
23518 (beginning-of-line 2)
23519 (transpose-lines 1)
23520 (beginning-of-line 0))
23521 (transpose-lines 1)
23522 (beginning-of-line -1))
23523 (org-move-to-column c))))
23525 (defun org-drag-line-backward (arg)
23526 "Drag the line at point ARG lines backward."
23527 (interactive "p")
23528 (org-drag-line-forward (- arg)))
23530 (defun org-mark-element ()
23531 "Put point at beginning of this element, mark at end.
23533 Interactively, if this command is repeated or (in Transient Mark
23534 mode) if the mark is active, it marks the next element after the
23535 ones already marked."
23536 (interactive)
23537 (let (deactivate-mark)
23538 (if (and (called-interactively-p 'any)
23539 (or (and (eq last-command this-command) (mark t))
23540 (and transient-mark-mode mark-active)))
23541 (set-mark
23542 (save-excursion
23543 (goto-char (mark))
23544 (goto-char (org-element-property :end (org-element-at-point)))))
23545 (let ((element (org-element-at-point)))
23546 (end-of-line)
23547 (push-mark (org-element-property :end element) t t)
23548 (goto-char (org-element-property :begin element))))))
23550 (defun org-narrow-to-element ()
23551 "Narrow buffer to current element."
23552 (interactive)
23553 (let ((elem (org-element-at-point)))
23554 (cond
23555 ((eq (car elem) 'headline)
23556 (narrow-to-region
23557 (org-element-property :begin elem)
23558 (org-element-property :end elem)))
23559 ((memq (car elem) org-element-greater-elements)
23560 (narrow-to-region
23561 (org-element-property :contents-begin elem)
23562 (org-element-property :contents-end elem)))
23564 (narrow-to-region
23565 (org-element-property :begin elem)
23566 (org-element-property :end elem))))))
23568 (defun org-transpose-element ()
23569 "Transpose current and previous elements, keeping blank lines between.
23570 Point is moved after both elements."
23571 (interactive)
23572 (org-skip-whitespace)
23573 (let ((end (org-element-property :end (org-element-at-point))))
23574 (org-drag-element-backward)
23575 (goto-char end)))
23577 (defun org-unindent-buffer ()
23578 "Un-indent the visible part of the buffer.
23579 Relative indentation (between items, inside blocks, etc.) isn't
23580 modified."
23581 (interactive)
23582 (unless (eq major-mode 'org-mode)
23583 (user-error "Cannot un-indent a buffer not in Org mode"))
23584 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23585 (unindent-tree
23586 (lambda (contents)
23587 (dolist (element (reverse contents))
23588 (if (memq (org-element-type element) '(headline section))
23589 (funcall unindent-tree (org-element-contents element))
23590 (save-excursion
23591 (save-restriction
23592 (narrow-to-region
23593 (org-element-property :begin element)
23594 (org-element-property :end element))
23595 (org-do-remove-indentation))))))))
23596 (funcall unindent-tree (org-element-contents parse-tree))))
23598 (defun org-make-options-regexp (kwds &optional extra)
23599 "Make a regular expression for keyword lines.
23600 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23601 when non-nil, is a regexp matching keywords names."
23602 (concat "^[ \t]*#\\+\\("
23603 (regexp-opt kwds)
23604 (and extra (concat (and kwds "\\|") extra))
23605 "\\):[ \t]*\\(.*\\)"))
23608 ;;; Finish up
23610 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23611 (lambda () (add-hook 'change-major-mode-hook
23612 'org-show-all 'append 'local)))
23614 (provide 'org)
23616 (run-hooks 'org-load-hook)
23618 ;;; org.el ends here