Standardize tag regexps
[org-mode/org-tableheadings.git] / lisp / org.el
blobcde3f19516424e779a98a9abddcbedd5c6e92062
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.10
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)
188 ;; load languages based on value of `org-babel-load-languages'
189 (defvar org-babel-load-languages)
191 ;;;###autoload
192 (defun org-babel-do-load-languages (sym value)
193 "Load the languages defined in `org-babel-load-languages'."
194 (set-default sym value)
195 (dolist (pair org-babel-load-languages)
196 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
197 (if active
198 (require (intern (concat "ob-" lang)))
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-execute:" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-expand-body:" lang)))))))
204 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
205 ;;;###autoload
206 (defun org-babel-load-file (file &optional compile)
207 "Load Emacs Lisp source code blocks in the Org FILE.
208 This function exports the source code using `org-babel-tangle'
209 and then loads the resulting file using `load-file'. With prefix
210 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
211 file to byte-code before it is loaded."
212 (interactive "fFile to load: \nP")
213 (let* ((age (lambda (file)
214 (float-time
215 (time-subtract (current-time)
216 (nth 5 (or (file-attributes (file-truename file))
217 (file-attributes file)))))))
218 (base-name (file-name-sans-extension file))
219 (exported-file (concat base-name ".el")))
220 ;; tangle if the Org file is newer than the elisp file
221 (unless (and (file-exists-p exported-file)
222 (> (funcall age file) (funcall age exported-file)))
223 ;; Tangle-file traversal returns reversed list of tangled files
224 ;; and we want to evaluate the first target.
225 (setq exported-file
226 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
227 (message "%s %s"
228 (if compile
229 (progn (byte-compile-file exported-file 'load)
230 "Compiled and loaded")
231 (progn (load-file exported-file) "Loaded"))
232 exported-file)))
234 (defcustom org-babel-load-languages '((emacs-lisp . t))
235 "Languages which can be evaluated in Org buffers.
236 This list can be used to load support for any of the languages
237 below, note that each language will depend on a different set of
238 system executables and/or Emacs modes. When a language is
239 \"loaded\", then code blocks in that language can be evaluated
240 with `org-babel-execute-src-block' bound by default to C-c
241 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
242 be set to remove code block evaluation from the C-c C-c
243 keybinding. By default only Emacs Lisp (which has no
244 requirements) is loaded."
245 :group 'org-babel
246 :set 'org-babel-do-load-languages
247 :version "24.1"
248 :type '(alist :tag "Babel Languages"
249 :key-type
250 (choice
251 (const :tag "Awk" awk)
252 (const :tag "C" C)
253 (const :tag "R" R)
254 (const :tag "Asymptote" asymptote)
255 (const :tag "Calc" calc)
256 (const :tag "Clojure" clojure)
257 (const :tag "CSS" css)
258 (const :tag "Ditaa" ditaa)
259 (const :tag "Dot" dot)
260 (const :tag "Ebnf2ps" ebnf2ps)
261 (const :tag "Emacs Lisp" emacs-lisp)
262 (const :tag "Forth" forth)
263 (const :tag "Fortran" fortran)
264 (const :tag "Gnuplot" gnuplot)
265 (const :tag "Haskell" haskell)
266 (const :tag "hledger" hledger)
267 (const :tag "IO" io)
268 (const :tag "J" J)
269 (const :tag "Java" java)
270 (const :tag "Javascript" js)
271 (const :tag "LaTeX" latex)
272 (const :tag "Ledger" ledger)
273 (const :tag "Lilypond" lilypond)
274 (const :tag "Lisp" lisp)
275 (const :tag "Makefile" makefile)
276 (const :tag "Maxima" maxima)
277 (const :tag "Matlab" matlab)
278 (const :tag "Mscgen" mscgen)
279 (const :tag "Ocaml" ocaml)
280 (const :tag "Octave" octave)
281 (const :tag "Org" org)
282 (const :tag "Perl" perl)
283 (const :tag "Pico Lisp" picolisp)
284 (const :tag "PlantUML" plantuml)
285 (const :tag "Python" python)
286 (const :tag "Ruby" ruby)
287 (const :tag "Sass" sass)
288 (const :tag "Scala" scala)
289 (const :tag "Scheme" scheme)
290 (const :tag "Screen" screen)
291 (const :tag "Shell Script" shell)
292 (const :tag "Shen" shen)
293 (const :tag "Sql" sql)
294 (const :tag "Sqlite" sqlite)
295 (const :tag "Stan" stan)
296 (const :tag "Vala" vala))
297 :value-type (boolean :tag "Activate" :value t)))
299 ;;;; Customization variables
300 (defcustom org-clone-delete-id nil
301 "Remove ID property of clones of a subtree.
302 When non-nil, clones of a subtree don't inherit the ID property.
303 Otherwise they inherit the ID property with a new unique
304 identifier."
305 :type 'boolean
306 :version "24.1"
307 :group 'org-id)
309 ;;; Version
310 (org-check-version)
312 ;;;###autoload
313 (defun org-version (&optional here full message)
314 "Show the Org version.
315 Interactively, or when MESSAGE is non-nil, show it in echo area.
316 With prefix argument, or when HERE is non-nil, insert it at point.
317 In non-interactive uses, a reduced version string is output unless
318 FULL is given."
319 (interactive (list current-prefix-arg t (not current-prefix-arg)))
320 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
321 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
322 (load-suffixes (list ".el"))
323 (org-install-dir
324 (ignore-errors (org-find-library-dir "org-loaddefs"))))
325 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
326 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
327 (let* ((load-suffixes save-load-suffixes)
328 (release (org-release))
329 (git-version (org-git-version))
330 (version (format "Org mode version %s (%s @ %s)"
331 release
332 git-version
333 (if org-install-dir
334 (if (string= org-dir org-install-dir)
335 org-install-dir
336 (concat "mixed installation! "
337 org-install-dir
338 " and "
339 org-dir))
340 "org-loaddefs.el can not be found!")))
341 (version1 (if full version release)))
342 (when here (insert version1))
343 (when message (message "%s" version1))
344 version1)))
346 (defconst org-version (org-version))
349 ;;; Syntax Constants
351 ;;;; Block
353 (defconst org-block-regexp
354 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
355 "Regular expression for hiding blocks.")
357 (defconst org-dblock-start-re
358 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
359 "Matches the start line of a dynamic block, with parameters.")
361 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
362 "Matches the end of a dynamic block.")
364 ;;;; Clock and Planning
366 (defconst org-clock-string "CLOCK:"
367 "String used as prefix for timestamps clocking work hours on an item.")
369 (defvar org-closed-string "CLOSED:"
370 "String used as the prefix for timestamps logging closing a TODO entry.")
372 (defvar org-deadline-string "DEADLINE:"
373 "String to mark deadline entries.
374 \\<org-mode-map>
375 A deadline is this string, followed by a time stamp. It must be
376 a word, terminated by a colon. You can insert a schedule keyword
377 and a timestamp with `\\[org-deadline]'.")
379 (defvar org-scheduled-string "SCHEDULED:"
380 "String to mark scheduled TODO entries.
381 \\<org-mode-map>
382 A schedule is this string, followed by a time stamp. It must be
383 a word, terminated by a colon. You can insert a schedule keyword
384 and a timestamp with `\\[org-schedule]'.")
386 (defconst org-ds-keyword-length
387 (+ 2
388 (apply #'max
389 (mapcar #'length
390 (list org-deadline-string org-scheduled-string
391 org-clock-string org-closed-string))))
392 "Maximum length of the DEADLINE and SCHEDULED keywords.")
394 (defconst org-planning-line-re
395 (concat "^[ \t]*"
396 (regexp-opt
397 (list org-closed-string org-deadline-string org-scheduled-string)
399 "Matches a line with planning info.
400 Matched keyword is in group 1.")
402 (defconst org-clock-line-re
403 (concat "^[ \t]*" org-clock-string)
404 "Matches a line with clock info.")
406 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
407 "Matches the DEADLINE keyword.")
409 (defconst org-deadline-time-regexp
410 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
411 "Matches the DEADLINE keyword together with a time stamp.")
413 (defconst org-deadline-time-hour-regexp
414 (concat "\\<" org-deadline-string
415 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
416 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
418 (defconst org-deadline-line-regexp
419 (concat "\\<\\(" org-deadline-string "\\).*")
420 "Matches the DEADLINE keyword and the rest of the line.")
422 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
423 "Matches the SCHEDULED keyword.")
425 (defconst org-scheduled-time-regexp
426 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
427 "Matches the SCHEDULED keyword together with a time stamp.")
429 (defconst org-scheduled-time-hour-regexp
430 (concat "\\<" org-scheduled-string
431 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
432 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
434 (defconst org-closed-time-regexp
435 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
436 "Matches the CLOSED keyword together with a time stamp.")
438 (defconst org-keyword-time-regexp
439 (concat "\\<"
440 (regexp-opt
441 (list org-scheduled-string org-deadline-string org-closed-string
442 org-clock-string)
444 " *[[<]\\([^]>]+\\)[]>]")
445 "Matches any of the 4 keywords, together with the time stamp.")
447 (defconst org-keyword-time-not-clock-regexp
448 (concat
449 "\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string) t)
452 " *[[<]\\([^]>]+\\)[]>]")
453 "Matches any of the 3 keywords, together with the time stamp.")
455 (defconst org-maybe-keyword-time-regexp
456 (concat "\\(\\<"
457 (regexp-opt
458 (list org-scheduled-string org-deadline-string org-closed-string
459 org-clock-string)
461 "\\)?"
462 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
463 "\\|"
464 "<%%([^\r\n>]*>\\)")
465 "Matches a timestamp, possibly preceded by a keyword.")
467 (defconst org-all-time-keywords
468 (mapcar (lambda (w) (substring w 0 -1))
469 (list org-scheduled-string org-deadline-string
470 org-clock-string org-closed-string))
471 "List of time keywords.")
473 ;;;; Drawer
475 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
476 "Matches first or last line of a hidden block.
477 Group 1 contains drawer's name or \"END\".")
479 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
480 "Regular expression matching the first line of a property drawer.")
482 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
483 "Regular expression matching the last line of a property drawer.")
485 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
486 "Regular expression matching the first line of a clock drawer.")
488 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
489 "Regular expression matching the last line of a clock drawer.")
491 (defconst org-property-drawer-re
492 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
493 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
494 "[ \t]*:END:[ \t]*$")
495 "Matches an entire property drawer.")
497 (defconst org-clock-drawer-re
498 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
499 org-clock-drawer-end-re "\\)\n?")
500 "Matches an entire clock drawer.")
502 ;;;; Headline
504 (defconst org-heading-keyword-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline with some keyword.
507 This regexp will match the headline of any node which has the
508 exact keyword that is put into the format. The keyword isn't in
509 any group by default, but the stars and the body are.")
511 (defconst org-heading-keyword-maybe-regexp-format
512 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
513 "Printf format for a regexp matching a headline, possibly with some keyword.
514 This regexp can match any headline with the specified keyword, or
515 without a keyword. The keyword isn't in any group by default,
516 but the stars and the body are.")
518 (defconst org-archive-tag "ARCHIVE"
519 "The tag that marks a subtree as archived.
520 An archived subtree does not open during visibility cycling, and does
521 not contribute to the agenda listings.")
523 (defconst org-tag-re "[[:alnum:]_@#%]+"
524 "Regexp matching a single tag.")
526 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
527 "Regexp matching the tag group at the end of a line, with leading spaces.
528 Tags are stored in match group 1. Match group 2 stores the tags
529 without the enclosing colons.")
531 (defconst org-tag-line-re
532 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
533 "Regexp matching tags in a headline.
534 Tags are stored in match group 1. Match group 2 stores the tags
535 without the enclosing colons.")
537 (eval-and-compile
538 (defconst org-comment-string "COMMENT"
539 "Entries starting with this keyword will never be exported.
540 \\<org-mode-map>
541 An entry can be toggled between COMMENT and normal with
542 `\\[org-toggle-comment]'."))
545 ;;;; LaTeX Environments and Fragments
547 (defconst org-latex-regexps
548 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
549 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
550 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
551 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
552 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
554 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
555 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
556 "Regular expressions for matching embedded LaTeX.")
558 ;;;; Node Property
560 (defconst org-effort-property "Effort"
561 "The property that is being used to keep track of effort estimates.
562 Effort estimates given in this property need to have the format H:MM.")
564 ;;;; Table
566 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
567 "Detect an org-type or table-type table.")
569 (defconst org-table-line-regexp "^[ \t]*|"
570 "Detect an org-type table line.")
572 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
573 "Detect an org-type table line.")
575 (defconst org-table-hline-regexp "^[ \t]*|-"
576 "Detect an org-type table hline.")
578 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
579 "Detect a table-type table hline.")
581 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
582 "Detect the first line outside a table when searching from within it.
583 This works for both table types.")
585 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
586 "Detect a #+TBLFM line.")
588 ;;;; Timestamp
590 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
591 "Regular expression for fast time stamp matching.")
593 (defconst org-ts-regexp-inactive
594 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
595 "Regular expression for fast inactive time stamp matching.")
597 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
598 "Regular expression for fast time stamp matching.")
600 (defconst org-ts-regexp0
601 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
602 "Regular expression matching time strings for analysis.
603 This one does not require the space after the date, so it can be used
604 on a string that terminates immediately after the date.")
606 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
607 "Regular expression matching time strings for analysis.")
609 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
610 "Regular expression matching time stamps, with groups.")
612 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
613 "Regular expression matching time stamps (also [..]), with groups.")
615 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
616 "Regular expression matching a time stamp range.")
618 (defconst org-tr-regexp-both
619 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
620 "Regular expression matching a time stamp range.")
622 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
623 org-ts-regexp "\\)?")
624 "Regular expression matching a time stamp or time stamp range.")
626 (defconst org-tsr-regexp-both
627 (concat org-ts-regexp-both "\\(--?-?"
628 org-ts-regexp-both "\\)?")
629 "Regular expression matching a time stamp or time stamp range.
630 The time stamps may be either active or inactive.")
632 (defconst org-repeat-re
633 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
634 "Regular expression for specifying repeated events.
635 After a match, group 1 contains the repeat expression.")
637 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
638 "Formats for `format-time-string' which are used for time stamps.")
641 ;;; The custom variables
643 (defgroup org nil
644 "Outline-based notes management and organizer."
645 :tag "Org"
646 :group 'outlines
647 :group 'calendar)
649 (defcustom org-mode-hook nil
650 "Mode hook for Org mode, run after the mode was turned on."
651 :group 'org
652 :type 'hook)
654 (defcustom org-load-hook nil
655 "Hook that is run after org.el has been loaded."
656 :group 'org
657 :type 'hook)
659 (defcustom org-log-buffer-setup-hook nil
660 "Hook that is run after an Org log buffer is created."
661 :group 'org
662 :version "24.1"
663 :type 'hook)
665 (defvar org-modules) ; defined below
666 (defvar org-modules-loaded nil
667 "Have the modules been loaded already?")
669 (defun org-load-modules-maybe (&optional force)
670 "Load all extensions listed in `org-modules'."
671 (when (or force (not org-modules-loaded))
672 (dolist (ext org-modules)
673 (condition-case nil (require ext)
674 (error (message "Problems while trying to load feature `%s'" ext))))
675 (setq org-modules-loaded t)))
677 (defun org-set-modules (var value)
678 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
679 (set var value)
680 (when (featurep 'org)
681 (org-load-modules-maybe 'force)
682 (org-element-cache-reset 'all)))
684 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
685 "Modules that should always be loaded together with org.el.
687 If a description starts with <C>, the file is not part of Emacs
688 and loading it will require that you have downloaded and properly
689 installed the Org mode distribution.
691 You can also use this system to load external packages (i.e. neither Org
692 core modules, nor modules from the CONTRIB directory). Just add symbols
693 to the end of the list. If the package is called org-xyz.el, then you need
694 to add the symbol `xyz', and the package must have a call to:
696 (provide \\='org-xyz)
698 For export specific modules, see also `org-export-backends'."
699 :group 'org
700 :set 'org-set-modules
701 :version "24.4"
702 :package-version '(Org . "8.0")
703 :type
704 '(set :greedy t
705 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
706 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
707 (const :tag " crypt: Encryption of subtrees" org-crypt)
708 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
709 (const :tag " docview: Links to doc-view buffers" org-docview)
710 (const :tag " eww: Store link to url of eww" org-eww)
711 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
712 (const :tag " habit: Track your consistency with habits" org-habit)
713 (const :tag " id: Global IDs for identifying entries" org-id)
714 (const :tag " info: Links to Info nodes" org-info)
715 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
716 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
717 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
718 (const :tag " mouse: Additional mouse support" org-mouse)
719 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
720 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
721 (const :tag " tempo: Fast completion for structures" org-tempo)
722 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
724 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
725 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
726 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
727 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
728 (const :tag "C collector: Collect properties into tables" org-collector)
729 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
730 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
731 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
732 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
733 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
734 (const :tag "C eval: Include command output as text" org-eval)
735 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
736 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
737 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
738 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
739 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
740 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
741 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
742 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
743 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
744 (const :tag "C man: Support for links to manpages in Org mode" org-man)
745 (const :tag "C mew: Links to Mew folders/messages" org-mew)
746 (const :tag "C mtags: Support for muse-like tags" org-mtags)
747 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
748 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
749 (const :tag "C registry: A registry for Org links" org-registry)
750 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
751 (const :tag "C secretary: Team management with Org" org-secretary)
752 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
753 (const :tag "C toc: Table of contents for Org buffer" org-toc)
754 (const :tag "C track: Keep up with Org mode development" org-track)
755 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
756 (const :tag "C vm: Links to VM folders/messages" org-vm)
757 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
758 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
759 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
761 (defvar org-export-registered-backends) ; From ox.el.
762 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
763 (declare-function org-export-backend-name "ox" (backend) t)
764 (defcustom org-export-backends '(ascii html icalendar latex odt)
765 "List of export back-ends that should be always available.
767 If a description starts with <C>, the file is not part of Emacs
768 and loading it will require that you have downloaded and properly
769 installed the Org mode distribution.
771 Unlike to `org-modules', libraries in this list will not be
772 loaded along with Org, but only once the export framework is
773 needed.
775 This variable needs to be set before org.el is loaded. If you
776 need to make a change while Emacs is running, use the customize
777 interface or run the following code, where VAL stands for the new
778 value of the variable, after updating it:
780 (progn
781 (setq org-export-registered-backends
782 (cl-remove-if-not
783 (lambda (backend)
784 (let ((name (org-export-backend-name backend)))
785 (or (memq name val)
786 (catch \\='parentp
787 (dolist (b val)
788 (and (org-export-derived-backend-p b name)
789 (throw \\='parentp t)))))))
790 org-export-registered-backends))
791 (let ((new-list (mapcar #\\='org-export-backend-name
792 org-export-registered-backends)))
793 (dolist (backend val)
794 (cond
795 ((not (load (format \"ox-%s\" backend) t t))
796 (message \"Problems while trying to load export back-end \\=`%s\\='\"
797 backend))
798 ((not (memq backend new-list)) (push backend new-list))))
799 (set-default \\='org-export-backends new-list)))
801 Adding a back-end to this list will also pull the back-end it
802 depends on, if any."
803 :group 'org
804 :group 'org-export
805 :version "26.1"
806 :package-version '(Org . "9.0")
807 :initialize 'custom-initialize-set
808 :set (lambda (var val)
809 (if (not (featurep 'ox)) (set-default var val)
810 ;; Any back-end not required anymore (not present in VAL and not
811 ;; a parent of any back-end in the new value) is removed from the
812 ;; list of registered back-ends.
813 (setq org-export-registered-backends
814 (cl-remove-if-not
815 (lambda (backend)
816 (let ((name (org-export-backend-name backend)))
817 (or (memq name val)
818 (catch 'parentp
819 (dolist (b val)
820 (and (org-export-derived-backend-p b name)
821 (throw 'parentp t)))))))
822 org-export-registered-backends))
823 ;; Now build NEW-LIST of both new back-ends and required
824 ;; parents.
825 (let ((new-list (mapcar #'org-export-backend-name
826 org-export-registered-backends)))
827 (dolist (backend val)
828 (cond
829 ((not (load (format "ox-%s" backend) t t))
830 (message "Problems while trying to load export back-end `%s'"
831 backend))
832 ((not (memq backend new-list)) (push backend new-list))))
833 ;; Set VAR to that list with fixed dependencies.
834 (set-default var new-list))))
835 :type '(set :greedy t
836 (const :tag " ascii Export buffer to ASCII format" ascii)
837 (const :tag " beamer Export buffer to Beamer presentation" beamer)
838 (const :tag " html Export buffer to HTML format" html)
839 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
840 (const :tag " latex Export buffer to LaTeX format" latex)
841 (const :tag " man Export buffer to MAN format" man)
842 (const :tag " md Export buffer to Markdown format" md)
843 (const :tag " odt Export buffer to ODT format" odt)
844 (const :tag " org Export buffer to Org format" org)
845 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
846 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
847 (const :tag "C deck Export buffer to deck.js presentations" deck)
848 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
849 (const :tag "C groff Export buffer to Groff format" groff)
850 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
851 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
852 (const :tag "C s5 Export buffer to s5 presentations" s5)
853 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
855 (eval-after-load 'ox
856 '(dolist (backend org-export-backends)
857 (condition-case nil (require (intern (format "ox-%s" backend)))
858 (error (message "Problems while trying to load export back-end `%s'"
859 backend)))))
861 (defcustom org-support-shift-select nil
862 "Non-nil means make shift-cursor commands select text when possible.
863 \\<org-mode-map>\
865 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
866 start selecting a region, or enlarge regions started in this way.
867 In Org mode, in special contexts, these same keys are used for
868 other purposes, important enough to compete with shift selection.
869 Org tries to balance these needs by supporting `shift-select-mode'
870 outside these special contexts, under control of this variable.
872 The default of this variable is nil, to avoid confusing behavior. Shifted
873 cursor keys will then execute Org commands in the following contexts:
874 - on a headline, changing TODO state (left/right) and priority (up/down)
875 - on a time stamp, changing the time
876 - in a plain list item, changing the bullet type
877 - in a property definition line, switching between allowed values
878 - in the BEGIN line of a clock table (changing the time block).
879 Outside these contexts, the commands will throw an error.
881 When this variable is t and the cursor is not in a special
882 context, Org mode will support shift-selection for making and
883 enlarging regions. To make this more effective, the bullet
884 cycling will no longer happen anywhere in an item line, but only
885 if the cursor is exactly on the bullet.
887 If you set this variable to the symbol `always', then the keys
888 will not be special in headlines, property lines, and item lines,
889 to make shift selection work there as well. If this is what you
890 want, you can use the following alternative commands:
891 `\\[org-todo]' and `\\[org-priority]' \
892 to change TODO state and priority,
893 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
894 can be used to switch TODO sets,
895 `\\[org-ctrl-c-minus]' to cycle item bullet types,
896 and properties can be edited by hand or in column view.
898 However, when the cursor is on a timestamp, shift-cursor commands
899 will still edit the time stamp - this is just too good to give up."
900 :group 'org
901 :type '(choice
902 (const :tag "Never" nil)
903 (const :tag "When outside special context" t)
904 (const :tag "Everywhere except timestamps" always)))
906 (defcustom org-loop-over-headlines-in-active-region nil
907 "Shall some commands act upon headlines in the active region?
909 When set to t, some commands will be performed in all headlines
910 within the active region.
912 When set to `start-level', some commands will be performed in all
913 headlines within the active region, provided that these headlines
914 are of the same level than the first one.
916 When set to a string, those commands will be performed on the
917 matching headlines within the active region. Such string must be
918 a tags/property/todo match as it is used in the agenda tags view.
920 The list of commands is: `org-schedule', `org-deadline',
921 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
922 `org-archive-to-archive-sibling'. The archiving commands skip
923 already archived entries."
924 :type '(choice (const :tag "Don't loop" nil)
925 (const :tag "All headlines in active region" t)
926 (const :tag "In active region, headlines at the same level than the first one" start-level)
927 (string :tag "Tags/Property/Todo matcher"))
928 :version "24.1"
929 :group 'org-todo
930 :group 'org-archive)
932 (defcustom org-startup-folded t
933 "Non-nil means entering Org mode will switch to OVERVIEW.
935 This can also be configured on a per-file basis by adding one of
936 the following lines anywhere in the buffer:
938 #+STARTUP: fold (or `overview', this is equivalent)
939 #+STARTUP: nofold (or `showall', this is equivalent)
940 #+STARTUP: content
941 #+STARTUP: showeverything
943 Set `org-agenda-inhibit-startup' to a non-nil value if you want
944 to ignore this option when Org opens agenda files for the first
945 time."
946 :group 'org-startup
947 :type '(choice
948 (const :tag "nofold: show all" nil)
949 (const :tag "fold: overview" t)
950 (const :tag "content: all headlines" content)
951 (const :tag "show everything, even drawers" showeverything)))
953 (defcustom org-startup-truncated t
954 "Non-nil means entering Org mode will set `truncate-lines'.
955 This is useful since some lines containing links can be very long and
956 uninteresting. Also tables look terrible when wrapped.
958 The variable `org-startup-truncated' allows to configure
959 truncation for Org mode different to the other modes that use the
960 variable `truncate-lines' and as a shortcut instead of putting
961 the variable `truncate-lines' into the `org-mode-hook'. If one
962 wants to configure truncation for Org mode not statically but
963 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
964 the variable `truncate-lines' has to be used because in such a
965 case it is too late to set the variable `org-startup-truncated'."
966 :group 'org-startup
967 :type 'boolean)
969 (defcustom org-startup-indented nil
970 "Non-nil means turn on `org-indent-mode' on startup.
971 This can also be configured on a per-file basis by adding one of
972 the following lines anywhere in the buffer:
974 #+STARTUP: indent
975 #+STARTUP: noindent"
976 :group 'org-structure
977 :type '(choice
978 (const :tag "Not" nil)
979 (const :tag "Globally (slow on startup in large files)" t)))
981 (defcustom org-use-sub-superscripts t
982 "Non-nil means interpret \"_\" and \"^\" for display.
984 If you want to control how Org exports those characters, see
985 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
986 used to be an alias for `org-export-with-sub-superscripts' in
987 Org <8.0, it is not anymore.
989 When this option is turned on, you can use TeX-like syntax for
990 sub- and superscripts within the buffer. Several characters after
991 \"_\" or \"^\" will be considered as a single item - so grouping
992 with {} is normally not needed. For example, the following things
993 will be parsed as single sub- or superscripts:
995 10^24 or 10^tau several digits will be considered 1 item.
996 10^-12 or 10^-tau a leading sign with digits or a word
997 x^2-y^3 will be read as x^2 - y^3, because items are
998 terminated by almost any nonword/nondigit char.
999 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1001 Still, ambiguity is possible. So when in doubt, use {} to enclose
1002 the sub/superscript. If you set this variable to the symbol `{}',
1003 the braces are *required* in order to trigger interpretations as
1004 sub/superscript. This can be helpful in documents that need \"_\"
1005 frequently in plain text."
1006 :group 'org-startup
1007 :version "24.4"
1008 :package-version '(Org . "8.0")
1009 :type '(choice
1010 (const :tag "Always interpret" t)
1011 (const :tag "Only with braces" {})
1012 (const :tag "Never interpret" nil)))
1014 (defcustom org-startup-with-beamer-mode nil
1015 "Non-nil means turn on `org-beamer-mode' on startup.
1016 This can also be configured on a per-file basis by adding one of
1017 the following lines anywhere in the buffer:
1019 #+STARTUP: beamer"
1020 :group 'org-startup
1021 :version "24.1"
1022 :type 'boolean)
1024 (defcustom org-startup-align-all-tables nil
1025 "Non-nil means align all tables when visiting a file.
1026 This can also be configured on a per-file basis by adding one of
1027 the following lines anywhere in the buffer:
1028 #+STARTUP: align
1029 #+STARTUP: noalign"
1030 :group 'org-startup
1031 :type 'boolean)
1033 (defcustom org-startup-shrink-all-tables nil
1034 "Non-nil means shrink all table columns with a width cookie.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: shrink"
1038 :group 'org-startup
1039 :type 'boolean
1040 :version "27.1"
1041 :package-version '(Org . "9.2")
1042 :safe #'booleanp)
1044 (defcustom org-startup-with-inline-images nil
1045 "Non-nil means show inline images when loading a new Org file.
1046 This can also be configured on a per-file basis by adding one of
1047 the following lines anywhere in the buffer:
1048 #+STARTUP: inlineimages
1049 #+STARTUP: noinlineimages"
1050 :group 'org-startup
1051 :version "24.1"
1052 :type 'boolean)
1054 (defcustom org-startup-with-latex-preview nil
1055 "Non-nil means preview LaTeX fragments when loading a new Org file.
1057 This can also be configured on a per-file basis by adding one of
1058 the following lines anywhere in the buffer:
1059 #+STARTUP: latexpreview
1060 #+STARTUP: nolatexpreview"
1061 :group 'org-startup
1062 :version "24.4"
1063 :package-version '(Org . "8.0")
1064 :type 'boolean)
1066 (defcustom org-insert-mode-line-in-empty-file nil
1067 "Non-nil means insert the first line setting Org mode in empty files.
1068 When the function `org-mode' is called interactively in an empty file, this
1069 normally means that the file name does not automatically trigger Org mode.
1070 To ensure that the file will always be in Org mode in the future, a
1071 line enforcing Org mode will be inserted into the buffer, if this option
1072 has been set."
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defcustom org-replace-disputed-keys nil
1077 "Non-nil means use alternative key bindings for some keys.
1079 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1080 These keys are also used by other packages like Shift Select mode,
1081 CUA mode or Windmove. If you want to use Org mode together with
1082 one of these other modes, or more generally if you would like to
1083 move some Org mode commands to other keys, set this variable and
1084 configure the keys with the variable `org-disputed-keys'.
1086 This option is only relevant at load-time of Org mode, and must be set
1087 *before* org.el is loaded. Changing it requires a restart of Emacs to
1088 become effective."
1089 :group 'org-startup
1090 :type 'boolean)
1092 (defcustom org-use-extra-keys nil
1093 "Non-nil means use extra key sequence definitions for certain commands.
1094 This happens automatically if `window-system' is nil. This
1095 variable lets you do the same manually. You must set it before
1096 loading Org."
1097 :group 'org-startup
1098 :type 'boolean)
1100 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1102 (defcustom org-disputed-keys
1103 '(([(shift up)] . [(meta p)])
1104 ([(shift down)] . [(meta n)])
1105 ([(shift left)] . [(meta -)])
1106 ([(shift right)] . [(meta +)])
1107 ([(control shift right)] . [(meta shift +)])
1108 ([(control shift left)] . [(meta shift -)]))
1109 "Keys for which Org mode and other modes compete.
1110 This is an alist, cars are the default keys, second element specifies
1111 the alternative to use when `org-replace-disputed-keys' is t.
1113 Keys can be specified in any syntax supported by `define-key'.
1114 The value of this option takes effect only at Org mode startup,
1115 therefore you'll have to restart Emacs to apply it after changing."
1116 :group 'org-startup
1117 :type 'alist)
1119 (defun org-key (key)
1120 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1121 Or return the original if not disputed."
1122 (when org-replace-disputed-keys
1123 (let* ((nkey (key-description key))
1124 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1125 org-disputed-keys)))
1126 (setq key (if x (cdr x) key))))
1127 key)
1129 (defun org-defkey (keymap key def)
1130 "Define a key, possibly translated, as returned by `org-key'."
1131 (define-key keymap (org-key key) def))
1133 (defcustom org-ellipsis nil
1134 "The ellipsis to use in the Org mode outline.
1136 When nil, just use the standard three dots. When a non-empty string,
1137 use that string instead.
1139 The change affects only Org mode (which will then use its own display table).
1140 Changing this requires executing `\\[org-mode]' in a buffer to become
1141 effective."
1142 :group 'org-startup
1143 :type '(choice (const :tag "Default" nil)
1144 (string :tag "String" :value "...#"))
1145 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1147 (defvar org-display-table nil
1148 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1150 (defgroup org-keywords nil
1151 "Keywords in Org mode."
1152 :tag "Org Keywords"
1153 :group 'org)
1155 (defcustom org-closed-keep-when-no-todo nil
1156 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1157 :group 'org-todo
1158 :group 'org-keywords
1159 :version "24.4"
1160 :package-version '(Org . "8.0")
1161 :type 'boolean)
1163 (defgroup org-structure nil
1164 "Options concerning the general structure of Org files."
1165 :tag "Org Structure"
1166 :group 'org)
1168 (defgroup org-reveal-location nil
1169 "Options about how to make context of a location visible."
1170 :tag "Org Reveal Location"
1171 :group 'org-structure)
1173 (defcustom org-show-context-detail '((agenda . local)
1174 (bookmark-jump . lineage)
1175 (isearch . lineage)
1176 (default . ancestors))
1177 "Alist between context and visibility span when revealing a location.
1179 \\<org-mode-map>Some actions may move point into invisible
1180 locations. As a consequence, Org always expose a neighborhood
1181 around point. How much is shown depends on the initial action,
1182 or context. Valid contexts are
1184 agenda when exposing an entry from the agenda
1185 org-goto when using the command `org-goto' (`\\[org-goto]')
1186 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1187 tags-tree when constructing a sparse tree based on tags matches
1188 link-search when exposing search matches associated with a link
1189 mark-goto when exposing the jump goal of a mark
1190 bookmark-jump when exposing a bookmark location
1191 isearch when exiting from an incremental search
1192 default default for all contexts not set explicitly
1194 Allowed visibility spans are
1196 minimal show current headline; if point is not on headline,
1197 also show entry
1199 local show current headline, entry and next headline
1201 ancestors show current headline and its direct ancestors; if
1202 point is not on headline, also show entry
1204 lineage show current headline, its direct ancestors and all
1205 their children; if point is not on headline, also show
1206 entry and first child
1208 tree show current headline, its direct ancestors and all
1209 their children; if point is not on headline, also show
1210 entry and all children
1212 canonical show current headline, its direct ancestors along with
1213 their entries and children; if point is not located on
1214 the headline, also show current entry and all children
1216 As special cases, a nil or t value means show all contexts in
1217 `minimal' or `canonical' view, respectively.
1219 Some views can make displayed information very compact, but also
1220 make it harder to edit the location of the match. In such
1221 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1222 more context."
1223 :group 'org-reveal-location
1224 :version "26.1"
1225 :package-version '(Org . "9.0")
1226 :type '(choice
1227 (const :tag "Canonical" t)
1228 (const :tag "Minimal" nil)
1229 (repeat :greedy t :tag "Individual contexts"
1230 (cons
1231 (choice :tag "Context"
1232 (const agenda)
1233 (const org-goto)
1234 (const occur-tree)
1235 (const tags-tree)
1236 (const link-search)
1237 (const mark-goto)
1238 (const bookmark-jump)
1239 (const isearch)
1240 (const default))
1241 (choice :tag "Detail level"
1242 (const minimal)
1243 (const local)
1244 (const ancestors)
1245 (const lineage)
1246 (const tree)
1247 (const canonical))))))
1249 (defcustom org-indirect-buffer-display 'other-window
1250 "How should indirect tree buffers be displayed?
1252 This applies to indirect buffers created with the commands
1253 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1255 Valid values are:
1256 current-window Display in the current window
1257 other-window Just display in another window.
1258 dedicated-frame Create one new frame, and re-use it each time.
1259 new-frame Make a new frame each time. Note that in this case
1260 previously-made indirect buffers are kept, and you need to
1261 kill these buffers yourself."
1262 :group 'org-structure
1263 :group 'org-agenda-windows
1264 :type '(choice
1265 (const :tag "In current window" current-window)
1266 (const :tag "In current frame, other window" other-window)
1267 (const :tag "Each time a new frame" new-frame)
1268 (const :tag "One dedicated frame" dedicated-frame)))
1270 (defcustom org-use-speed-commands nil
1271 "Non-nil means activate single letter commands at beginning of a headline.
1272 This may also be a function to test for appropriate locations where speed
1273 commands should be active.
1275 For example, to activate speed commands when the point is on any
1276 star at the beginning of the headline, you can do this:
1278 (setq org-use-speed-commands
1279 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1280 :group 'org-structure
1281 :type '(choice
1282 (const :tag "Never" nil)
1283 (const :tag "At beginning of headline stars" t)
1284 (function)))
1286 (defcustom org-speed-commands-user nil
1287 "Alist of additional speed commands.
1288 This list will be checked before `org-speed-commands-default'
1289 when the variable `org-use-speed-commands' is non-nil
1290 and when the cursor is at the beginning of a headline.
1291 The car of each entry is a string with a single letter, which must
1292 be assigned to `self-insert-command' in the global map.
1293 The cdr is either a command to be called interactively, a function
1294 to be called, or a form to be evaluated.
1295 An entry that is just a list with a single string will be interpreted
1296 as a descriptive headline that will be added when listing the speed
1297 commands in the Help buffer using the `?' speed command."
1298 :group 'org-structure
1299 :type '(repeat :value ("k" . ignore)
1300 (choice :value ("k" . ignore)
1301 (list :tag "Descriptive Headline" (string :tag "Headline"))
1302 (cons :tag "Letter and Command"
1303 (string :tag "Command letter")
1304 (choice
1305 (function)
1306 (sexp))))))
1308 (defcustom org-bookmark-names-plist
1309 '(:last-capture "org-capture-last-stored"
1310 :last-refile "org-refile-last-stored"
1311 :last-capture-marker "org-capture-last-stored-marker")
1312 "Names for bookmarks automatically set by some Org commands.
1313 This can provide strings as names for a number of bookmarks Org sets
1314 automatically. The following keys are currently implemented:
1315 :last-capture
1316 :last-capture-marker
1317 :last-refile
1318 When a key does not show up in the property list, the corresponding bookmark
1319 is not set."
1320 :group 'org-structure
1321 :type 'plist)
1323 (defgroup org-cycle nil
1324 "Options concerning visibility cycling in Org mode."
1325 :tag "Org Cycle"
1326 :group 'org-structure)
1328 (defcustom org-cycle-skip-children-state-if-no-children t
1329 "Non-nil means skip CHILDREN state in entries that don't have any."
1330 :group 'org-cycle
1331 :type 'boolean)
1333 (defcustom org-cycle-max-level nil
1334 "Maximum level which should still be subject to visibility cycling.
1335 Levels higher than this will, for cycling, be treated as text, not a headline.
1336 When `org-odd-levels-only' is set, a value of N in this variable actually
1337 means 2N-1 stars as the limiting headline.
1338 When nil, cycle all levels.
1339 Note that the limiting level of cycling is also influenced by
1340 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1341 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1342 than its value."
1343 :group 'org-cycle
1344 :type '(choice
1345 (const :tag "No limit" nil)
1346 (integer :tag "Maximum level")))
1348 (defcustom org-hide-block-startup nil
1349 "Non-nil means entering Org mode will fold all blocks.
1350 This can also be set in on a per-file basis with
1352 #+STARTUP: hideblocks
1353 #+STARTUP: showblocks"
1354 :group 'org-startup
1355 :group 'org-cycle
1356 :type 'boolean)
1358 (defcustom org-cycle-global-at-bob nil
1359 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1361 This makes it possible to do global cycling without having to use `S-TAB'
1362 or `\\[universal-argument] TAB'. For this special case to work, the first \
1363 line of the buffer
1364 must not be a headline -- it may be empty or some other text.
1366 When used in this way, `org-cycle-hook' is disabled temporarily to make
1367 sure the cursor stays at the beginning of the buffer.
1369 When this option is nil, don't do anything special at the beginning of
1370 the buffer."
1371 :group 'org-cycle
1372 :type 'boolean)
1374 (defcustom org-cycle-level-after-item/entry-creation t
1375 "Non-nil means cycle entry level or item indentation in new empty entries.
1377 When the cursor is at the end of an empty headline, i.e., with only stars
1378 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1379 and then all possible ancestor states, before returning to the original state.
1380 This makes data entry extremely fast: M-RET to create a new headline,
1381 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1383 When the cursor is at the end of an empty plain list item, one TAB will
1384 make it a subitem, two or more tabs will back up to make this an item
1385 higher up in the item hierarchy."
1386 :group 'org-cycle
1387 :type 'boolean)
1389 (defcustom org-cycle-emulate-tab t
1390 "Where should `org-cycle' emulate TAB.
1391 nil Never
1392 white Only in completely white lines
1393 whitestart Only at the beginning of lines, before the first non-white char
1394 t Everywhere except in headlines
1395 exc-hl-bol Everywhere except at the start of a headline
1396 If TAB is used in a place where it does not emulate TAB, the current subtree
1397 visibility is cycled."
1398 :group 'org-cycle
1399 :type '(choice (const :tag "Never" nil)
1400 (const :tag "Only in completely white lines" white)
1401 (const :tag "Before first char in a line" whitestart)
1402 (const :tag "Everywhere except in headlines" t)
1403 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1405 (defcustom org-cycle-separator-lines 2
1406 "Number of empty lines needed to keep an empty line between collapsed trees.
1407 If you leave an empty line between the end of a subtree and the following
1408 headline, this empty line is hidden when the subtree is folded.
1409 Org mode will leave (exactly) one empty line visible if the number of
1410 empty lines is equal or larger to the number given in this variable.
1411 So the default 2 means at least 2 empty lines after the end of a subtree
1412 are needed to produce free space between a collapsed subtree and the
1413 following headline.
1415 If the number is negative, and the number of empty lines is at least -N,
1416 all empty lines are shown.
1418 Special case: when 0, never leave empty lines in collapsed view."
1419 :group 'org-cycle
1420 :type 'integer)
1421 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1423 (defcustom org-pre-cycle-hook nil
1424 "Hook that is run before visibility cycling is happening.
1425 The function(s) in this hook must accept a single argument which indicates
1426 the new state that will be set right after running this hook. The
1427 argument is a symbol. Before a global state change, it can have the values
1428 `overview', `content', or `all'. Before a local state change, it can have
1429 the values `folded', `children', or `subtree'."
1430 :group 'org-cycle
1431 :type 'hook)
1433 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1434 org-cycle-show-empty-lines
1435 org-optimize-window-after-visibility-change)
1436 "Hook that is run after `org-cycle' has changed the buffer visibility.
1437 The function(s) in this hook must accept a single argument which indicates
1438 the new state that was set by the most recent `org-cycle' command. The
1439 argument is a symbol. After a global state change, it can have the values
1440 `overview', `contents', or `all'. After a local state change, it can have
1441 the values `folded', `children', or `subtree'."
1442 :group 'org-cycle
1443 :type 'hook
1444 :version "26.1"
1445 :package-version '(Org . "8.3"))
1447 (defgroup org-edit-structure nil
1448 "Options concerning structure editing in Org mode."
1449 :tag "Org Edit Structure"
1450 :group 'org-structure)
1452 (defcustom org-odd-levels-only nil
1453 "Non-nil means skip even levels and only use odd levels for the outline.
1454 This has the effect that two stars are being added/taken away in
1455 promotion/demotion commands. It also influences how levels are
1456 handled by the exporters.
1457 Changing it requires restart of `font-lock-mode' to become effective
1458 for fontification also in regions already fontified.
1459 You may also set this on a per-file basis by adding one of the following
1460 lines to the buffer:
1462 #+STARTUP: odd
1463 #+STARTUP: oddeven"
1464 :group 'org-edit-structure
1465 :group 'org-appearance
1466 :type 'boolean)
1468 (defcustom org-adapt-indentation t
1469 "Non-nil means adapt indentation to outline node level.
1471 When this variable is set, Org assumes that you write outlines by
1472 indenting text in each node to align with the headline (after the
1473 stars). The following issues are influenced by this variable:
1475 - The indentation is increased by one space in a demotion
1476 command, and decreased by one in a promotion command. However,
1477 in the latter case, if shifting some line in the entry body
1478 would alter document structure (e.g., insert a new headline),
1479 indentation is not changed at all.
1481 - Property drawers and planning information is inserted indented
1482 when this variable is set. When nil, they will not be indented.
1484 - TAB indents a line relative to current level. The lines below
1485 a headline will be indented when this variable is set.
1487 Note that this is all about true indentation, by adding and
1488 removing space characters. See also \"org-indent.el\" which does
1489 level-dependent indentation in a virtual way, i.e. at display
1490 time in Emacs."
1491 :group 'org-edit-structure
1492 :type 'boolean
1493 :safe #'booleanp)
1495 (defcustom org-special-ctrl-a/e nil
1496 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1498 When t, `C-a' will bring back the cursor to the beginning of the
1499 headline text, i.e. after the stars and after a possible TODO
1500 keyword. In an item, this will be the position after bullet and
1501 check-box, if any. When the cursor is already at that position,
1502 another `C-a' will bring it to the beginning of the line.
1504 `C-e' will jump to the end of the headline, ignoring the presence
1505 of tags in the headline. A second `C-e' will then jump to the
1506 true end of the line, after any tags. This also means that, when
1507 this variable is non-nil, `C-e' also will never jump beyond the
1508 end of the heading of a folded section, i.e. not after the
1509 ellipses.
1511 When set to the symbol `reversed', the first `C-a' or `C-e' works
1512 normally, going to the true line boundary first. Only a directly
1513 following, identical keypress will bring the cursor to the
1514 special positions.
1516 This may also be a cons cell where the behavior for `C-a' and
1517 `C-e' is set separately."
1518 :group 'org-edit-structure
1519 :type '(choice
1520 (const :tag "off" nil)
1521 (const :tag "on: after stars/bullet and before tags first" t)
1522 (const :tag "reversed: true line boundary first" reversed)
1523 (cons :tag "Set C-a and C-e separately"
1524 (choice :tag "Special C-a"
1525 (const :tag "off" nil)
1526 (const :tag "on: after stars/bullet first" t)
1527 (const :tag "reversed: before stars/bullet first" reversed))
1528 (choice :tag "Special C-e"
1529 (const :tag "off" nil)
1530 (const :tag "on: before tags first" t)
1531 (const :tag "reversed: after tags first" reversed)))))
1532 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1534 (defcustom org-special-ctrl-k nil
1535 "Non-nil means `C-k' will behave specially in headlines.
1536 When nil, `C-k' will call the default `kill-line' command.
1537 When t, the following will happen while the cursor is in the headline:
1539 - When the cursor is at the beginning of a headline, kill the entire
1540 line and possible the folded subtree below the line.
1541 - When in the middle of the headline text, kill the headline up to the tags.
1542 - When after the headline text, kill the tags."
1543 :group 'org-edit-structure
1544 :type 'boolean)
1546 (defcustom org-ctrl-k-protect-subtree nil
1547 "Non-nil means, do not delete a hidden subtree with C-k.
1548 When set to the symbol `error', simply throw an error when C-k is
1549 used to kill (part-of) a headline that has hidden text behind it.
1550 Any other non-nil value will result in a query to the user, if it is
1551 OK to kill that hidden subtree. When nil, kill without remorse."
1552 :group 'org-edit-structure
1553 :version "24.1"
1554 :type '(choice
1555 (const :tag "Do not protect hidden subtrees" nil)
1556 (const :tag "Protect hidden subtrees with a security query" t)
1557 (const :tag "Never kill a hidden subtree with C-k" error)))
1559 (defcustom org-special-ctrl-o t
1560 "Non-nil means, make `C-o' insert a row in tables."
1561 :group 'org-edit-structure
1562 :type 'boolean)
1564 (defcustom org-catch-invisible-edits nil
1565 "Check if in invisible region before inserting or deleting a character.
1566 Valid values are:
1568 nil Do not check, so just do invisible edits.
1569 error Throw an error and do nothing.
1570 show Make point visible, and do the requested edit.
1571 show-and-error Make point visible, then throw an error and abort the edit.
1572 smart Make point visible, and do insertion/deletion if it is
1573 adjacent to visible text and the change feels predictable.
1574 Never delete a previously invisible character or add in the
1575 middle or right after an invisible region. Basically, this
1576 allows insertion and backward-delete right before ellipses.
1577 FIXME: maybe in this case we should not even show?"
1578 :group 'org-edit-structure
1579 :version "24.1"
1580 :type '(choice
1581 (const :tag "Do not check" nil)
1582 (const :tag "Throw error when trying to edit" error)
1583 (const :tag "Unhide, but do not do the edit" show-and-error)
1584 (const :tag "Show invisible part and do the edit" show)
1585 (const :tag "Be smart and do the right thing" smart)))
1587 (defcustom org-yank-folded-subtrees t
1588 "Non-nil means when yanking subtrees, fold them.
1589 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1590 it starts with a heading and all other headings in it are either children
1591 or siblings, then fold all the subtrees. However, do this only if no
1592 text after the yank would be swallowed into a folded tree by this action."
1593 :group 'org-edit-structure
1594 :type 'boolean)
1596 (defcustom org-yank-adjusted-subtrees nil
1597 "Non-nil means when yanking subtrees, adjust the level.
1598 With this setting, `org-paste-subtree' is used to insert the subtree, see
1599 this function for details."
1600 :group 'org-edit-structure
1601 :type 'boolean)
1603 (defcustom org-M-RET-may-split-line '((default . t))
1604 "Non-nil means M-RET will split the line at the cursor position.
1605 When nil, it will go to the end of the line before making a
1606 new line.
1607 You may also set this option in a different way for different
1608 contexts. Valid contexts are:
1610 headline when creating a new headline
1611 item when creating a new item
1612 table in a table field
1613 default the value to be used for all contexts not explicitly
1614 customized"
1615 :group 'org-structure
1616 :group 'org-table
1617 :type '(choice
1618 (const :tag "Always" t)
1619 (const :tag "Never" nil)
1620 (repeat :greedy t :tag "Individual contexts"
1621 (cons
1622 (choice :tag "Context"
1623 (const headline)
1624 (const item)
1625 (const table)
1626 (const default))
1627 (boolean)))))
1630 (defcustom org-insert-heading-respect-content nil
1631 "Non-nil means insert new headings after the current subtree.
1632 \\<org-mode-map>
1633 When nil, the new heading is created directly after the current line.
1634 The commands `\\[org-insert-heading-respect-content]' and \
1635 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1636 for the duration of the command."
1637 :group 'org-structure
1638 :type 'boolean)
1640 (defcustom org-blank-before-new-entry '((heading . auto)
1641 (plain-list-item . auto))
1642 "Should `org-insert-heading' leave a blank line before new heading/item?
1643 The value is an alist, with `heading' and `plain-list-item' as CAR,
1644 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1645 which case Org will look at the surrounding headings/items and try to
1646 make an intelligent decision whether to insert a blank line or not."
1647 :group 'org-edit-structure
1648 :type '(list
1649 (cons (const heading)
1650 (choice (const :tag "Never" nil)
1651 (const :tag "Always" t)
1652 (const :tag "Auto" auto)))
1653 (cons (const plain-list-item)
1654 (choice (const :tag "Never" nil)
1655 (const :tag "Always" t)
1656 (const :tag "Auto" auto)))))
1658 (defcustom org-insert-heading-hook nil
1659 "Hook being run after inserting a new heading."
1660 :group 'org-edit-structure
1661 :type 'hook)
1663 (defcustom org-enable-fixed-width-editor t
1664 "Non-nil means lines starting with \":\" are treated as fixed-width.
1665 This currently only means they are never auto-wrapped.
1666 When nil, such lines will be treated like ordinary lines."
1667 :group 'org-edit-structure
1668 :type 'boolean)
1670 (defgroup org-sparse-trees nil
1671 "Options concerning sparse trees in Org mode."
1672 :tag "Org Sparse Trees"
1673 :group 'org-structure)
1675 (defcustom org-highlight-sparse-tree-matches t
1676 "Non-nil means highlight all matches that define a sparse tree.
1677 The highlights will automatically disappear the next time the buffer is
1678 changed by an edit command."
1679 :group 'org-sparse-trees
1680 :type 'boolean)
1682 (defcustom org-remove-highlights-with-change t
1683 "Non-nil means any change to the buffer will remove temporary highlights.
1684 \\<org-mode-map>\
1685 Such highlights are created by `org-occur' and `org-clock-display'.
1686 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1687 to get rid of the highlights.
1688 The highlights created by `org-toggle-latex-fragment' always need
1689 `\\[org-toggle-latex-fragment]' to be removed."
1690 :group 'org-sparse-trees
1691 :group 'org-time
1692 :type 'boolean)
1694 (defcustom org-occur-case-fold-search t
1695 "Non-nil means `org-occur' should be case-insensitive.
1696 If set to `smart' the search will be case-insensitive only if it
1697 doesn't specify any upper case character."
1698 :group 'org-sparse-trees
1699 :version "26.1"
1700 :type '(choice
1701 (const :tag "Case-sensitive" nil)
1702 (const :tag "Case-insensitive" t)
1703 (const :tag "Case-insensitive for lower case searches only" smart)))
1705 (defcustom org-occur-hook '(org-first-headline-recenter)
1706 "Hook that is run after `org-occur' has constructed a sparse tree.
1707 This can be used to recenter the window to show as much of the structure
1708 as possible."
1709 :group 'org-sparse-trees
1710 :type 'hook)
1712 (defgroup org-table nil
1713 "Options concerning tables in Org mode."
1714 :tag "Org Table"
1715 :group 'org)
1717 (defcustom org-self-insert-cluster-for-undo nil
1718 "Non-nil means cluster self-insert commands for undo when possible.
1719 If this is set, then, like in the Emacs command loop, 20 consecutive
1720 characters will be undone together.
1721 This is configurable, because there is some impact on typing performance."
1722 :group 'org-table
1723 :type 'boolean)
1725 (defcustom org-table-tab-recognizes-table.el t
1726 "Non-nil means TAB will automatically notice a table.el table.
1727 When it sees such a table, it moves point into it and - if necessary -
1728 calls `table-recognize-table'."
1729 :group 'org-table-editing
1730 :type 'boolean)
1732 (defgroup org-link nil
1733 "Options concerning links in Org mode."
1734 :tag "Org Link"
1735 :group 'org)
1737 (defvar-local org-link-abbrev-alist-local nil
1738 "Buffer-local version of `org-link-abbrev-alist', which see.
1739 The value of this is taken from the #+LINK lines.")
1741 (defcustom org-link-parameters
1742 '(("doi" :follow org--open-doi-link)
1743 ("elisp" :follow org--open-elisp-link)
1744 ("file" :complete org-file-complete-link)
1745 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1746 ("help" :follow org--open-help-link)
1747 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1748 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1749 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1750 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1751 ("shell" :follow org--open-shell-link))
1752 "An alist of properties that defines all the links in Org mode.
1753 The key in each association is a string of the link type.
1754 Subsequent optional elements make up a p-list of link properties.
1756 :follow - A function that takes the link path as an argument.
1758 :export - A function that takes the link path, description and
1759 export-backend as arguments.
1761 :store - A function responsible for storing the link. See the
1762 function `org-store-link-functions'.
1764 :complete - A function that inserts a link with completion. The
1765 function takes one optional prefix arg.
1767 :face - A face for the link, or a function that returns a face.
1768 The function takes one argument which is the link path. The
1769 default face is `org-link'.
1771 :mouse-face - The mouse-face. The default is `highlight'.
1773 :display - `full' will not fold the link in descriptive
1774 display. Default is `org-link'.
1776 :help-echo - A string or function that takes (window object position)
1777 as arguments and returns a string.
1779 :keymap - A keymap that is active on the link. The default is
1780 `org-mouse-map'.
1782 :htmlize-link - A function for the htmlize-link. Defaults
1783 to (list :uri \"type:path\")
1785 :activate-func - A function to run at the end of font-lock
1786 activation. The function must accept (link-start link-end path bracketp)
1787 as arguments."
1788 :group 'org-link
1789 :type '(alist :tag "Link display parameters"
1790 :value-type plist)
1791 :version "26.1"
1792 :package-version '(Org . "9.1"))
1794 (defun org-link-get-parameter (type key)
1795 "Get TYPE link property for KEY.
1796 TYPE is a string and KEY is a plist keyword."
1797 (plist-get
1798 (cdr (assoc type org-link-parameters))
1799 key))
1801 (defun org-link-set-parameters (type &rest parameters)
1802 "Set link TYPE properties to PARAMETERS.
1803 PARAMETERS should be :key val pairs."
1804 (let ((data (assoc type org-link-parameters)))
1805 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1806 (push (cons type parameters) org-link-parameters)
1807 (org-make-link-regexps)
1808 (org-element-update-syntax))))
1810 (defun org-link-types ()
1811 "Return a list of known link types."
1812 (mapcar #'car org-link-parameters))
1814 (defcustom org-link-abbrev-alist nil
1815 "Alist of link abbreviations.
1816 The car of each element is a string, to be replaced at the start of a link.
1817 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1818 links in Org buffers can have an optional tag after a double colon, e.g.,
1820 [[linkkey:tag][description]]
1822 The `linkkey' must be a single word, starting with a letter, followed
1823 by letters, numbers, `-' or `_'.
1825 If REPLACE is a string, the tag will simply be appended to create the link.
1826 If the string contains \"%s\", the tag will be inserted there. If the string
1827 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1828 at that point (see the function `url-hexify-string'). If the string contains
1829 the specifier \"%(my-function)\", then the custom function `my-function' will
1830 be invoked: this function takes the tag as its only argument and must return
1831 a string.
1833 REPLACE may also be a function that will be called with the tag as the
1834 only argument to create the link, which should be returned as a string.
1836 See the manual for examples."
1837 :group 'org-link
1838 :type '(repeat
1839 (cons
1840 (string :tag "Protocol")
1841 (choice
1842 (string :tag "Format")
1843 (function)))))
1845 (defcustom org-descriptive-links t
1846 "Non-nil means Org will display descriptive links.
1847 E.g. [[https://orgmode.org][Org website]] will be displayed as
1848 \"Org Website\", hiding the link itself and just displaying its
1849 description. When set to nil, Org will display the full links
1850 literally.
1852 You can interactively set the value of this variable by calling
1853 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1854 :group 'org-link
1855 :type 'boolean)
1857 (defcustom org-link-file-path-type 'adaptive
1858 "How the path name in file links should be stored.
1859 Valid values are:
1861 relative Relative to the current directory, i.e. the directory of the file
1862 into which the link is being inserted.
1863 absolute Absolute path, if possible with ~ for home directory.
1864 noabbrev Absolute path, no abbreviation of home directory.
1865 adaptive Use relative path for files in the current directory and sub-
1866 directories of it. For other files, use an absolute path."
1867 :group 'org-link
1868 :type '(choice
1869 (const relative)
1870 (const absolute)
1871 (const noabbrev)
1872 (const adaptive)))
1874 (defvaralias 'org-activate-links 'org-highlight-links)
1875 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1876 "Types of links that should be highlighted in Org files.
1878 This is a list of symbols, each one of them leading to the
1879 highlighting of a certain link type.
1881 You can still open links that are not highlighted.
1883 In principle, it does not hurt to turn on highlighting for all
1884 link types. There may be a small gain when turning off unused
1885 link types. The types are:
1887 bracket The recommended [[link][description]] or [[link]] links with hiding.
1888 angle Links in angular brackets that may contain whitespace like
1889 <bbdb:Carsten Dominik>.
1890 plain Plain links in normal text, no whitespace, like http://google.com.
1891 radio Text that is matched by a radio target, see manual for details.
1892 tag Tag settings in a headline (link to tag search).
1893 date Time stamps (link to calendar).
1894 footnote Footnote labels.
1896 If you set this variable during an Emacs session, use `org-mode-restart'
1897 in the Org buffer so that the change takes effect."
1898 :group 'org-link
1899 :group 'org-appearance
1900 :type '(set :greedy t
1901 (const :tag "Double bracket links" bracket)
1902 (const :tag "Angular bracket links" angle)
1903 (const :tag "Plain text links" plain)
1904 (const :tag "Radio target matches" radio)
1905 (const :tag "Tags" tag)
1906 (const :tag "Timestamps" date)
1907 (const :tag "Footnotes" footnote)))
1909 (defcustom org-make-link-description-function nil
1910 "Function to use for generating link descriptions from links.
1911 This function must take two parameters: the first one is the
1912 link, the second one is the description generated by
1913 `org-insert-link'. The function should return the description to
1914 use."
1915 :group 'org-link
1916 :type '(choice (const nil) (function)))
1918 (defgroup org-link-store nil
1919 "Options concerning storing links in Org mode."
1920 :tag "Org Store Link"
1921 :group 'org-link)
1923 (defcustom org-url-hexify-p t
1924 "When non-nil, hexify URL when creating a link."
1925 :type 'boolean
1926 :version "24.3"
1927 :group 'org-link-store)
1929 (defcustom org-email-link-description-format "Email %c: %.30s"
1930 "Format of the description part of a link to an email or usenet message.
1931 The following %-escapes will be replaced by corresponding information:
1933 %F full \"From\" field
1934 %f name, taken from \"From\" field, address if no name
1935 %T full \"To\" field
1936 %t first name in \"To\" field, address if no name
1937 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1938 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1939 %s subject
1940 %d date
1941 %m message-id.
1943 You may use normal field width specification between the % and the letter.
1944 This is for example useful to limit the length of the subject.
1946 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1947 :group 'org-link-store
1948 :type 'string)
1950 (defcustom org-from-is-user-regexp
1951 (let (r1 r2)
1952 (when (and user-mail-address (not (string= user-mail-address "")))
1953 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1954 (when (and user-full-name (not (string= user-full-name "")))
1955 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1956 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1957 "Regexp matched against the \"From:\" header of an email or usenet message.
1958 It should match if the message is from the user him/herself."
1959 :group 'org-link-store
1960 :type 'regexp)
1962 (defcustom org-context-in-file-links t
1963 "Non-nil means file links from `org-store-link' contain context.
1964 \\<org-mode-map>
1965 A search string will be added to the file name with :: as separator
1966 and used to find the context when the link is activated by the command
1967 `org-open-at-point'. When this option is t, the entire active region
1968 will be placed in the search string of the file link. If set to a
1969 positive integer, only the first n lines of context will be stored.
1971 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1972 \\[org-store-link]')
1973 negates this setting for the duration of the command."
1974 :group 'org-link-store
1975 :type '(choice boolean integer))
1977 (defcustom org-keep-stored-link-after-insertion nil
1978 "Non-nil means keep link in list for entire session.
1979 \\<org-mode-map>
1980 The command `org-store-link' adds a link pointing to the current
1981 location to an internal list. These links accumulate during a session.
1982 The command `org-insert-link' can be used to insert links into any
1983 Org file (offering completion for all stored links).
1985 When this option is nil, every link which has been inserted once using
1986 `\\[org-insert-link]' will be removed from the list, to make completing the \
1987 unused
1988 links more efficient."
1989 :group 'org-link-store
1990 :type 'boolean)
1992 (defgroup org-link-follow nil
1993 "Options concerning following links in Org mode."
1994 :tag "Org Follow Link"
1995 :group 'org-link)
1997 (defcustom org-link-translation-function nil
1998 "Function to translate links with different syntax to Org syntax.
1999 This can be used to translate links created for example by the Planner
2000 or emacs-wiki packages to Org syntax.
2001 The function must accept two parameters, a TYPE containing the link
2002 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2003 which is everything after the link protocol. It should return a cons
2004 with possibly modified values of type and path.
2005 Org contains a function for this, so if you set this variable to
2006 `org-translate-link-from-planner', you should be able follow many
2007 links created by planner."
2008 :group 'org-link-follow
2009 :type '(choice (const nil) (function)))
2011 (defcustom org-follow-link-hook nil
2012 "Hook that is run after a link has been followed."
2013 :group 'org-link-follow
2014 :type 'hook)
2016 (defcustom org-tab-follows-link nil
2017 "Non-nil means on links TAB will follow the link.
2018 Needs to be set before org.el is loaded.
2019 This really should not be used, it does not make sense, and the
2020 implementation is bad."
2021 :group 'org-link-follow
2022 :type 'boolean)
2024 (defcustom org-return-follows-link nil
2025 "Non-nil means on links RET will follow the link.
2026 In tables, the special behavior of RET has precedence."
2027 :group 'org-link-follow
2028 :type 'boolean)
2030 (defcustom org-mouse-1-follows-link
2031 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2032 "Non-nil means mouse-1 on a link will follow the link.
2033 A longer mouse click will still set point. Needs to be set
2034 before org.el is loaded."
2035 :group 'org-link-follow
2036 :version "26.1"
2037 :package-version '(Org . "8.3")
2038 :type '(choice
2039 (const :tag "A double click follows the link" double)
2040 (const :tag "Unconditionally follow the link with mouse-1" t)
2041 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2043 (defcustom org-mark-ring-length 4
2044 "Number of different positions to be recorded in the ring.
2045 Changing this requires a restart of Emacs to work correctly."
2046 :group 'org-link-follow
2047 :type 'integer)
2049 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2050 "Non-nil means internal fuzzy links can only match headlines.
2052 When nil, the a fuzzy link may point to a target or a named
2053 construct in the document. When set to the special value
2054 `query-to-create', offer to create a new headline when none
2055 matched.
2057 Spaces and statistics cookies are ignored during heading searches."
2058 :group 'org-link-follow
2059 :version "24.1"
2060 :type '(choice
2061 (const :tag "Use fuzzy text search" nil)
2062 (const :tag "Match only exact headline" t)
2063 (const :tag "Match exact headline or query to create it"
2064 query-to-create))
2065 :safe #'symbolp)
2067 (defcustom org-link-frame-setup
2068 '((vm . vm-visit-folder-other-frame)
2069 (vm-imap . vm-visit-imap-folder-other-frame)
2070 (gnus . org-gnus-no-new-news)
2071 (file . find-file-other-window)
2072 (wl . wl-other-frame))
2073 "Setup the frame configuration for following links.
2074 When following a link with Emacs, it may often be useful to display
2075 this link in another window or frame. This variable can be used to
2076 set this up for the different types of links.
2077 For VM, use any of
2078 `vm-visit-folder'
2079 `vm-visit-folder-other-window'
2080 `vm-visit-folder-other-frame'
2081 For Gnus, use any of
2082 `gnus'
2083 `gnus-other-frame'
2084 `org-gnus-no-new-news'
2085 For FILE, use any of
2086 `find-file'
2087 `find-file-other-window'
2088 `find-file-other-frame'
2089 For Wanderlust use any of
2090 `wl'
2091 `wl-other-frame'
2092 For the calendar, use the variable `calendar-setup'.
2093 For BBDB, it is currently only possible to display the matches in
2094 another window."
2095 :group 'org-link-follow
2096 :type '(list
2097 (cons (const vm)
2098 (choice
2099 (const vm-visit-folder)
2100 (const vm-visit-folder-other-window)
2101 (const vm-visit-folder-other-frame)))
2102 (cons (const vm-imap)
2103 (choice
2104 (const vm-visit-imap-folder)
2105 (const vm-visit-imap-folder-other-window)
2106 (const vm-visit-imap-folder-other-frame)))
2107 (cons (const gnus)
2108 (choice
2109 (const gnus)
2110 (const gnus-other-frame)
2111 (const org-gnus-no-new-news)))
2112 (cons (const file)
2113 (choice
2114 (const find-file)
2115 (const find-file-other-window)
2116 (const find-file-other-frame)))
2117 (cons (const wl)
2118 (choice
2119 (const wl)
2120 (const wl-other-frame)))))
2122 (defcustom org-display-internal-link-with-indirect-buffer nil
2123 "Non-nil means use indirect buffer to display infile links.
2124 Activating internal links (from one location in a file to another location
2125 in the same file) normally just jumps to the location. When the link is
2126 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2127 is displayed in
2128 another window. When this option is set, the other window actually displays
2129 an indirect buffer clone of the current buffer, to avoid any visibility
2130 changes to the current buffer."
2131 :group 'org-link-follow
2132 :type 'boolean)
2134 (defcustom org-open-non-existing-files nil
2135 "Non-nil means `org-open-file' will open non-existing files.
2136 When nil, an error will be generated.
2137 This variable applies only to external applications because they
2138 might choke on non-existing files. If the link is to a file that
2139 will be opened in Emacs, the variable is ignored."
2140 :group 'org-link-follow
2141 :type 'boolean)
2143 (defcustom org-open-directory-means-index-dot-org nil
2144 "Non-nil means a link to a directory really means to index.org.
2145 When nil, following a directory link will run dired or open a finder/explorer
2146 window on that directory."
2147 :group 'org-link-follow
2148 :type 'boolean)
2150 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2151 "Non-nil means ask for confirmation before executing shell links.
2152 Shell links can be dangerous: just think about a link
2154 [[shell:rm -rf ~/*][Google Search]]
2156 This link would show up in your Org document as \"Google Search\",
2157 but really it would remove your entire home directory.
2158 Therefore we advise against setting this variable to nil.
2159 Just change it to `y-or-n-p' if you want to confirm with a
2160 single keystroke rather than having to type \"yes\"."
2161 :group 'org-link-follow
2162 :type '(choice
2163 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2164 (const :tag "with y-or-n (faster)" y-or-n-p)
2165 (const :tag "no confirmation (dangerous)" nil)))
2166 (put 'org-confirm-shell-link-function
2167 'safe-local-variable
2168 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2170 (defcustom org-confirm-shell-link-not-regexp ""
2171 "A regexp to skip confirmation for shell links."
2172 :group 'org-link-follow
2173 :version "24.1"
2174 :type 'regexp)
2176 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2177 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2178 Elisp links can be dangerous: just think about a link
2180 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2182 This link would show up in your Org document as \"Google Search\",
2183 but really it would remove your entire home directory.
2184 Therefore we advise against setting this variable to nil.
2185 Just change it to `y-or-n-p' if you want to confirm with a
2186 single keystroke rather than having to type \"yes\"."
2187 :group 'org-link-follow
2188 :type '(choice
2189 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2190 (const :tag "with y-or-n (faster)" y-or-n-p)
2191 (const :tag "no confirmation (dangerous)" nil)))
2192 (put 'org-confirm-shell-link-function
2193 'safe-local-variable
2194 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2196 (defcustom org-confirm-elisp-link-not-regexp ""
2197 "A regexp to skip confirmation for Elisp links."
2198 :group 'org-link-follow
2199 :version "24.1"
2200 :type 'regexp)
2202 (defconst org-file-apps-defaults-gnu
2203 '((remote . emacs)
2204 (system . mailcap)
2205 (t . mailcap))
2206 "Default file applications on a UNIX or GNU/Linux system.
2207 See `org-file-apps'.")
2209 (defconst org-file-apps-defaults-macosx
2210 '((remote . emacs)
2211 (system . "open %s")
2212 ("ps.gz" . "gv %s")
2213 ("eps.gz" . "gv %s")
2214 ("dvi" . "xdvi %s")
2215 ("fig" . "xfig %s")
2216 (t . "open %s"))
2217 "Default file applications on a macOS system.
2218 The system \"open\" is known as a default, but we use X11 applications
2219 for some files for which the OS does not have a good default.
2220 See `org-file-apps'.")
2222 (defconst org-file-apps-defaults-windowsnt
2223 (list '(remote . emacs)
2224 (cons 'system (lambda (file _path)
2225 (with-no-warnings (w32-shell-execute "open" file))))
2226 (cons t (lambda (file _path)
2227 (with-no-warnings (w32-shell-execute "open" file)))))
2228 "Default file applications on a Windows NT system.
2229 The system \"open\" is used for most files.
2230 See `org-file-apps'.")
2232 (defcustom org-file-apps
2233 '((auto-mode . emacs)
2234 ("\\.mm\\'" . default)
2235 ("\\.x?html?\\'" . default)
2236 ("\\.pdf\\'" . default))
2237 "External applications for opening `file:path' items in a document.
2238 \\<org-mode-map>\
2240 Org mode uses system defaults for different file types, but
2241 you can use this variable to set the application for a given file
2242 extension. The entries in this list are cons cells where the car identifies
2243 files and the cdr the corresponding command.
2245 Possible values for the file identifier are:
2247 \"string\" A string as a file identifier can be interpreted in different
2248 ways, depending on its contents:
2250 - Alphanumeric characters only:
2251 Match links with this file extension.
2252 Example: (\"pdf\" . \"evince %s\")
2253 to open PDFs with evince.
2255 - Regular expression: Match links where the
2256 filename matches the regexp. If you want to
2257 use groups here, use shy groups.
2259 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2260 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2261 to open *.html and *.xhtml with firefox.
2263 - Regular expression which contains (non-shy) groups:
2264 Match links where the whole link, including \"::\", and
2265 anything after that, matches the regexp.
2266 In a custom command string, %1, %2, etc. are replaced with
2267 the parts of the link that were matched by the groups.
2268 For backwards compatibility, if a command string is given
2269 that does not use any of the group matches, this case is
2270 handled identically to the second one (i.e. match against
2271 file name only).
2272 In a custom function, you can access the group matches with
2273 (match-string n link).
2275 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2276 \"evince -p %1 %s\")
2277 to open [[file:document.pdf::5]] with evince at page 5.
2279 `directory' Matches a directory
2280 `remote' Matches a remote file, accessible through tramp or efs.
2281 Remote files most likely should be visited through Emacs
2282 because external applications cannot handle such paths.
2283 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2284 so all files Emacs knows how to handle. Using this with
2285 command `emacs' will open most files in Emacs. Beware that this
2286 will also open html files inside Emacs, unless you add
2287 (\"html\" . default) to the list as well.
2288 `system' The system command to open files, like `open' on Windows
2289 and macOS, and mailcap under GNU/Linux. This is the command
2290 that will be selected if you call `org-open-at-point' with a
2291 double prefix argument (`\\[universal-argument] \
2292 \\[universal-argument] \\[org-open-at-point]').
2293 t Default for files not matched by any of the other options.
2295 Possible values for the command are:
2297 `emacs' The file will be visited by the current Emacs process.
2298 `default' Use the default application for this file type, which is the
2299 association for t in the list, most likely in the system-specific
2300 part. This can be used to overrule an unwanted setting in the
2301 system-specific variable.
2302 `system' Use the system command for opening files, like \"open\".
2303 This command is specified by the entry whose car is `system'.
2304 Most likely, the system-specific version of this variable
2305 does define this command, but you can overrule/replace it
2306 here.
2307 `mailcap' Use command specified in the mailcaps.
2308 string A command to be executed by a shell; %s will be replaced
2309 by the path to the file.
2310 function A Lisp function, which will be called with two arguments:
2311 the file path and the original link string, without the
2312 \"file:\" prefix.
2314 For more examples, see the system specific constants
2315 `org-file-apps-defaults-macosx'
2316 `org-file-apps-defaults-windowsnt'
2317 `org-file-apps-defaults-gnu'."
2318 :group 'org-link-follow
2319 :type '(repeat
2320 (cons (choice :value ""
2321 (string :tag "Extension")
2322 (const :tag "System command to open files" system)
2323 (const :tag "Default for unrecognized files" t)
2324 (const :tag "Remote file" remote)
2325 (const :tag "Links to a directory" directory)
2326 (const :tag "Any files that have Emacs modes"
2327 auto-mode))
2328 (choice :value ""
2329 (const :tag "Visit with Emacs" emacs)
2330 (const :tag "Use default" default)
2331 (const :tag "Use the system command" system)
2332 (string :tag "Command")
2333 (function :tag "Function")))))
2335 (defcustom org-doi-server-url "http://dx.doi.org/"
2336 "The URL of the DOI server."
2337 :type 'string
2338 :version "24.3"
2339 :group 'org-link-follow)
2341 (defgroup org-refile nil
2342 "Options concerning refiling entries in Org mode."
2343 :tag "Org Refile"
2344 :group 'org)
2346 (defcustom org-directory "~/org"
2347 "Directory with Org files.
2348 This is just a default location to look for Org files. There is no need
2349 at all to put your files into this directory. It is used in the
2350 following situations:
2352 1. When a capture template specifies a target file that is not an
2353 absolute path. The path will then be interpreted relative to
2354 `org-directory'
2355 2. When the value of variable `org-agenda-files' is a single file, any
2356 relative paths in this file will be taken as relative to
2357 `org-directory'."
2358 :group 'org-refile
2359 :group 'org-capture
2360 :type 'directory)
2362 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2363 "Default target for storing notes.
2364 Used as a fall back file for org-capture.el, for templates that
2365 do not specify a target file."
2366 :group 'org-refile
2367 :group 'org-capture
2368 :type 'file)
2370 (defcustom org-reverse-note-order nil
2371 "Non-nil means store new notes at the beginning of a file or entry.
2372 When nil, new notes will be filed to the end of a file or entry.
2373 This can also be a list with cons cells of regular expressions that
2374 are matched against file names, and values."
2375 :group 'org-capture
2376 :group 'org-refile
2377 :type '(choice
2378 (const :tag "Reverse always" t)
2379 (const :tag "Reverse never" nil)
2380 (repeat :tag "By file name regexp"
2381 (cons regexp boolean))))
2383 (defcustom org-log-refile nil
2384 "Information to record when a task is refiled.
2386 Possible values are:
2388 nil Don't add anything
2389 time Add a time stamp to the task
2390 note Prompt for a note and add it with template `org-log-note-headings'
2392 This option can also be set with on a per-file-basis with
2394 #+STARTUP: nologrefile
2395 #+STARTUP: logrefile
2396 #+STARTUP: lognoterefile
2398 You can have local logging settings for a subtree by setting the LOGGING
2399 property to one or more of these keywords.
2401 When bulk-refiling from the agenda, the value `note' is forbidden and
2402 will temporarily be changed to `time'."
2403 :group 'org-refile
2404 :group 'org-progress
2405 :version "24.1"
2406 :type '(choice
2407 (const :tag "No logging" nil)
2408 (const :tag "Record timestamp" time)
2409 (const :tag "Record timestamp with note." note)))
2411 (defcustom org-refile-targets nil
2412 "Targets for refiling entries with `\\[org-refile]'.
2413 This is a list of cons cells. Each cell contains:
2414 - a specification of the files to be considered, either a list of files,
2415 or a symbol whose function or variable value will be used to retrieve
2416 a file name or a list of file names. If you use `org-agenda-files' for
2417 that, all agenda files will be scanned for targets. Nil means consider
2418 headings in the current buffer.
2419 - A specification of how to find candidate refile targets. This may be
2420 any of:
2421 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2422 This tag has to be present in all target headlines, inheritance will
2423 not be considered.
2424 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2425 todo keyword.
2426 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2427 headlines that are refiling targets.
2428 - a cons cell (:level . N). Any headline of level N is considered a target.
2429 Note that, when `org-odd-levels-only' is set, level corresponds to
2430 order in hierarchy, not to the number of stars.
2431 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2432 Note that, when `org-odd-levels-only' is set, level corresponds to
2433 order in hierarchy, not to the number of stars.
2435 Each element of this list generates a set of possible targets.
2436 The union of these sets is presented (with completion) to
2437 the user by `org-refile'.
2439 You can set the variable `org-refile-target-verify-function' to a function
2440 to verify each headline found by the simple criteria above.
2442 When this variable is nil, all top-level headlines in the current buffer
2443 are used, equivalent to the value `((nil . (:level . 1))'."
2444 :group 'org-refile
2445 :type '(repeat
2446 (cons
2447 (choice :value org-agenda-files
2448 (const :tag "All agenda files" org-agenda-files)
2449 (const :tag "Current buffer" nil)
2450 (function) (variable) (file))
2451 (choice :tag "Identify target headline by"
2452 (cons :tag "Specific tag" (const :value :tag) (string))
2453 (cons :tag "TODO keyword" (const :value :todo) (string))
2454 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2455 (cons :tag "Level number" (const :value :level) (integer))
2456 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2458 (defcustom org-refile-target-verify-function nil
2459 "Function to verify if the headline at point should be a refile target.
2460 The function will be called without arguments, with point at the
2461 beginning of the headline. It should return t and leave point
2462 where it is if the headline is a valid target for refiling.
2464 If the target should not be selected, the function must return nil.
2465 In addition to this, it may move point to a place from where the search
2466 should be continued. For example, the function may decide that the entire
2467 subtree of the current entry should be excluded and move point to the end
2468 of the subtree."
2469 :group 'org-refile
2470 :type '(choice
2471 (const nil)
2472 (function)))
2474 (defcustom org-refile-use-cache nil
2475 "Non-nil means cache refile targets to speed up the process.
2476 \\<org-mode-map>\
2477 The cache for a particular file will be updated automatically when
2478 the buffer has been killed, or when any of the marker used for flagging
2479 refile targets no longer points at a live buffer.
2480 If you have added new entries to a buffer that might themselves be targets,
2481 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2482 if you find that easier, \
2483 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2484 \\[org-refile]'."
2485 :group 'org-refile
2486 :version "24.1"
2487 :type 'boolean)
2489 (defcustom org-refile-use-outline-path nil
2490 "Non-nil means provide refile targets as paths.
2491 So a level 3 headline will be available as level1/level2/level3.
2493 When the value is `file', also include the file name (without directory)
2494 into the path. In this case, you can also stop the completion after
2495 the file name, to get entries inserted as top level in the file.
2497 When `full-file-path', include the full file path.
2499 When `buffer-name', use the buffer name."
2500 :group 'org-refile
2501 :type '(choice
2502 (const :tag "Not" nil)
2503 (const :tag "Yes" t)
2504 (const :tag "Start with file name" file)
2505 (const :tag "Start with full file path" full-file-path)
2506 (const :tag "Start with buffer name" buffer-name)))
2508 (defcustom org-outline-path-complete-in-steps t
2509 "Non-nil means complete the outline path in hierarchical steps.
2510 When Org uses the refile interface to select an outline path (see
2511 `org-refile-use-outline-path'), the completion of the path can be
2512 done in a single go, or it can be done in steps down the headline
2513 hierarchy. Going in steps is probably the best if you do not use
2514 a special completion package like `ido' or `icicles'. However,
2515 when using these packages, going in one step can be very fast,
2516 while still showing the whole path to the entry."
2517 :group 'org-refile
2518 :type 'boolean)
2520 (defcustom org-refile-allow-creating-parent-nodes nil
2521 "Non-nil means allow the creation of new nodes as refile targets.
2522 New nodes are then created by adding \"/new node name\" to the completion
2523 of an existing node. When the value of this variable is `confirm',
2524 new node creation must be confirmed by the user (recommended).
2525 When nil, the completion must match an existing entry.
2527 Note that, if the new heading is not seen by the criteria
2528 listed in `org-refile-targets', multiple instances of the same
2529 heading would be created by trying again to file under the new
2530 heading."
2531 :group 'org-refile
2532 :type '(choice
2533 (const :tag "Never" nil)
2534 (const :tag "Always" t)
2535 (const :tag "Prompt for confirmation" confirm)))
2537 (defcustom org-refile-active-region-within-subtree nil
2538 "Non-nil means also refile active region within a subtree.
2540 By default `org-refile' doesn't allow refiling regions if they
2541 don't contain a set of subtrees, but it might be convenient to
2542 do so sometimes: in that case, the first line of the region is
2543 converted to a headline before refiling."
2544 :group 'org-refile
2545 :version "24.1"
2546 :type 'boolean)
2548 (defgroup org-todo nil
2549 "Options concerning TODO items in Org mode."
2550 :tag "Org TODO"
2551 :group 'org)
2553 (defgroup org-progress nil
2554 "Options concerning Progress logging in Org mode."
2555 :tag "Org Progress"
2556 :group 'org-time)
2558 (defvar org-todo-interpretation-widgets
2559 '((:tag "Sequence (cycling hits every state)" sequence)
2560 (:tag "Type (cycling directly to DONE)" type))
2561 "The available interpretation symbols for customizing `org-todo-keywords'.
2562 Interested libraries should add to this list.")
2564 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2565 "List of TODO entry keyword sequences and their interpretation.
2566 \\<org-mode-map>This is a list of sequences.
2568 Each sequence starts with a symbol, either `sequence' or `type',
2569 indicating if the keywords should be interpreted as a sequence of
2570 action steps, or as different types of TODO items. The first
2571 keywords are states requiring action - these states will select a headline
2572 for inclusion into the global TODO list Org produces. If one of the
2573 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2574 signify that no further action is necessary. If \"|\" is not found,
2575 the last keyword is treated as the only DONE state of the sequence.
2577 The command `\\[org-todo]' cycles an entry through these states, and one
2578 additional state where no keyword is present. For details about this
2579 cycling, see the manual.
2581 TODO keywords and interpretation can also be set on a per-file basis with
2582 the special #+SEQ_TODO and #+TYP_TODO lines.
2584 Each keyword can optionally specify a character for fast state selection
2585 \(in combination with the variable `org-use-fast-todo-selection')
2586 and specifiers for state change logging, using the same syntax that
2587 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2588 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2589 indicates to record a time stamp each time this state is selected.
2591 Each keyword may also specify if a timestamp or a note should be
2592 recorded when entering or leaving the state, by adding additional
2593 characters in the parenthesis after the keyword. This looks like this:
2594 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2595 record only the time of the state change. With X and Y being either
2596 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2597 Y when leaving the state if and only if the *target* state does not
2598 define X. You may omit any of the fast-selection key or X or /Y,
2599 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2601 For backward compatibility, this variable may also be just a list
2602 of keywords. In this case the interpretation (sequence or type) will be
2603 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2604 :group 'org-todo
2605 :group 'org-keywords
2606 :type '(choice
2607 (repeat :tag "Old syntax, just keywords"
2608 (string :tag "Keyword"))
2609 (repeat :tag "New syntax"
2610 (cons
2611 (choice
2612 :tag "Interpretation"
2613 ;;Quick and dirty way to see
2614 ;;`org-todo-interpretations'. This takes the
2615 ;;place of item arguments
2616 :convert-widget
2617 (lambda (widget)
2618 (widget-put widget
2619 :args (mapcar
2620 (lambda (x)
2621 (widget-convert
2622 (cons 'const x)))
2623 org-todo-interpretation-widgets))
2624 widget))
2625 (repeat
2626 (string :tag "Keyword"))))))
2628 (defvar-local org-todo-keywords-1 nil
2629 "All TODO and DONE keywords active in a buffer.")
2630 (defvar org-todo-keywords-for-agenda nil)
2631 (defvar org-done-keywords-for-agenda nil)
2632 (defvar org-todo-keyword-alist-for-agenda nil)
2633 (defvar org-tag-alist-for-agenda nil
2634 "Alist of all tags from all agenda files.")
2635 (defvar org-tag-groups-alist-for-agenda nil
2636 "Alist of all groups tags from all current agenda files.")
2637 (defvar-local org-tag-groups-alist nil)
2638 (defvar org-agenda-contributing-files nil)
2639 (defvar-local org-current-tag-alist nil
2640 "Alist of all tag groups in current buffer.
2641 This variable takes into consideration `org-tag-alist',
2642 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2643 (defvar-local org-not-done-keywords nil)
2644 (defvar-local org-done-keywords nil)
2645 (defvar-local org-todo-heads nil)
2646 (defvar-local org-todo-sets nil)
2647 (defvar-local org-todo-log-states nil)
2648 (defvar-local org-todo-kwd-alist nil)
2649 (defvar-local org-todo-key-alist nil)
2650 (defvar-local org-todo-key-trigger nil)
2652 (defcustom org-todo-interpretation 'sequence
2653 "Controls how TODO keywords are interpreted.
2654 This variable is in principle obsolete and is only used for
2655 backward compatibility, if the interpretation of todo keywords is
2656 not given already in `org-todo-keywords'. See that variable for
2657 more information."
2658 :group 'org-todo
2659 :group 'org-keywords
2660 :type '(choice (const sequence)
2661 (const type)))
2663 (defcustom org-use-fast-todo-selection t
2664 "\\<org-mode-map>\
2665 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2666 This variable describes if and under what circumstances the cycling
2667 mechanism for TODO keywords will be replaced by a single-key, direct
2668 selection scheme.
2670 When nil, fast selection is never used.
2672 When the symbol `prefix', it will be used when `org-todo' is called
2673 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2674 in an Org buffer, and
2675 `\\[universal-argument] t' in an agenda buffer.
2677 When t, fast selection is used by default. In this case, the prefix
2678 argument forces cycling instead.
2680 In all cases, the special interface is only used if access keys have
2681 actually been assigned by the user, i.e. if keywords in the configuration
2682 are followed by a letter in parenthesis, like TODO(t)."
2683 :group 'org-todo
2684 :type '(choice
2685 (const :tag "Never" nil)
2686 (const :tag "By default" t)
2687 (const :tag "Only with C-u C-c C-t" prefix)))
2689 (defcustom org-provide-todo-statistics t
2690 "Non-nil means update todo statistics after insert and toggle.
2691 ALL-HEADLINES means update todo statistics by including headlines
2692 with no TODO keyword as well, counting them as not done.
2693 A list of TODO keywords means the same, but skip keywords that are
2694 not in this list.
2695 When set to a list of two lists, the first list contains keywords
2696 to consider as TODO keywords, the second list contains keywords
2697 to consider as DONE keywords.
2699 When this is set, todo statistics is updated in the parent of the
2700 current entry each time a todo state is changed."
2701 :group 'org-todo
2702 :type '(choice
2703 (const :tag "Yes, only for TODO entries" t)
2704 (const :tag "Yes, including all entries" all-headlines)
2705 (repeat :tag "Yes, for TODOs in this list"
2706 (string :tag "TODO keyword"))
2707 (list :tag "Yes, for TODOs and DONEs in these lists"
2708 (repeat (string :tag "TODO keyword"))
2709 (repeat (string :tag "DONE keyword")))
2710 (other :tag "No TODO statistics" nil)))
2712 (defcustom org-hierarchical-todo-statistics t
2713 "Non-nil means TODO statistics covers just direct children.
2714 When nil, all entries in the subtree are considered.
2715 This has only an effect if `org-provide-todo-statistics' is set.
2716 To set this to nil for only a single subtree, use a COOKIE_DATA
2717 property and include the word \"recursive\" into the value."
2718 :group 'org-todo
2719 :type 'boolean)
2721 (defcustom org-after-todo-state-change-hook nil
2722 "Hook which is run after the state of a TODO item was changed.
2723 The new state (a string with a TODO keyword, or nil) is available in the
2724 Lisp variable `org-state'."
2725 :group 'org-todo
2726 :type 'hook)
2728 (defvar org-blocker-hook nil
2729 "Hook for functions that are allowed to block a state change.
2731 Functions in this hook should not modify the buffer.
2732 Each function gets as its single argument a property list,
2733 see `org-trigger-hook' for more information about this list.
2735 If any of the functions in this hook returns nil, the state change
2736 is blocked.")
2738 (defvar org-trigger-hook nil
2739 "Hook for functions that are triggered by a state change.
2741 Each function gets as its single argument a property list with at
2742 least the following elements:
2744 (:type type-of-change :position pos-at-entry-start
2745 :from old-state :to new-state)
2747 Depending on the type, more properties may be present.
2749 This mechanism is currently implemented for:
2751 TODO state changes
2752 ------------------
2753 :type todo-state-change
2754 :from previous state (keyword as a string), or nil, or a symbol
2755 `todo' or `done', to indicate the general type of state.
2756 :to new state, like in :from")
2758 (defcustom org-enforce-todo-dependencies nil
2759 "Non-nil means undone TODO entries will block switching the parent to DONE.
2760 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2761 be blocked if any prior sibling is not yet done.
2762 Finally, if the parent is blocked because of ordered siblings of its own,
2763 the child will also be blocked."
2764 :set (lambda (var val)
2765 (set var val)
2766 (if val
2767 (add-hook 'org-blocker-hook
2768 'org-block-todo-from-children-or-siblings-or-parent)
2769 (remove-hook 'org-blocker-hook
2770 'org-block-todo-from-children-or-siblings-or-parent)))
2771 :group 'org-todo
2772 :type 'boolean)
2774 (defcustom org-enforce-todo-checkbox-dependencies nil
2775 "Non-nil means unchecked boxes will block switching the parent to DONE.
2776 When this is nil, checkboxes have no influence on switching TODO states.
2777 When non-nil, you first need to check off all check boxes before the TODO
2778 entry can be switched to DONE.
2779 This variable needs to be set before org.el is loaded, and you need to
2780 restart Emacs after a change to make the change effective. The only way
2781 to change is while Emacs is running is through the customize interface."
2782 :set (lambda (var val)
2783 (set var val)
2784 (if val
2785 (add-hook 'org-blocker-hook
2786 'org-block-todo-from-checkboxes)
2787 (remove-hook 'org-blocker-hook
2788 'org-block-todo-from-checkboxes)))
2789 :group 'org-todo
2790 :type 'boolean)
2792 (defcustom org-treat-insert-todo-heading-as-state-change nil
2793 "Non-nil means inserting a TODO heading is treated as state change.
2794 So when the command `\\[org-insert-todo-heading]' is used, state change
2795 logging will apply if appropriate. When nil, the new TODO item will
2796 be inserted directly, and no logging will take place."
2797 :group 'org-todo
2798 :type 'boolean)
2800 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2801 "Non-nil means switching TODO states with S-cursor counts as state change.
2802 This is the default behavior. However, setting this to nil allows a
2803 convenient way to select a TODO state and bypass any logging associated
2804 with that."
2805 :group 'org-todo
2806 :type 'boolean)
2808 (defcustom org-todo-state-tags-triggers nil
2809 "Tag changes that should be triggered by TODO state changes.
2810 This is a list. Each entry is
2812 (state-change (tag . flag) .......)
2814 State-change can be a string with a state, and empty string to indicate the
2815 state that has no TODO keyword, or it can be one of the symbols `todo'
2816 or `done', meaning any not-done or done state, respectively."
2817 :group 'org-todo
2818 :group 'org-tags
2819 :type '(repeat
2820 (cons (choice :tag "When changing to"
2821 (const :tag "Not-done state" todo)
2822 (const :tag "Done state" done)
2823 (string :tag "State"))
2824 (repeat
2825 (cons :tag "Tag action"
2826 (string :tag "Tag")
2827 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2829 (defcustom org-log-done nil
2830 "Information to record when a task moves to the DONE state.
2832 Possible values are:
2834 nil Don't add anything, just change the keyword
2835 time Add a time stamp to the task
2836 note Prompt for a note and add it with template `org-log-note-headings'
2838 This option can also be set with on a per-file-basis with
2840 #+STARTUP: nologdone
2841 #+STARTUP: logdone
2842 #+STARTUP: lognotedone
2844 You can have local logging settings for a subtree by setting the LOGGING
2845 property to one or more of these keywords."
2846 :group 'org-todo
2847 :group 'org-progress
2848 :type '(choice
2849 (const :tag "No logging" nil)
2850 (const :tag "Record CLOSED timestamp" time)
2851 (const :tag "Record CLOSED timestamp with note." note)))
2853 ;; Normalize old uses of org-log-done.
2854 (cond
2855 ((eq org-log-done t) (setq org-log-done 'time))
2856 ((and (listp org-log-done) (memq 'done org-log-done))
2857 (setq org-log-done 'note)))
2859 (defcustom org-log-reschedule nil
2860 "Information to record when the scheduling date of a tasks is modified.
2862 Possible values are:
2864 nil Don't add anything, just change the date
2865 time Add a time stamp to the task
2866 note Prompt for a note and add it with template `org-log-note-headings'
2868 This option can also be set with on a per-file-basis with
2870 #+STARTUP: nologreschedule
2871 #+STARTUP: logreschedule
2872 #+STARTUP: lognotereschedule"
2873 :group 'org-todo
2874 :group 'org-progress
2875 :type '(choice
2876 (const :tag "No logging" nil)
2877 (const :tag "Record timestamp" time)
2878 (const :tag "Record timestamp with note." note)))
2880 (defcustom org-log-redeadline nil
2881 "Information to record when the deadline date of a tasks is modified.
2883 Possible values are:
2885 nil Don't add anything, just change the date
2886 time Add a time stamp to the task
2887 note Prompt for a note and add it with template `org-log-note-headings'
2889 This option can also be set with on a per-file-basis with
2891 #+STARTUP: nologredeadline
2892 #+STARTUP: logredeadline
2893 #+STARTUP: lognoteredeadline
2895 You can have local logging settings for a subtree by setting the LOGGING
2896 property to one or more of these keywords."
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type '(choice
2900 (const :tag "No logging" nil)
2901 (const :tag "Record timestamp" time)
2902 (const :tag "Record timestamp with note." note)))
2904 (defcustom org-log-note-clock-out nil
2905 "Non-nil means record a note when clocking out of an item.
2906 This can also be configured on a per-file basis by adding one of
2907 the following lines anywhere in the buffer:
2909 #+STARTUP: lognoteclock-out
2910 #+STARTUP: nolognoteclock-out"
2911 :group 'org-todo
2912 :group 'org-progress
2913 :type 'boolean)
2915 (defcustom org-log-done-with-time t
2916 "Non-nil means the CLOSED time stamp will contain date and time.
2917 When nil, only the date will be recorded."
2918 :group 'org-progress
2919 :type 'boolean)
2921 (defcustom org-log-note-headings
2922 '((done . "CLOSING NOTE %t")
2923 (state . "State %-12s from %-12S %t")
2924 (note . "Note taken on %t")
2925 (reschedule . "Rescheduled from %S on %t")
2926 (delschedule . "Not scheduled, was %S on %t")
2927 (redeadline . "New deadline from %S on %t")
2928 (deldeadline . "Removed deadline, was %S on %t")
2929 (refile . "Refiled on %t")
2930 (clock-out . ""))
2931 "Headings for notes added to entries.
2933 The value is an alist, with the car being a symbol indicating the
2934 note context, and the cdr is the heading to be used. The heading
2935 may also be the empty string. The following placeholders can be
2936 used:
2938 %t a time stamp.
2939 %T an active time stamp instead the default inactive one
2940 %d a short-format time stamp.
2941 %D an active short-format time stamp.
2942 %s the new TODO state or time stamp (inactive), in double quotes.
2943 %S the old TODO state or time stamp (inactive), in double quotes.
2944 %u the user name.
2945 %U full user name.
2947 In fact, it is not a good idea to change the `state' entry,
2948 because Agenda Log mode depends on the format of these entries."
2949 :group 'org-todo
2950 :group 'org-progress
2951 :type '(list :greedy t
2952 (cons (const :tag "Heading when closing an item" done) string)
2953 (cons (const :tag
2954 "Heading when changing todo state (todo sequence only)"
2955 state) string)
2956 (cons (const :tag "Heading when just taking a note" note) string)
2957 (cons (const :tag "Heading when rescheduling" reschedule) string)
2958 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2959 (cons (const :tag "Heading when changing deadline" redeadline) string)
2960 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2961 (cons (const :tag "Heading when refiling" refile) string)
2962 (cons (const :tag "Heading when clocking out" clock-out) string)))
2964 (unless (assq 'note org-log-note-headings)
2965 (push '(note . "%t") org-log-note-headings))
2967 (defcustom org-log-into-drawer nil
2968 "Non-nil means insert state change notes and time stamps into a drawer.
2969 When nil, state changes notes will be inserted after the headline and
2970 any scheduling and clock lines, but not inside a drawer.
2972 The value of this variable should be the name of the drawer to use.
2973 LOGBOOK is proposed as the default drawer for this purpose, you can
2974 also set this to a string to define the drawer of your choice.
2976 A value of t is also allowed, representing \"LOGBOOK\".
2978 A value of t or nil can also be set with on a per-file-basis with
2980 #+STARTUP: logdrawer
2981 #+STARTUP: nologdrawer
2983 If this variable is set, `org-log-state-notes-insert-after-drawers'
2984 will be ignored.
2986 You can set the property LOG_INTO_DRAWER to overrule this setting for
2987 a subtree.
2989 Do not check directly this variable in a Lisp program. Call
2990 function `org-log-into-drawer' instead."
2991 :group 'org-todo
2992 :group 'org-progress
2993 :type '(choice
2994 (const :tag "Not into a drawer" nil)
2995 (const :tag "LOGBOOK" t)
2996 (string :tag "Other")))
2998 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3000 (defun org-log-into-drawer ()
3001 "Name of the log drawer, as a string, or nil.
3002 This is the value of `org-log-into-drawer'. However, if the
3003 current entry has or inherits a LOG_INTO_DRAWER property, it will
3004 be used instead of the default value."
3005 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3006 (cond ((equal p "nil") nil)
3007 ((equal p "t") "LOGBOOK")
3008 ((stringp p) p)
3009 (p "LOGBOOK")
3010 ((stringp org-log-into-drawer) org-log-into-drawer)
3011 (org-log-into-drawer "LOGBOOK"))))
3013 (defcustom org-log-state-notes-insert-after-drawers nil
3014 "Non-nil means insert state change notes after any drawers in entry.
3015 Only the drawers that *immediately* follow the headline and the
3016 deadline/scheduled line are skipped.
3017 When nil, insert notes right after the heading and perhaps the line
3018 with deadline/scheduling if present.
3020 This variable will have no effect if `org-log-into-drawer' is
3021 set."
3022 :group 'org-todo
3023 :group 'org-progress
3024 :type 'boolean)
3026 (defcustom org-log-states-order-reversed t
3027 "Non-nil means the latest state note will be directly after heading.
3028 When nil, the state change notes will be ordered according to time.
3030 This option can also be set with on a per-file-basis with
3032 #+STARTUP: logstatesreversed
3033 #+STARTUP: nologstatesreversed"
3034 :group 'org-todo
3035 :group 'org-progress
3036 :type 'boolean)
3038 (defcustom org-todo-repeat-to-state nil
3039 "The TODO state to which a repeater should return the repeating task.
3040 By default this is the first task of a TODO sequence or the
3041 previous state of a TYPE_TODO set. But you can specify to use
3042 the previous state in a TODO sequence or a string.
3044 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3045 entry, which has precedence over this option."
3046 :group 'org-todo
3047 :version "24.1"
3048 :type '(choice (const :tag "Use the previous TODO state" t)
3049 (const :tag "Use the head of the TODO sequence" nil)
3050 (string :tag "Use a specific TODO state")))
3052 (defcustom org-log-repeat 'time
3053 "Non-nil means record moving through the DONE state when triggering repeat.
3054 An auto-repeating task is immediately switched back to TODO when
3055 marked DONE. If you are not logging state changes (by adding \"@\"
3056 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3057 record a closing note, there will be no record of the task moving
3058 through DONE. This variable forces taking a note anyway.
3060 nil Don't force a record
3061 time Record a time stamp
3062 note Prompt for a note and add it with template `org-log-note-headings'
3064 This option can also be set with on a per-file-basis with
3066 #+STARTUP: nologrepeat
3067 #+STARTUP: logrepeat
3068 #+STARTUP: lognoterepeat
3070 You can have local logging settings for a subtree by setting the LOGGING
3071 property to one or more of these keywords."
3072 :group 'org-todo
3073 :group 'org-progress
3074 :type '(choice
3075 (const :tag "Don't force a record" nil)
3076 (const :tag "Force recording the DONE state" time)
3077 (const :tag "Force recording a note with the DONE state" note)))
3080 (defgroup org-priorities nil
3081 "Priorities in Org mode."
3082 :tag "Org Priorities"
3083 :group 'org-todo)
3085 (defcustom org-enable-priority-commands t
3086 "Non-nil means priority commands are active.
3087 When nil, these commands will be disabled, so that you never accidentally
3088 set a priority."
3089 :group 'org-priorities
3090 :type 'boolean)
3092 (defcustom org-highest-priority ?A
3093 "The highest priority of TODO items. A character like ?A, ?B etc.
3094 Must have a smaller ASCII number than `org-lowest-priority'."
3095 :group 'org-priorities
3096 :type 'character)
3098 (defcustom org-lowest-priority ?C
3099 "The lowest priority of TODO items. A character like ?A, ?B etc.
3100 Must have a larger ASCII number than `org-highest-priority'."
3101 :group 'org-priorities
3102 :type 'character)
3104 (defcustom org-default-priority ?B
3105 "The default priority of TODO items.
3106 This is the priority an item gets if no explicit priority is given.
3107 When starting to cycle on an empty priority the first step in the cycle
3108 depends on `org-priority-start-cycle-with-default'. The resulting first
3109 step priority must not exceed the range from `org-highest-priority' to
3110 `org-lowest-priority' which means that `org-default-priority' has to be
3111 in this range exclusive or inclusive the range boundaries. Else the
3112 first step refuses to set the default and the second will fall back
3113 to (depending on the command used) the highest or lowest priority."
3114 :group 'org-priorities
3115 :type 'character)
3117 (defcustom org-priority-start-cycle-with-default t
3118 "Non-nil means start with default priority when starting to cycle.
3119 When this is nil, the first step in the cycle will be (depending on the
3120 command used) one higher or lower than the default priority.
3121 See also `org-default-priority'."
3122 :group 'org-priorities
3123 :type 'boolean)
3125 (defcustom org-get-priority-function nil
3126 "Function to extract the priority from a string.
3127 The string is normally the headline. If this is nil Org computes the
3128 priority from the priority cookie like [#A] in the headline. It returns
3129 an integer, increasing by 1000 for each priority level.
3130 The user can set a different function here, which should take a string
3131 as an argument and return the numeric priority."
3132 :group 'org-priorities
3133 :version "24.1"
3134 :type '(choice
3135 (const nil)
3136 (function)))
3138 (defgroup org-time nil
3139 "Options concerning time stamps and deadlines in Org mode."
3140 :tag "Org Time"
3141 :group 'org)
3143 (defcustom org-time-stamp-rounding-minutes '(0 5)
3144 "Number of minutes to round time stamps to.
3145 \\<org-mode-map>\
3146 These are two values, the first applies when first creating a time stamp.
3147 The second applies when changing it with the commands `S-up' and `S-down'.
3148 When changing the time stamp, this means that it will change in steps
3149 of N minutes, as given by the second value.
3151 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3152 numbers should be factors of 60, so for example 5, 10, 15.
3154 When this is larger than 1, you can still force an exact time stamp by using
3155 a double prefix argument to a time stamp command like \
3156 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3157 and by using a prefix arg to `S-up/down' to specify the exact number
3158 of minutes to shift."
3159 :group 'org-time
3160 :get (lambda (var) ; Make sure both elements are there
3161 (if (integerp (default-value var))
3162 (list (default-value var) 5)
3163 (default-value var)))
3164 :type '(list
3165 (integer :tag "when inserting times")
3166 (integer :tag "when modifying times")))
3168 ;; Normalize old customizations of this variable.
3169 (when (integerp org-time-stamp-rounding-minutes)
3170 (setq org-time-stamp-rounding-minutes
3171 (list org-time-stamp-rounding-minutes
3172 org-time-stamp-rounding-minutes)))
3174 (defcustom org-display-custom-times nil
3175 "Non-nil means overlay custom formats over all time stamps.
3176 The formats are defined through the variable `org-time-stamp-custom-formats'.
3177 To turn this on on a per-file basis, insert anywhere in the file:
3178 #+STARTUP: customtime"
3179 :group 'org-time
3180 :set 'set-default
3181 :type 'sexp)
3182 (make-variable-buffer-local 'org-display-custom-times)
3184 (defcustom org-time-stamp-custom-formats
3185 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3186 "Custom formats for time stamps. See `format-time-string' for the syntax.
3187 These are overlaid over the default ISO format if the variable
3188 `org-display-custom-times' is set. Time like %H:%M should be at the
3189 end of the second format. The custom formats are also honored by export
3190 commands, if custom time display is turned on at the time of export."
3191 :group 'org-time
3192 :type 'sexp)
3194 (defun org-time-stamp-format (&optional long inactive)
3195 "Get the right format for a time string."
3196 (let ((f (if long (cdr org-time-stamp-formats)
3197 (car org-time-stamp-formats))))
3198 (if inactive
3199 (concat "[" (substring f 1 -1) "]")
3200 f)))
3202 (defcustom org-deadline-warning-days 14
3203 "Number of days before expiration during which a deadline becomes active.
3204 This variable governs the display in sparse trees and in the agenda.
3205 When 0 or negative, it means use this number (the absolute value of it)
3206 even if a deadline has a different individual lead time specified.
3208 Custom commands can set this variable in the options section."
3209 :group 'org-time
3210 :group 'org-agenda-daily/weekly
3211 :type 'integer)
3213 (defcustom org-scheduled-delay-days 0
3214 "Number of days before a scheduled item becomes active.
3215 This variable governs the display in sparse trees and in the agenda.
3216 The default value (i.e. 0) means: don't delay scheduled item.
3217 When negative, it means use this number (the absolute value of it)
3218 even if a scheduled item has a different individual delay time
3219 specified.
3221 Custom commands can set this variable in the options section."
3222 :group 'org-time
3223 :group 'org-agenda-daily/weekly
3224 :version "24.4"
3225 :package-version '(Org . "8.0")
3226 :type 'integer)
3228 (defcustom org-read-date-prefer-future t
3229 "Non-nil means assume future for incomplete date input from user.
3230 This affects the following situations:
3231 1. The user gives a month but not a year.
3232 For example, if it is April and you enter \"feb 2\", this will be read
3233 as Feb 2, *next* year. \"May 5\", however, will be this year.
3234 2. The user gives a day, but no month.
3235 For example, if today is the 15th, and you enter \"3\", Org will read
3236 this as the third of *next* month. However, if you enter \"17\",
3237 it will be considered as *this* month.
3239 If you set this variable to the symbol `time', then also the following
3240 will work:
3242 3. If the user gives a time.
3243 If the time is before now, it will be interpreted as tomorrow.
3245 Currently none of this works for ISO week specifications.
3247 When this option is nil, the current day, month and year will always be
3248 used as defaults.
3250 See also `org-agenda-jump-prefer-future'."
3251 :group 'org-time
3252 :type '(choice
3253 (const :tag "Never" nil)
3254 (const :tag "Check month and day" t)
3255 (const :tag "Check month, day, and time" time)))
3257 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3258 "Should the agenda jump command prefer the future for incomplete dates?
3259 The default is to do the same as configured in `org-read-date-prefer-future'.
3260 But you can also set a deviating value here.
3261 This may t or nil, or the symbol `org-read-date-prefer-future'."
3262 :group 'org-agenda
3263 :group 'org-time
3264 :version "24.1"
3265 :type '(choice
3266 (const :tag "Use org-read-date-prefer-future"
3267 org-read-date-prefer-future)
3268 (const :tag "Never" nil)
3269 (const :tag "Always" t)))
3271 (defcustom org-read-date-force-compatible-dates t
3272 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3274 Depending on the system Emacs is running on, certain dates cannot
3275 be represented with the type used internally to represent time.
3276 Dates between 1970-1-1 and 2038-1-1 can always be represented
3277 correctly. Some systems allow for earlier dates, some for later,
3278 some for both. One way to find out it to insert any date into an
3279 Org buffer, putting the cursor on the year and hitting S-up and
3280 S-down to test the range.
3282 When this variable is set to t, the date/time prompt will not let
3283 you specify dates outside the 1970-2037 range, so it is certain that
3284 these dates will work in whatever version of Emacs you are
3285 running, and also that you can move a file from one Emacs implementation
3286 to another. WHenever Org is forcing the year for you, it will display
3287 a message and beep.
3289 When this variable is nil, Org will check if the date is
3290 representable in the specific Emacs implementation you are using.
3291 If not, it will force a year, usually the current year, and beep
3292 to remind you. Currently this setting is not recommended because
3293 the likelihood that you will open your Org files in an Emacs that
3294 has limited date range is not negligible.
3296 A workaround for this problem is to use diary sexp dates for time
3297 stamps outside of this range."
3298 :group 'org-time
3299 :version "24.1"
3300 :type 'boolean)
3302 (defcustom org-read-date-display-live t
3303 "Non-nil means display current interpretation of date prompt live.
3304 This display will be in an overlay, in the minibuffer."
3305 :group 'org-time
3306 :type 'boolean)
3308 (defcustom org-read-date-popup-calendar t
3309 "Non-nil means pop up a calendar when prompting for a date.
3310 In the calendar, the date can be selected with mouse-1. However, the
3311 minibuffer will also be active, and you can simply enter the date as well.
3312 When nil, only the minibuffer will be available."
3313 :group 'org-time
3314 :type 'boolean)
3315 (defvaralias 'org-popup-calendar-for-date-prompt
3316 'org-read-date-popup-calendar)
3318 (defcustom org-extend-today-until 0
3319 "The hour when your day really ends. Must be an integer.
3320 This has influence for the following applications:
3321 - When switching the agenda to \"today\". It it is still earlier than
3322 the time given here, the day recognized as TODAY is actually yesterday.
3323 - When a date is read from the user and it is still before the time given
3324 here, the current date and time will be assumed to be yesterday, 23:59.
3325 Also, timestamps inserted in capture templates follow this rule.
3327 IMPORTANT: This is a feature whose implementation is and likely will
3328 remain incomplete. Really, it is only here because past midnight seems to
3329 be the favorite working time of John Wiegley :-)"
3330 :group 'org-time
3331 :type 'integer)
3333 (defcustom org-use-effective-time nil
3334 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3335 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3336 \"effective time\" of any timestamps between midnight and 8am will be
3337 23:59 of the previous day."
3338 :group 'org-time
3339 :version "24.1"
3340 :type 'boolean)
3342 (defcustom org-use-last-clock-out-time-as-effective-time nil
3343 "When non-nil, use the last clock out time for `org-todo'.
3344 Note that this option has precedence over the combined use of
3345 `org-use-effective-time' and `org-extend-today-until'."
3346 :group 'org-time
3347 :version "24.4"
3348 :package-version '(Org . "8.0")
3349 :type 'boolean)
3351 (defcustom org-edit-timestamp-down-means-later nil
3352 "Non-nil means S-down will increase the time in a time stamp.
3353 When nil, S-up will increase."
3354 :group 'org-time
3355 :type 'boolean)
3357 (defcustom org-calendar-follow-timestamp-change t
3358 "Non-nil means make the calendar window follow timestamp changes.
3359 When a timestamp is modified and the calendar window is visible, it will be
3360 moved to the new date."
3361 :group 'org-time
3362 :type 'boolean)
3364 (defgroup org-tags nil
3365 "Options concerning tags in Org mode."
3366 :tag "Org Tags"
3367 :group 'org)
3369 (defcustom org-tag-alist nil
3370 "Default tags available in Org files.
3372 The value of this variable is an alist. Associations either:
3374 (TAG)
3375 (TAG . SELECT)
3376 (SPECIAL)
3378 where TAG is a tag as a string, SELECT is character, used to
3379 select that tag through the fast tag selection interface, and
3380 SPECIAL is one of the following keywords: `:startgroup',
3381 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3382 `:newline'. These keywords are used to define a hierarchy of
3383 tags. See manual for details.
3385 When this variable is nil, Org mode bases tag input on what is
3386 already in the buffer. The value can be overridden locally by
3387 using a TAGS keyword, e.g.,
3389 #+TAGS: tag1 tag2
3391 See also `org-tag-persistent-alist' to sidestep this behavior."
3392 :group 'org-tags
3393 :type '(repeat
3394 (choice
3395 (cons :tag "Tag with key"
3396 (string :tag "Tag name")
3397 (character :tag "Access char"))
3398 (list :tag "Tag" (string :tag "Tag name"))
3399 (const :tag "Start radio group" (:startgroup))
3400 (const :tag "Start tag group, non distinct" (:startgrouptag))
3401 (const :tag "Group tags delimiter" (:grouptags))
3402 (const :tag "End radio group" (:endgroup))
3403 (const :tag "End tag group, non distinct" (:endgrouptag))
3404 (const :tag "New line" (:newline)))))
3406 (defcustom org-tag-persistent-alist nil
3407 "Tags always available in Org files.
3409 The value of this variable is an alist. Associations either:
3411 (TAG)
3412 (TAG . SELECT)
3413 (SPECIAL)
3415 where TAG is a tag as a string, SELECT is a character, used to
3416 select that tag through the fast tag selection interface, and
3417 SPECIAL is one of the following keywords: `:startgroup',
3418 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3419 `:newline'. These keywords are used to define a hierarchy of
3420 tags. See manual for details.
3422 Unlike to `org-tag-alist', tags defined in this variable do not
3423 depend on a local TAGS keyword. Instead, to disable these tags
3424 on a per-file basis, insert anywhere in the file:
3426 #+STARTUP: noptag"
3427 :group 'org-tags
3428 :type '(repeat
3429 (choice
3430 (cons :tag "Tag with key"
3431 (string :tag "Tag name")
3432 (character :tag "Access char"))
3433 (list :tag "Tag" (string :tag "Tag name"))
3434 (const :tag "Start radio group" (:startgroup))
3435 (const :tag "Start tag group, non distinct" (:startgrouptag))
3436 (const :tag "Group tags delimiter" (:grouptags))
3437 (const :tag "End radio group" (:endgroup))
3438 (const :tag "End tag group, non distinct" (:endgrouptag))
3439 (const :tag "New line" (:newline)))))
3441 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3442 "If non-nil, always offer completion for all tags of all agenda files.
3443 Instead of customizing this variable directly, you might want to
3444 set it locally for capture buffers, because there no list of
3445 tags in that file can be created dynamically (there are none).
3447 (add-hook \\='org-capture-mode-hook
3448 (lambda ()
3449 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3450 :group 'org-tags
3451 :version "24.1"
3452 :type 'boolean)
3454 (defvar org-file-tags nil
3455 "List of tags that can be inherited by all entries in the file.
3456 The tags will be inherited if the variable `org-use-tag-inheritance'
3457 says they should be.
3458 This variable is populated from #+FILETAGS lines.")
3460 (defcustom org-use-fast-tag-selection 'auto
3461 "Non-nil means use fast tag selection scheme.
3462 This is a special interface to select and deselect tags with single keys.
3463 When nil, fast selection is never used.
3464 When the symbol `auto', fast selection is used if and only if selection
3465 characters for tags have been configured, either through the variable
3466 `org-tag-alist' or through a #+TAGS line in the buffer.
3467 When t, fast selection is always used and selection keys are assigned
3468 automatically if necessary."
3469 :group 'org-tags
3470 :type '(choice
3471 (const :tag "Always" t)
3472 (const :tag "Never" nil)
3473 (const :tag "When selection characters are configured" auto)))
3475 (defcustom org-fast-tag-selection-single-key nil
3476 "Non-nil means fast tag selection exits after first change.
3477 When nil, you have to press RET to exit it.
3478 During fast tag selection, you can toggle this flag with `C-c'.
3479 This variable can also have the value `expert'. In this case, the window
3480 displaying the tags menu is not even shown, until you press C-c again."
3481 :group 'org-tags
3482 :type '(choice
3483 (const :tag "No" nil)
3484 (const :tag "Yes" t)
3485 (const :tag "Expert" expert)))
3487 (defvar org-fast-tag-selection-include-todo nil
3488 "Non-nil means fast tags selection interface will also offer TODO states.
3489 This is an undocumented feature, you should not rely on it.")
3491 (defcustom org-tags-column -77
3492 "The column to which tags should be indented in a headline.
3493 If this number is positive, it specifies the column. If it is negative,
3494 it means that the tags should be flushright to that column. For example,
3495 -80 works well for a normal 80 character screen.
3496 When 0, place tags directly after headline text, with only one space in
3497 between."
3498 :group 'org-tags
3499 :type 'integer)
3501 (defcustom org-auto-align-tags t
3502 "Non-nil keeps tags aligned when modifying headlines.
3503 Some operations (i.e. demoting) change the length of a headline and
3504 therefore shift the tags around. With this option turned on, after
3505 each such operation the tags are again aligned to `org-tags-column'."
3506 :group 'org-tags
3507 :type 'boolean)
3509 (defcustom org-use-tag-inheritance t
3510 "Non-nil means tags in levels apply also for sublevels.
3511 When nil, only the tags directly given in a specific line apply there.
3512 This may also be a list of tags that should be inherited, or a regexp that
3513 matches tags that should be inherited. Additional control is possible
3514 with the variable `org-tags-exclude-from-inheritance' which gives an
3515 explicit list of tags to be excluded from inheritance, even if the value of
3516 `org-use-tag-inheritance' would select it for inheritance.
3518 If this option is t, a match early-on in a tree can lead to a large
3519 number of matches in the subtree when constructing the agenda or creating
3520 a sparse tree. If you only want to see the first match in a tree during
3521 a search, check out the variable `org-tags-match-list-sublevels'."
3522 :group 'org-tags
3523 :type '(choice
3524 (const :tag "Not" nil)
3525 (const :tag "Always" t)
3526 (repeat :tag "Specific tags" (string :tag "Tag"))
3527 (regexp :tag "Tags matched by regexp")))
3529 (defcustom org-tags-exclude-from-inheritance nil
3530 "List of tags that should never be inherited.
3531 This is a way to exclude a few tags from inheritance. For way to do
3532 the opposite, to actively allow inheritance for selected tags,
3533 see the variable `org-use-tag-inheritance'."
3534 :group 'org-tags
3535 :type '(repeat (string :tag "Tag")))
3537 (defun org-tag-inherit-p (tag)
3538 "Check if TAG is one that should be inherited."
3539 (cond
3540 ((member tag org-tags-exclude-from-inheritance) nil)
3541 ((eq org-use-tag-inheritance t) t)
3542 ((not org-use-tag-inheritance) nil)
3543 ((stringp org-use-tag-inheritance)
3544 (string-match org-use-tag-inheritance tag))
3545 ((listp org-use-tag-inheritance)
3546 (member tag org-use-tag-inheritance))
3547 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3549 (defcustom org-tags-match-list-sublevels t
3550 "Non-nil means list also sublevels of headlines matching a search.
3551 This variable applies to tags/property searches, and also to stuck
3552 projects because this search is based on a tags match as well.
3554 When set to the symbol `indented', sublevels are indented with
3555 leading dots.
3557 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3558 the sublevels of a headline matching a tag search often also match
3559 the same search. Listing all of them can create very long lists.
3560 Setting this variable to nil causes subtrees of a match to be skipped.
3562 This variable is semi-obsolete and probably should always be true. It
3563 is better to limit inheritance to certain tags using the variables
3564 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3565 :group 'org-tags
3566 :type '(choice
3567 (const :tag "No, don't list them" nil)
3568 (const :tag "Yes, do list them" t)
3569 (const :tag "List them, indented with leading dots" indented)))
3571 (defcustom org-tags-sort-function nil
3572 "When set, tags are sorted using this function as a comparator."
3573 :group 'org-tags
3574 :type '(choice
3575 (const :tag "No sorting" nil)
3576 (const :tag "Alphabetical" org-string-collate-lessp)
3577 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3578 (function :tag "Custom function" nil)))
3580 (defvar org-tags-history nil
3581 "History of minibuffer reads for tags.")
3582 (defvar org-last-tags-completion-table nil
3583 "The last used completion table for tags.")
3584 (defvar org-after-tags-change-hook nil
3585 "Hook that is run after the tags in a line have changed.")
3587 (defgroup org-properties nil
3588 "Options concerning properties in Org mode."
3589 :tag "Org Properties"
3590 :group 'org)
3592 (defcustom org-property-format "%-10s %s"
3593 "How property key/value pairs should be formatted by `indent-line'.
3594 When `indent-line' hits a property definition, it will format the line
3595 according to this format, mainly to make sure that the values are
3596 lined-up with respect to each other."
3597 :group 'org-properties
3598 :type 'string)
3600 (defcustom org-properties-postprocess-alist nil
3601 "Alist of properties and functions to adjust inserted values.
3602 Elements of this alist must be of the form
3604 ([string] [function])
3606 where [string] must be a property name and [function] must be a
3607 lambda expression: this lambda expression must take one argument,
3608 the value to adjust, and return the new value as a string.
3610 For example, this element will allow the property \"Remaining\"
3611 to be updated wrt the relation between the \"Effort\" property
3612 and the clock summary:
3614 ((\"Remaining\" (lambda(value)
3615 (let ((clocksum (org-clock-sum-current-item))
3616 (effort (org-duration-to-minutes
3617 (org-entry-get (point) \"Effort\"))))
3618 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3619 :group 'org-properties
3620 :version "24.1"
3621 :type '(alist :key-type (string :tag "Property")
3622 :value-type (function :tag "Function")))
3624 (defcustom org-use-property-inheritance nil
3625 "Non-nil means properties apply also for sublevels.
3627 This setting is chiefly used during property searches. Turning it on can
3628 cause significant overhead when doing a search, which is why it is not
3629 on by default.
3631 When nil, only the properties directly given in the current entry count.
3632 When t, every property is inherited. The value may also be a list of
3633 properties that should have inheritance, or a regular expression matching
3634 properties that should be inherited.
3636 However, note that some special properties use inheritance under special
3637 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3638 and the properties ending in \"_ALL\" when they are used as descriptor
3639 for valid values of a property.
3641 Note for programmers:
3642 When querying an entry with `org-entry-get', you can control if inheritance
3643 should be used. By default, `org-entry-get' looks only at the local
3644 properties. You can request inheritance by setting the inherit argument
3645 to t (to force inheritance) or to `selective' (to respect the setting
3646 in this variable)."
3647 :group 'org-properties
3648 :type '(choice
3649 (const :tag "Not" nil)
3650 (const :tag "Always" t)
3651 (repeat :tag "Specific properties" (string :tag "Property"))
3652 (regexp :tag "Properties matched by regexp")))
3654 (defun org-property-inherit-p (property)
3655 "Return a non-nil value if PROPERTY should be inherited."
3656 (cond
3657 ((eq org-use-property-inheritance t) t)
3658 ((not org-use-property-inheritance) nil)
3659 ((stringp org-use-property-inheritance)
3660 (string-match org-use-property-inheritance property))
3661 ((listp org-use-property-inheritance)
3662 (member-ignore-case property org-use-property-inheritance))
3663 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3665 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3666 "The default column format, if no other format has been defined.
3667 This variable can be set on the per-file basis by inserting a line
3669 #+COLUMNS: %25ITEM ....."
3670 :group 'org-properties
3671 :type 'string)
3673 (defcustom org-columns-ellipses ".."
3674 "The ellipses to be used when a field in column view is truncated.
3675 When this is the empty string, as many characters as possible are shown,
3676 but then there will be no visual indication that the field has been truncated.
3677 When this is a string of length N, the last N characters of a truncated
3678 field are replaced by this string. If the column is narrower than the
3679 ellipses string, only part of the ellipses string will be shown."
3680 :group 'org-properties
3681 :type 'string)
3683 (defconst org-global-properties-fixed
3684 '(("VISIBILITY_ALL" . "folded children content all")
3685 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3686 "List of property/value pairs that can be inherited by any entry.
3688 These are fixed values, for the preset properties. The user variable
3689 that can be used to add to this list is `org-global-properties'.
3691 The entries in this list are cons cells where the car is a property
3692 name and cdr is a string with the value. If the value represents
3693 multiple items like an \"_ALL\" property, separate the items by
3694 spaces.")
3696 (defcustom org-global-properties nil
3697 "List of property/value pairs that can be inherited by any entry.
3699 This list will be combined with the constant `org-global-properties-fixed'.
3701 The entries in this list are cons cells where the car is a property
3702 name and cdr is a string with the value.
3704 You can set buffer-local values for the same purpose in the variable
3705 `org-file-properties' this by adding lines like
3707 #+PROPERTY: NAME VALUE"
3708 :group 'org-properties
3709 :type '(repeat
3710 (cons (string :tag "Property")
3711 (string :tag "Value"))))
3713 (defvar-local org-file-properties nil
3714 "List of property/value pairs that can be inherited by any entry.
3715 Valid for the current buffer.
3716 This variable is populated from #+PROPERTY lines.")
3718 (defgroup org-agenda nil
3719 "Options concerning agenda views in Org mode."
3720 :tag "Org Agenda"
3721 :group 'org)
3723 (defvar-local org-category nil
3724 "Variable used by Org files to set a category for agenda display.
3725 Such files should use a file variable to set it, for example
3727 # -*- mode: org; org-category: \"ELisp\"
3729 or contain a special line
3731 #+CATEGORY: ELisp
3733 If the file does not specify a category, then file's base name
3734 is used instead.")
3735 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3737 (defcustom org-agenda-files nil
3738 "The files to be used for agenda display.
3740 If an entry is a directory, all files in that directory that are matched
3741 by `org-agenda-file-regexp' will be part of the file list.
3743 If the value of the variable is not a list but a single file name, then
3744 the list of agenda files is actually stored and maintained in that file,
3745 one agenda file per line. In this file paths can be given relative to
3746 `org-directory'. Tilde expansion and environment variable substitution
3747 are also made.
3749 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3750 and removed with `\\[org-remove-file]'."
3751 :group 'org-agenda
3752 :type '(choice
3753 (repeat :tag "List of files and directories" file)
3754 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3756 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3757 "Regular expression to match files for `org-agenda-files'.
3758 If any element in the list in that variable contains a directory instead
3759 of a normal file, all files in that directory that are matched by this
3760 regular expression will be included."
3761 :group 'org-agenda
3762 :type 'regexp)
3764 (defcustom org-agenda-text-search-extra-files nil
3765 "List of extra files to be searched by text search commands.
3766 These files will be searched in addition to the agenda files by the
3767 commands `org-search-view' (`\\[org-agenda] s') \
3768 and `org-occur-in-agenda-files'.
3769 Note that these files will only be searched for text search commands,
3770 not for the other agenda views like todo lists, tag searches or the weekly
3771 agenda. This variable is intended to list notes and possibly archive files
3772 that should also be searched by these two commands.
3773 In fact, if the first element in the list is the symbol `agenda-archives',
3774 then all archive files of all agenda files will be added to the search
3775 scope."
3776 :group 'org-agenda
3777 :type '(set :greedy t
3778 (const :tag "Agenda Archives" agenda-archives)
3779 (repeat :inline t (file))))
3781 (defvaralias 'org-agenda-multi-occur-extra-files
3782 'org-agenda-text-search-extra-files)
3784 (defcustom org-agenda-skip-unavailable-files nil
3785 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3786 A nil value means to remove them, after a query, from the list."
3787 :group 'org-agenda
3788 :type 'boolean)
3790 (defcustom org-agenda-diary-file 'diary-file
3791 "File to which to add new entries with the `i' key in agenda and calendar.
3792 When this is the symbol `diary-file', the functionality in the Emacs
3793 calendar will be used to add entries to the `diary-file'. But when this
3794 points to a file, `org-agenda-diary-entry' will be used instead."
3795 :group 'org-agenda
3796 :type '(choice
3797 (const :tag "The standard Emacs diary file" diary-file)
3798 (file :tag "Special Org file diary entries")))
3800 (defgroup org-latex nil
3801 "Options for embedding LaTeX code into Org mode."
3802 :tag "Org LaTeX"
3803 :group 'org)
3805 (defcustom org-format-latex-options
3806 '(:foreground default :background default :scale 1.0
3807 :html-foreground "Black" :html-background "Transparent"
3808 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3809 "Options for creating images from LaTeX fragments.
3810 This is a property list with the following properties:
3811 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3812 `default' means use the foreground of the default face.
3813 `auto' means use the foreground from the text face.
3814 :background the background color, or \"Transparent\".
3815 `default' means use the background of the default face.
3816 `auto' means use the background from the text face.
3817 :scale a scaling factor for the size of the images, to get more pixels
3818 :html-foreground, :html-background, :html-scale
3819 the same numbers for HTML export.
3820 :matchers a list indicating which matchers should be used to
3821 find LaTeX fragments. Valid members of this list are:
3822 \"begin\" find environments
3823 \"$1\" find single characters surrounded by $.$
3824 \"$\" find math expressions surrounded by $...$
3825 \"$$\" find math expressions surrounded by $$....$$
3826 \"\\(\" find math expressions surrounded by \\(...\\)
3827 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3828 :group 'org-latex
3829 :type 'plist)
3831 (defcustom org-format-latex-signal-error t
3832 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3833 When nil, just push out a message."
3834 :group 'org-latex
3835 :version "24.1"
3836 :type 'boolean)
3838 (defcustom org-latex-to-mathml-jar-file nil
3839 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3840 Use this to specify additional executable file say a jar file.
3842 When using MathToWeb as the converter, specify the full-path to
3843 your mathtoweb.jar file."
3844 :group 'org-latex
3845 :version "24.1"
3846 :type '(choice
3847 (const :tag "None" nil)
3848 (file :tag "JAR file" :must-match t)))
3850 (defcustom org-latex-to-mathml-convert-command nil
3851 "Command to convert LaTeX fragments to MathML.
3852 Replace format-specifiers in the command as noted below and use
3853 `shell-command' to convert LaTeX to MathML.
3854 %j: Executable file in fully expanded form as specified by
3855 `org-latex-to-mathml-jar-file'.
3856 %I: Input LaTeX file in fully expanded form.
3857 %i: The latex fragment to be converted.
3858 %o: Output MathML file.
3860 This command is used by `org-create-math-formula'.
3862 When using MathToWeb as the converter, set this option to
3863 \"java -jar %j -unicode -force -df %o %I\".
3865 When using LaTeXML set this option to
3866 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3867 :group 'org-latex
3868 :version "24.1"
3869 :type '(choice
3870 (const :tag "None" nil)
3871 (string :tag "\nShell command")))
3873 (defcustom org-preview-latex-default-process 'dvipng
3874 "The default process to convert LaTeX fragments to image files.
3875 All available processes and theirs documents can be found in
3876 `org-preview-latex-process-alist', which see."
3877 :group 'org-latex
3878 :version "26.1"
3879 :package-version '(Org . "9.0")
3880 :type 'symbol)
3882 (defcustom org-preview-latex-process-alist
3883 '((dvipng
3884 :programs ("latex" "dvipng")
3885 :description "dvi > png"
3886 :message "you need to install the programs: latex and dvipng."
3887 :image-input-type "dvi"
3888 :image-output-type "png"
3889 :image-size-adjust (1.0 . 1.0)
3890 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3891 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3892 (dvisvgm
3893 :programs ("latex" "dvisvgm")
3894 :description "dvi > svg"
3895 :message "you need to install the programs: latex and dvisvgm."
3896 :use-xcolor t
3897 :image-input-type "dvi"
3898 :image-output-type "svg"
3899 :image-size-adjust (1.7 . 1.5)
3900 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3901 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3902 (imagemagick
3903 :programs ("latex" "convert")
3904 :description "pdf > png"
3905 :message "you need to install the programs: latex and imagemagick."
3906 :use-xcolor t
3907 :image-input-type "pdf"
3908 :image-output-type "png"
3909 :image-size-adjust (1.0 . 1.0)
3910 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3911 :image-converter
3912 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3913 "Definitions of external processes for LaTeX previewing.
3914 Org mode can use some external commands to generate TeX snippet's images for
3915 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3916 `org-create-formula-image' how to call them.
3918 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3919 PROPERTIES accepts the following attributes:
3921 :programs list of strings, required programs.
3922 :description string, describe the process.
3923 :message string, message it when required programs cannot be found.
3924 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3925 :image-output-type string, output file type of image converter (e.g., \"png\").
3926 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3927 deal with background and foreground color of image.
3928 Otherwise, dvipng style background and foreground color
3929 format are generated. You may then refer to them in
3930 command options with \"%F\" and \"%B\".
3931 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3932 image size showed in buffer and the cdr element is for
3933 HTML file. This option is only useful for process
3934 developers, users should use variable
3935 `org-format-latex-options' instead.
3936 :post-clean list of strings, files matched are to be cleaned up once
3937 the image is generated. When nil, the files with \".dvi\",
3938 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3939 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3940 be cleaned up.
3941 :latex-header list of strings, the LaTeX header of the snippet file.
3942 When nil, the fallback value is used instead, which is
3943 controlled by `org-format-latex-header',
3944 `org-latex-default-packages-alist' and
3945 `org-latex-packages-alist', which see.
3946 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3947 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3948 replaced with values defined below.
3949 :image-converter list of image converter commands strings. Each of them is
3950 given to the shell and supports any of the following
3951 place-holders defined below.
3953 Place-holders used by `:image-converter' and `:latex-compiler':
3955 %f input file name
3956 %b base name of input file
3957 %o base directory of input file
3958 %O absolute output file name
3960 Place-holders only used by `:image-converter':
3962 %F foreground of image
3963 %B background of image
3964 %D dpi, which is used to adjust image size by some processing commands.
3965 %S the image size scale ratio, which is used to adjust image size by some
3966 processing commands."
3967 :group 'org-latex
3968 :version "26.1"
3969 :package-version '(Org . "9.0")
3970 :type '(alist :tag "LaTeX to image backends"
3971 :value-type (plist)))
3973 (defcustom org-preview-latex-image-directory "ltximg/"
3974 "Path to store latex preview images.
3975 A relative path here creates many directories relative to the
3976 processed Org files paths. An absolute path puts all preview
3977 images at the same place."
3978 :group 'org-latex
3979 :version "26.1"
3980 :package-version '(Org . "9.0")
3981 :type 'string)
3983 (defun org-format-latex-mathml-available-p ()
3984 "Return t if `org-latex-to-mathml-convert-command' is usable."
3985 (save-match-data
3986 (when (and (boundp 'org-latex-to-mathml-convert-command)
3987 org-latex-to-mathml-convert-command)
3988 (let ((executable (car (split-string
3989 org-latex-to-mathml-convert-command))))
3990 (when (executable-find executable)
3991 (if (string-match
3992 "%j" org-latex-to-mathml-convert-command)
3993 (file-readable-p org-latex-to-mathml-jar-file)
3994 t))))))
3996 (defcustom org-format-latex-header "\\documentclass{article}
3997 \\usepackage[usenames]{color}
3998 \[PACKAGES]
3999 \[DEFAULT-PACKAGES]
4000 \\pagestyle{empty} % do not remove
4001 % The settings below are copied from fullpage.sty
4002 \\setlength{\\textwidth}{\\paperwidth}
4003 \\addtolength{\\textwidth}{-3cm}
4004 \\setlength{\\oddsidemargin}{1.5cm}
4005 \\addtolength{\\oddsidemargin}{-2.54cm}
4006 \\setlength{\\evensidemargin}{\\oddsidemargin}
4007 \\setlength{\\textheight}{\\paperheight}
4008 \\addtolength{\\textheight}{-\\headheight}
4009 \\addtolength{\\textheight}{-\\headsep}
4010 \\addtolength{\\textheight}{-\\footskip}
4011 \\addtolength{\\textheight}{-3cm}
4012 \\setlength{\\topmargin}{1.5cm}
4013 \\addtolength{\\topmargin}{-2.54cm}"
4014 "The document header used for processing LaTeX fragments.
4015 It is imperative that this header make sure that no page number
4016 appears on the page. The package defined in the variables
4017 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4018 will either replace the placeholder \"[PACKAGES]\" in this
4019 header, or they will be appended."
4020 :group 'org-latex
4021 :type 'string)
4023 (defun org-set-packages-alist (var val)
4024 "Set the packages alist and make sure it has 3 elements per entry."
4025 (set var (mapcar (lambda (x)
4026 (if (and (consp x) (= (length x) 2))
4027 (list (car x) (nth 1 x) t)
4029 val)))
4031 (defun org-get-packages-alist (var)
4032 "Get the packages alist and make sure it has 3 elements per entry."
4033 (mapcar (lambda (x)
4034 (if (and (consp x) (= (length x) 2))
4035 (list (car x) (nth 1 x) t)
4037 (default-value var)))
4039 (defcustom org-latex-default-packages-alist
4040 '(("AUTO" "inputenc" t ("pdflatex"))
4041 ("T1" "fontenc" t ("pdflatex"))
4042 ("" "graphicx" t)
4043 ("" "grffile" t)
4044 ("" "longtable" nil)
4045 ("" "wrapfig" nil)
4046 ("" "rotating" nil)
4047 ("normalem" "ulem" t)
4048 ("" "amsmath" t)
4049 ("" "textcomp" t)
4050 ("" "amssymb" t)
4051 ("" "capt-of" nil)
4052 ("" "hyperref" nil))
4053 "Alist of default packages to be inserted in the header.
4055 Change this only if one of the packages here causes an
4056 incompatibility with another package you are using.
4058 The packages in this list are needed by one part or another of
4059 Org mode to function properly:
4061 - inputenc, fontenc: for basic font and character selection
4062 - graphicx: for including images
4063 - grffile: allow periods and spaces in graphics file names
4064 - longtable: For multipage tables
4065 - wrapfig: for figure placement
4066 - rotating: for sideways figures and tables
4067 - ulem: for underline and strike-through
4068 - amsmath: for subscript and superscript and math environments
4069 - textcomp, amssymb: for various symbols used
4070 for interpreting the entities in `org-entities'. You can skip
4071 some of these packages if you don't use any of their symbols.
4072 - capt-of: for captions outside of floats
4073 - hyperref: for cross references
4075 Therefore you should not modify this variable unless you know
4076 what you are doing. The one reason to change it anyway is that
4077 you might be loading some other package that conflicts with one
4078 of the default packages. Each element is either a cell or
4079 a string.
4081 A cell is of the format
4083 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4085 If SNIPPET-FLAG is non-nil, the package also needs to be included
4086 when compiling LaTeX snippets into images for inclusion into
4087 non-LaTeX output. COMPILERS is a list of compilers that should
4088 include the package, see `org-latex-compiler'. If the document
4089 compiler is not in the list, and the list is non-nil, the package
4090 will not be inserted in the final document.
4092 A string will be inserted as-is in the header of the document."
4093 :group 'org-latex
4094 :group 'org-export-latex
4095 :set 'org-set-packages-alist
4096 :get 'org-get-packages-alist
4097 :version "26.1"
4098 :package-version '(Org . "8.3")
4099 :type '(repeat
4100 (choice
4101 (list :tag "options/package pair"
4102 (string :tag "options")
4103 (string :tag "package")
4104 (boolean :tag "Snippet")
4105 (choice
4106 (const :tag "For all compilers" nil)
4107 (repeat :tag "Allowed compiler" string)))
4108 (string :tag "A line of LaTeX"))))
4110 (defcustom org-latex-packages-alist nil
4111 "Alist of packages to be inserted in every LaTeX header.
4113 These will be inserted after `org-latex-default-packages-alist'.
4114 Each element is either a cell or a string.
4116 A cell is of the format:
4118 (\"options\" \"package\" SNIPPET-FLAG)
4120 SNIPPET-FLAG, when non-nil, indicates that this package is also
4121 needed when turning LaTeX snippets into images for inclusion into
4122 non-LaTeX output.
4124 A string will be inserted as-is in the header of the document.
4126 Make sure that you only list packages here which:
4128 - you want in every file;
4129 - do not conflict with the setup in `org-format-latex-header';
4130 - do not conflict with the default packages in
4131 `org-latex-default-packages-alist'."
4132 :group 'org-latex
4133 :group 'org-export-latex
4134 :set 'org-set-packages-alist
4135 :get 'org-get-packages-alist
4136 :type '(repeat
4137 (choice
4138 (list :tag "options/package pair"
4139 (string :tag "options")
4140 (string :tag "package")
4141 (boolean :tag "Snippet"))
4142 (string :tag "A line of LaTeX"))))
4144 (defgroup org-appearance nil
4145 "Settings for Org mode appearance."
4146 :tag "Org Appearance"
4147 :group 'org)
4149 (defcustom org-level-color-stars-only nil
4150 "Non-nil means fontify only the stars in each headline.
4151 When nil, the entire headline is fontified.
4152 Changing it requires restart of `font-lock-mode' to become effective
4153 also in regions already fontified."
4154 :group 'org-appearance
4155 :type 'boolean)
4157 (defcustom org-hide-leading-stars nil
4158 "Non-nil means hide the first N-1 stars in a headline.
4159 This works by using the face `org-hide' for these stars. This
4160 face is white for a light background, and black for a dark
4161 background. You may have to customize the face `org-hide' to
4162 make this work.
4163 Changing it requires restart of `font-lock-mode' to become effective
4164 also in regions already fontified.
4165 You may also set this on a per-file basis by adding one of the following
4166 lines to the buffer:
4168 #+STARTUP: hidestars
4169 #+STARTUP: showstars"
4170 :group 'org-appearance
4171 :type 'boolean)
4173 (defcustom org-hidden-keywords nil
4174 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4175 For example, a value \\='(title) for this list makes the document's title
4176 appear in the buffer without the initial \"#+TITLE:\" part."
4177 :group 'org-appearance
4178 :version "24.1"
4179 :type '(set (const :tag "#+AUTHOR" author)
4180 (const :tag "#+DATE" date)
4181 (const :tag "#+EMAIL" email)
4182 (const :tag "#+TITLE" title)))
4184 (defcustom org-custom-properties nil
4185 "List of properties (as strings) with a special meaning.
4186 The default use of these custom properties is to let the user
4187 hide them with `org-toggle-custom-properties-visibility'."
4188 :group 'org-properties
4189 :group 'org-appearance
4190 :version "24.3"
4191 :type '(repeat (string :tag "Property Name")))
4193 (defcustom org-fontify-done-headline nil
4194 "Non-nil means change the face of a headline if it is marked DONE.
4195 Normally, only the TODO/DONE keyword indicates the state of a headline.
4196 When this is non-nil, the headline after the keyword is set to the
4197 `org-headline-done' as an additional indication."
4198 :group 'org-appearance
4199 :type 'boolean)
4201 (defcustom org-fontify-emphasized-text t
4202 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4203 Changing this variable requires a restart of Emacs to take effect."
4204 :group 'org-appearance
4205 :type 'boolean)
4207 (defcustom org-fontify-whole-heading-line nil
4208 "Non-nil means fontify the whole line for headings.
4209 This is useful when setting a background color for the
4210 org-level-* faces."
4211 :group 'org-appearance
4212 :type 'boolean)
4214 (defcustom org-highlight-latex-and-related nil
4215 "Non-nil means highlight LaTeX related syntax in the buffer.
4216 When non nil, the value should be a list containing any of the
4217 following symbols:
4218 `latex' Highlight LaTeX snippets and environments.
4219 `script' Highlight subscript and superscript.
4220 `entities' Highlight entities."
4221 :group 'org-appearance
4222 :version "24.4"
4223 :package-version '(Org . "8.0")
4224 :type '(choice
4225 (const :tag "No highlighting" nil)
4226 (set :greedy t :tag "Highlight"
4227 (const :tag "LaTeX snippets and environments" latex)
4228 (const :tag "Subscript and superscript" script)
4229 (const :tag "Entities" entities))))
4231 (defcustom org-hide-emphasis-markers nil
4232 "Non-nil mean font-lock should hide the emphasis marker characters."
4233 :group 'org-appearance
4234 :type 'boolean)
4236 (defcustom org-hide-macro-markers nil
4237 "Non-nil mean font-lock should hide the brackets marking macro calls."
4238 :group 'org-appearance
4239 :type 'boolean)
4241 (defcustom org-pretty-entities nil
4242 "Non-nil means show entities as UTF8 characters.
4243 When nil, the \\name form remains in the buffer."
4244 :group 'org-appearance
4245 :version "24.1"
4246 :type 'boolean)
4248 (defcustom org-pretty-entities-include-sub-superscripts t
4249 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4250 :group 'org-appearance
4251 :version "24.1"
4252 :type 'boolean)
4254 (defvar org-emph-re nil
4255 "Regular expression for matching emphasis.
4256 After a match, the match groups contain these elements:
4257 0 The match of the full regular expression, including the characters
4258 before and after the proper match
4259 1 The character before the proper match, or empty at beginning of line
4260 2 The proper match, including the leading and trailing markers
4261 3 The leading marker like * or /, indicating the type of highlighting
4262 4 The text between the emphasis markers, not including the markers
4263 5 The character after the match, empty at the end of a line")
4265 (defvar org-verbatim-re nil
4266 "Regular expression for matching verbatim text.")
4268 (defvar org-emphasis-regexp-components) ; defined just below
4269 (defvar org-emphasis-alist) ; defined just below
4270 (defun org-set-emph-re (var val)
4271 "Set variable and compute the emphasis regular expression."
4272 (set var val)
4273 (when (and (boundp 'org-emphasis-alist)
4274 (boundp 'org-emphasis-regexp-components)
4275 org-emphasis-alist org-emphasis-regexp-components)
4276 (pcase-let*
4277 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4278 (body (if (<= nl 0) body
4279 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4280 (template
4281 (format (concat "\\([%s]\\|^\\)" ;before markers
4282 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4283 "\\([%s]\\|$\\)") ;after markers
4284 pre border border body border post)))
4285 (setq org-emph-re (format template "*/_+"))
4286 (setq org-verbatim-re (format template "=~")))))
4288 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4289 ;; set this option proved cumbersome. See this message/thread:
4290 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4291 (defvar org-emphasis-regexp-components
4292 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4293 "Components used to build the regular expression for emphasis.
4294 This is a list with five entries. Terminology: In an emphasis string
4295 like \" *strong word* \", we call the initial space PREMATCH, the final
4296 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4297 and \"trong wor\" is the body. The different components in this variable
4298 specify what is allowed/forbidden in each part:
4300 pre Chars allowed as prematch. Beginning of line will be allowed too.
4301 post Chars allowed as postmatch. End of line will be allowed too.
4302 border The chars *forbidden* as border characters.
4303 body-regexp A regexp like \".\" to match a body character. Don't use
4304 non-shy groups here, and don't allow newline here.
4305 newline The maximum number of newlines allowed in an emphasis exp.
4307 You need to reload Org or to restart Emacs after setting this.")
4309 (defcustom org-emphasis-alist
4310 '(("*" bold)
4311 ("/" italic)
4312 ("_" underline)
4313 ("=" org-verbatim verbatim)
4314 ("~" org-code verbatim)
4315 ("+" (:strike-through t)))
4316 "Alist of characters and faces to emphasize text.
4317 Text starting and ending with a special character will be emphasized,
4318 for example *bold*, _underlined_ and /italic/. This variable sets the
4319 marker characters and the face to be used by font-lock for highlighting
4320 in Org buffers.
4322 You need to reload Org or to restart Emacs after customizing this."
4323 :group 'org-appearance
4324 :set 'org-set-emph-re
4325 :version "24.4"
4326 :package-version '(Org . "8.0")
4327 :type '(repeat
4328 (list
4329 (string :tag "Marker character")
4330 (choice
4331 (face :tag "Font-lock-face")
4332 (plist :tag "Face property list"))
4333 (option (const verbatim)))))
4335 (defvar org-protecting-blocks '("src" "example" "export")
4336 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4337 This is needed for font-lock setup.")
4339 ;;; Functions and variables from their packages
4340 ;; Declared here to avoid compiler warnings
4341 (defvar mark-active)
4343 ;; Various packages
4344 (declare-function calc-eval "calc" (str &optional separator &rest args))
4345 (declare-function calendar-forward-day "cal-move" (arg))
4346 (declare-function calendar-goto-date "cal-move" (date))
4347 (declare-function calendar-goto-today "cal-move" ())
4348 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4349 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4350 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4351 (declare-function cdlatex-tab "ext:cdlatex" ())
4352 (declare-function dired-get-filename
4353 "dired"
4354 (&optional localp no-error-if-not-filep))
4355 (declare-function iswitchb-read-buffer
4356 "iswitchb"
4357 (prompt &optional
4358 default require-match _predicate start matches-set))
4359 (declare-function org-agenda-change-all-lines
4360 "org-agenda"
4361 (newhead hdmarker &optional fixface just-this))
4362 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4363 "org-agenda"
4364 (&optional end))
4365 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4366 (declare-function org-agenda-format-item
4367 "org-agenda"
4368 (extra txt &optional level category tags dotime
4369 remove-re habitp))
4370 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4371 (declare-function org-agenda-save-markers-for-cut-and-paste
4372 "org-agenda"
4373 (beg end))
4374 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4375 (declare-function org-agenda-skip "org-agenda" ())
4376 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4377 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4378 (declare-function org-indent-mode "org-indent" (&optional arg))
4379 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4380 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4381 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4382 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4383 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4384 (declare-function parse-time-string "parse-time" (string))
4386 (defvar align-mode-rules-list)
4387 (defvar calc-embedded-close-formula)
4388 (defvar calc-embedded-open-formula)
4389 (defvar calc-embedded-open-mode)
4390 (defvar font-lock-unfontify-region-function)
4391 (defvar iswitchb-temp-buflist)
4392 (defvar org-agenda-tags-todo-honor-ignore-options)
4393 (defvar remember-data-file)
4394 (defvar texmathp-why)
4396 ;;;###autoload
4397 (defun turn-on-orgtbl ()
4398 "Unconditionally turn on `orgtbl-mode'."
4399 (require 'org-table)
4400 (orgtbl-mode 1))
4402 (defun org-at-table-p (&optional table-type)
4403 "Non-nil if the cursor is inside an Org table.
4404 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4405 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4406 (or (not (derived-mode-p 'org-mode))
4407 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4408 (and e (or table-type
4409 (eq 'org (org-element-property :type e))))))))
4411 (defun org-at-table.el-p ()
4412 "Non-nil when point is at a table.el table."
4413 (and (org-match-line "[ \t]*[|+]")
4414 (let ((element (org-element-at-point)))
4415 (and (eq (org-element-type element) 'table)
4416 (eq (org-element-property :type element) 'table.el)))))
4418 (defun org-at-table-hline-p ()
4419 "Non-nil when point is inside a hline in a table.
4420 Assume point is already in a table."
4421 (org-match-line org-table-hline-regexp))
4423 (defun org-table-map-tables (function &optional quietly)
4424 "Apply FUNCTION to the start of all tables in the buffer."
4425 (org-with-wide-buffer
4426 (goto-char (point-min))
4427 (while (re-search-forward org-table-any-line-regexp nil t)
4428 (unless quietly
4429 (message "Mapping tables: %d%%"
4430 (floor (* 100.0 (point)) (buffer-size))))
4431 (beginning-of-line 1)
4432 (when (and (looking-at org-table-line-regexp)
4433 ;; Exclude tables in src/example/verbatim/clocktable blocks
4434 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4435 (save-excursion (funcall function))
4436 (or (looking-at org-table-line-regexp)
4437 (forward-char 1)))
4438 (re-search-forward org-table-any-border-regexp nil 1)))
4439 (unless quietly (message "Mapping tables: done")))
4441 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4442 (declare-function org-clock-update-mode-line "org-clock" ())
4443 (declare-function org-resolve-clocks "org-clock"
4444 (&optional also-non-dangling-p prompt last-valid))
4446 (defun org-at-TBLFM-p (&optional pos)
4447 "Non-nil when point (or POS) is in #+TBLFM line."
4448 (save-excursion
4449 (goto-char (or pos (point)))
4450 (beginning-of-line)
4451 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4452 (eq (org-element-type (org-element-at-point)) 'table))))
4454 (defvar org-clock-start-time)
4455 (defvar org-clock-marker (make-marker)
4456 "Marker recording the last clock-in.")
4457 (defvar org-clock-hd-marker (make-marker)
4458 "Marker recording the last clock-in, but the headline position.")
4459 (defvar org-clock-heading ""
4460 "The heading of the current clock entry.")
4461 (defun org-clock-is-active ()
4462 "Return the buffer where the clock is currently running.
4463 Return nil if no clock is running."
4464 (marker-buffer org-clock-marker))
4466 (defun org-check-running-clock ()
4467 "Check if the current buffer contains the running clock.
4468 If yes, offer to stop it and to save the buffer with the changes."
4469 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4470 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4471 (buffer-name))))
4472 (org-clock-out)
4473 (when (y-or-n-p "Save changed buffer?")
4474 (save-buffer))))
4476 (defun org-clocktable-try-shift (dir n)
4477 "Check if this line starts a clock table, if yes, shift the time block."
4478 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4479 (org-clocktable-shift dir n)))
4481 ;;;###autoload
4482 (defun org-clock-persistence-insinuate ()
4483 "Set up hooks for clock persistence."
4484 (require 'org-clock)
4485 (add-hook 'org-mode-hook 'org-clock-load)
4486 (add-hook 'kill-emacs-hook 'org-clock-save))
4488 (defgroup org-archive nil
4489 "Options concerning archiving in Org mode."
4490 :tag "Org Archive"
4491 :group 'org-structure)
4493 (defcustom org-archive-location "%s_archive::"
4494 "The location where subtrees should be archived.
4496 The value of this variable is a string, consisting of two parts,
4497 separated by a double-colon. The first part is a filename and
4498 the second part is a headline.
4500 When the filename is omitted, archiving happens in the same file.
4501 %s in the filename will be replaced by the current file
4502 name (without the directory part). Archiving to a different file
4503 is useful to keep archived entries from contributing to the
4504 Org Agenda.
4506 The archived entries will be filed as subtrees of the specified
4507 headline. When the headline is omitted, the subtrees are simply
4508 filed away at the end of the file, as top-level entries. Also in
4509 the heading you can use %s to represent the file name, this can be
4510 useful when using the same archive for a number of different files.
4512 Here are a few examples:
4513 \"%s_archive::\"
4514 If the current file is Projects.org, archive in file
4515 Projects.org_archive, as top-level trees. This is the default.
4517 \"::* Archived Tasks\"
4518 Archive in the current file, under the top-level headline
4519 \"* Archived Tasks\".
4521 \"~/org/archive.org::\"
4522 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4524 \"~/org/archive.org::* From %s\"
4525 Archive in file ~/org/archive.org (absolute path), under headlines
4526 \"From FILENAME\" where file name is the current file name.
4528 \"~/org/datetree.org::datetree/* Finished Tasks\"
4529 The \"datetree/\" string is special, signifying to archive
4530 items to the datetree. Items are placed in either the CLOSED
4531 date of the item, or the current date if there is no CLOSED date.
4532 The heading will be a subentry to the current date. There doesn't
4533 need to be a heading, but there always needs to be a slash after
4534 datetree. For example, to store archived items directly in the
4535 datetree, use \"~/org/datetree.org::datetree/\".
4537 \"basement::** Finished Tasks\"
4538 Archive in file ./basement (relative path), as level 3 trees
4539 below the level 2 heading \"** Finished Tasks\".
4541 You may set this option on a per-file basis by adding to the buffer a
4542 line like
4544 #+ARCHIVE: basement::** Finished Tasks
4546 You may also define it locally for a subtree by setting an ARCHIVE property
4547 in the entry. If such a property is found in an entry, or anywhere up
4548 the hierarchy, it will be used."
4549 :group 'org-archive
4550 :type 'string)
4552 (defcustom org-agenda-skip-archived-trees t
4553 "Non-nil means the agenda will skip any items located in archived trees.
4554 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4555 variable is no longer recommended, you should leave it at the value t.
4556 Instead, use the key `v' to cycle the archives-mode in the agenda."
4557 :group 'org-archive
4558 :group 'org-agenda-skip
4559 :type 'boolean)
4561 (defcustom org-columns-skip-archived-trees t
4562 "Non-nil means ignore archived trees when creating column view."
4563 :group 'org-archive
4564 :group 'org-properties
4565 :type 'boolean)
4567 (defcustom org-cycle-open-archived-trees nil
4568 "Non-nil means `org-cycle' will open archived trees.
4569 An archived tree is a tree marked with the tag ARCHIVE.
4570 When nil, archived trees will stay folded. You can still open them with
4571 normal outline commands like `show-all', but not with the cycling commands."
4572 :group 'org-archive
4573 :group 'org-cycle
4574 :type 'boolean)
4576 (defcustom org-sparse-tree-open-archived-trees nil
4577 "Non-nil means sparse tree construction shows matches in archived trees.
4578 When nil, matches in these trees are highlighted, but the trees are kept in
4579 collapsed state."
4580 :group 'org-archive
4581 :group 'org-sparse-trees
4582 :type 'boolean)
4584 (defcustom org-sparse-tree-default-date-type nil
4585 "The default date type when building a sparse tree.
4586 When this is nil, a date is a scheduled or a deadline timestamp.
4587 Otherwise, these types are allowed:
4589 all: all timestamps
4590 active: only active timestamps (<...>)
4591 inactive: only inactive timestamps ([...])
4592 scheduled: only scheduled timestamps
4593 deadline: only deadline timestamps"
4594 :type '(choice (const :tag "Scheduled or deadline" nil)
4595 (const :tag "All timestamps" all)
4596 (const :tag "Only active timestamps" active)
4597 (const :tag "Only inactive timestamps" inactive)
4598 (const :tag "Only scheduled timestamps" scheduled)
4599 (const :tag "Only deadline timestamps" deadline)
4600 (const :tag "Only closed timestamps" closed))
4601 :version "26.1"
4602 :package-version '(Org . "8.3")
4603 :group 'org-sparse-trees)
4605 (defun org-cycle-hide-archived-subtrees (state)
4606 "Re-hide all archived subtrees after a visibility state change.
4607 STATE should be one of the symbols listed in the docstring of
4608 `org-cycle-hook'."
4609 (when (and (not org-cycle-open-archived-trees)
4610 (not (memq state '(overview folded))))
4611 (save-excursion
4612 (let* ((globalp (memq state '(contents all)))
4613 (beg (if globalp (point-min) (point)))
4614 (end (if globalp (point-max) (org-end-of-subtree t))))
4615 (org-hide-archived-subtrees beg end)
4616 (goto-char beg)
4617 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4618 (message "%s" (substitute-command-keys
4619 "Subtree is archived and stays closed. Use \
4620 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4622 (defun org-force-cycle-archived ()
4623 "Cycle subtree even if it is archived."
4624 (interactive)
4625 (setq this-command 'org-cycle)
4626 (let ((org-cycle-open-archived-trees t))
4627 (call-interactively 'org-cycle)))
4629 (defun org-hide-archived-subtrees (beg end)
4630 "Re-hide all archived subtrees after a visibility state change."
4631 (org-with-wide-buffer
4632 (let ((case-fold-search nil)
4633 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4634 (goto-char beg)
4635 ;; Include headline point is currently on.
4636 (beginning-of-line)
4637 (while (and (< (point) end) (re-search-forward re end t))
4638 (when (member org-archive-tag (org-get-tags nil t))
4639 (org-flag-subtree t)
4640 (org-end-of-subtree t))))))
4642 (defun org-flag-subtree (flag)
4643 (save-excursion
4644 (org-back-to-heading t)
4645 (org-flag-region (line-end-position)
4646 (progn (org-end-of-subtree t) (point))
4647 flag
4648 'outline)))
4650 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4652 ;; Declare Column View Code
4654 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4655 (declare-function org-columns-compute "org-colview" (property))
4657 ;; Declare ID code
4659 (declare-function org-id-store-link "org-id")
4660 (declare-function org-id-locations-load "org-id")
4661 (declare-function org-id-locations-save "org-id")
4662 (defvar org-id-track-globally)
4664 ;;; Variables for pre-computed regular expressions, all buffer local
4666 (defvar-local org-todo-regexp nil
4667 "Matches any of the TODO state keywords.
4668 Since TODO keywords are case-sensitive, `case-fold-search' is
4669 expected to be bound to nil when matching against this regexp.")
4671 (defvar-local org-not-done-regexp nil
4672 "Matches any of the TODO state keywords except the last one.
4673 Since TODO keywords are case-sensitive, `case-fold-search' is
4674 expected to be bound to nil when matching against this regexp.")
4676 (defvar-local org-not-done-heading-regexp nil
4677 "Matches a TODO headline that is not done.
4678 Since TODO keywords are case-sensitive, `case-fold-search' is
4679 expected to be bound to nil when matching against this regexp.")
4681 (defvar-local org-todo-line-regexp nil
4682 "Matches a headline and puts TODO state into group 2 if present.
4683 Since TODO keywords are case-sensitive, `case-fold-search' is
4684 expected to be bound to nil when matching against this regexp.")
4686 (defvar-local org-complex-heading-regexp nil
4687 "Matches a headline and puts everything into groups:
4689 group 1: Stars
4690 group 2: The TODO keyword, maybe
4691 group 3: Priority cookie
4692 group 4: True headline
4693 group 5: Tags
4695 Since TODO keywords are case-sensitive, `case-fold-search' is
4696 expected to be bound to nil when matching against this regexp.")
4698 (defvar-local org-complex-heading-regexp-format nil
4699 "Printf format to make regexp to match an exact headline.
4700 This regexp will match the headline of any node which has the
4701 exact headline text that is put into the format, but may have any
4702 TODO state, priority and tags.")
4704 (defvar-local org-todo-line-tags-regexp nil
4705 "Matches a headline and puts TODO state into group 2 if present.
4706 Also put tags into group 4 if tags are present.")
4708 (defconst org-plain-time-of-day-regexp
4709 (concat
4710 "\\(\\<[012]?[0-9]"
4711 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4712 "\\(--?"
4713 "\\(\\<[012]?[0-9]"
4714 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4715 "\\)?")
4716 "Regular expression to match a plain time or time range.
4717 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4718 groups carry important information:
4719 0 the full match
4720 1 the first time, range or not
4721 8 the second time, if it is a range.")
4723 (defconst org-plain-time-extension-regexp
4724 (concat
4725 "\\(\\<[012]?[0-9]"
4726 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4727 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4728 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4729 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4730 groups carry important information:
4731 0 the full match
4732 7 hours of duration
4733 9 minutes of duration")
4735 (defconst org-stamp-time-of-day-regexp
4736 (concat
4737 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4738 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4739 "\\(--?"
4740 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4741 "Regular expression to match a timestamp time or time range.
4742 After a match, the following groups carry important information:
4743 0 the full match
4744 1 date plus weekday, for back referencing to make sure both times are on the same day
4745 2 the first time, range or not
4746 4 the second time, if it is a range.")
4748 (defconst org-startup-options
4749 '(("fold" org-startup-folded t)
4750 ("overview" org-startup-folded t)
4751 ("nofold" org-startup-folded nil)
4752 ("showall" org-startup-folded nil)
4753 ("showeverything" org-startup-folded showeverything)
4754 ("content" org-startup-folded content)
4755 ("indent" org-startup-indented t)
4756 ("noindent" org-startup-indented nil)
4757 ("hidestars" org-hide-leading-stars t)
4758 ("showstars" org-hide-leading-stars nil)
4759 ("odd" org-odd-levels-only t)
4760 ("oddeven" org-odd-levels-only nil)
4761 ("align" org-startup-align-all-tables t)
4762 ("noalign" org-startup-align-all-tables nil)
4763 ("shrink" org-startup-shrink-all-tables t)
4764 ("inlineimages" org-startup-with-inline-images t)
4765 ("noinlineimages" org-startup-with-inline-images nil)
4766 ("latexpreview" org-startup-with-latex-preview t)
4767 ("nolatexpreview" org-startup-with-latex-preview nil)
4768 ("customtime" org-display-custom-times t)
4769 ("logdone" org-log-done time)
4770 ("lognotedone" org-log-done note)
4771 ("nologdone" org-log-done nil)
4772 ("lognoteclock-out" org-log-note-clock-out t)
4773 ("nolognoteclock-out" org-log-note-clock-out nil)
4774 ("logrepeat" org-log-repeat state)
4775 ("lognoterepeat" org-log-repeat note)
4776 ("logdrawer" org-log-into-drawer t)
4777 ("nologdrawer" org-log-into-drawer nil)
4778 ("logstatesreversed" org-log-states-order-reversed t)
4779 ("nologstatesreversed" org-log-states-order-reversed nil)
4780 ("nologrepeat" org-log-repeat nil)
4781 ("logreschedule" org-log-reschedule time)
4782 ("lognotereschedule" org-log-reschedule note)
4783 ("nologreschedule" org-log-reschedule nil)
4784 ("logredeadline" org-log-redeadline time)
4785 ("lognoteredeadline" org-log-redeadline note)
4786 ("nologredeadline" org-log-redeadline nil)
4787 ("logrefile" org-log-refile time)
4788 ("lognoterefile" org-log-refile note)
4789 ("nologrefile" org-log-refile nil)
4790 ("fninline" org-footnote-define-inline t)
4791 ("nofninline" org-footnote-define-inline nil)
4792 ("fnlocal" org-footnote-section nil)
4793 ("fnauto" org-footnote-auto-label t)
4794 ("fnprompt" org-footnote-auto-label nil)
4795 ("fnconfirm" org-footnote-auto-label confirm)
4796 ("fnplain" org-footnote-auto-label plain)
4797 ("fnadjust" org-footnote-auto-adjust t)
4798 ("nofnadjust" org-footnote-auto-adjust nil)
4799 ("constcgs" constants-unit-system cgs)
4800 ("constSI" constants-unit-system SI)
4801 ("noptag" org-tag-persistent-alist nil)
4802 ("hideblocks" org-hide-block-startup t)
4803 ("nohideblocks" org-hide-block-startup nil)
4804 ("beamer" org-startup-with-beamer-mode t)
4805 ("entitiespretty" org-pretty-entities t)
4806 ("entitiesplain" org-pretty-entities nil))
4807 "Variable associated with STARTUP options for Org.
4808 Each element is a list of three items: the startup options (as written
4809 in the #+STARTUP line), the corresponding variable, and the value to set
4810 this variable to if the option is found. An optional forth element PUSH
4811 means to push this value onto the list in the variable.")
4813 (defcustom org-group-tags t
4814 "When non-nil (the default), use group tags.
4815 This can be turned on/off through `org-toggle-tags-groups'."
4816 :group 'org-tags
4817 :group 'org-startup
4818 :type 'boolean)
4820 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4822 (defun org-toggle-tags-groups ()
4823 "Toggle support for group tags.
4824 Support for group tags is controlled by the option
4825 `org-group-tags', which is non-nil by default."
4826 (interactive)
4827 (setq org-group-tags (not org-group-tags))
4828 (cond ((and (derived-mode-p 'org-agenda-mode)
4829 org-group-tags)
4830 (org-agenda-redo))
4831 ((derived-mode-p 'org-mode)
4832 (let ((org-inhibit-startup t)) (org-mode))))
4833 (message "Groups tags support has been turned %s"
4834 (if org-group-tags "on" "off")))
4836 (defun org-tag-add-to-alist (alist1 alist2)
4837 "Append ALIST1 elements to ALIST2 if they are not there yet."
4838 (cond
4839 ((null alist2) alist1)
4840 ((null alist1) alist2)
4841 (t (let ((alist2-cars (mapcar (lambda (x) (car-safe x)) alist2))
4842 to-add)
4843 (dolist (i alist1)
4844 (unless (member (car-safe i) alist2-cars)
4845 (push i to-add)))
4846 (append to-add alist2)))))
4848 (defun org-set-regexps-and-options (&optional tags-only)
4849 "Precompute regular expressions used in the current buffer.
4850 When optional argument TAGS-ONLY is non-nil, only compute tags
4851 related expressions."
4852 (when (derived-mode-p 'org-mode)
4853 (let ((alist (org--setup-collect-keywords
4854 (org-make-options-regexp
4855 (append '("FILETAGS" "TAGS" "SETUPFILE")
4856 (and (not tags-only)
4857 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4858 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4859 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4860 ;; Startup options. Get this early since it does change
4861 ;; behavior for other options (e.g., tags).
4862 (let ((startup (cdr (assq 'startup alist))))
4863 (dolist (option startup)
4864 (let ((entry (assoc-string option org-startup-options t)))
4865 (when entry
4866 (let ((var (nth 1 entry))
4867 (val (nth 2 entry)))
4868 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4869 (unless (listp (symbol-value var))
4870 (set (make-local-variable var) nil))
4871 (add-to-list var val)))))))
4872 (setq-local org-file-tags
4873 (mapcar #'org-add-prop-inherited
4874 (cdr (assq 'filetags alist))))
4875 (setq org-current-tag-alist
4876 (org-tag-add-to-alist
4877 org-tag-persistent-alist
4878 (let ((tags (cdr (assq 'tags alist))))
4879 (if tags (org-tag-string-to-alist tags)
4880 org-tag-alist))))
4881 (setq org-tag-groups-alist
4882 (org-tag-alist-to-groups org-current-tag-alist))
4883 (unless tags-only
4884 ;; File properties.
4885 (setq-local org-file-properties (cdr (assq 'property alist)))
4886 ;; Archive location.
4887 (let ((archive (cdr (assq 'archive alist))))
4888 (when archive (setq-local org-archive-location archive)))
4889 ;; Category.
4890 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4891 (when cat
4892 (setq-local org-category (intern cat))
4893 (setq-local org-file-properties
4894 (org--update-property-plist
4895 "CATEGORY" cat org-file-properties))))
4896 ;; Columns.
4897 (let ((column (cdr (assq 'columns alist))))
4898 (when column (setq-local org-columns-default-format column)))
4899 ;; Constants.
4900 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4901 ;; Link abbreviations.
4902 (let ((links (cdr (assq 'link alist))))
4903 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4904 ;; Priorities.
4905 (let ((priorities (cdr (assq 'priorities alist))))
4906 (when priorities
4907 (setq-local org-highest-priority (nth 0 priorities))
4908 (setq-local org-lowest-priority (nth 1 priorities))
4909 (setq-local org-default-priority (nth 2 priorities))))
4910 ;; Scripts.
4911 (let ((scripts (assq 'scripts alist)))
4912 (when scripts
4913 (setq-local org-use-sub-superscripts (cdr scripts))))
4914 ;; TODO keywords.
4915 (setq-local org-todo-kwd-alist nil)
4916 (setq-local org-todo-key-alist nil)
4917 (setq-local org-todo-key-trigger nil)
4918 (setq-local org-todo-keywords-1 nil)
4919 (setq-local org-done-keywords nil)
4920 (setq-local org-todo-heads nil)
4921 (setq-local org-todo-sets nil)
4922 (setq-local org-todo-log-states nil)
4923 (let ((todo-sequences
4924 (or (nreverse (cdr (assq 'todo alist)))
4925 (let ((d (default-value 'org-todo-keywords)))
4926 (if (not (stringp (car d))) d
4927 ;; XXX: Backward compatibility code.
4928 (list (cons org-todo-interpretation d)))))))
4929 (dolist (sequence todo-sequences)
4930 (let* ((sequence (or (run-hook-with-args-until-success
4931 'org-todo-setup-filter-hook sequence)
4932 sequence))
4933 (sequence-type (car sequence))
4934 (keywords (cdr sequence))
4935 (sep (member "|" keywords))
4936 names alist)
4937 (dolist (k (remove "|" keywords))
4938 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4940 (error "Invalid TODO keyword %s" k))
4941 (let ((name (match-string 1 k))
4942 (key (match-string 2 k))
4943 (log (org-extract-log-state-settings k)))
4944 (push name names)
4945 (push (cons name (and key (string-to-char key))) alist)
4946 (when log (push log org-todo-log-states))))
4947 (let* ((names (nreverse names))
4948 (done (if sep (org-remove-keyword-keys (cdr sep))
4949 (last names)))
4950 (head (car names))
4951 (tail (list sequence-type head (car done) (org-last done))))
4952 (add-to-list 'org-todo-heads head 'append)
4953 (push names org-todo-sets)
4954 (setq org-done-keywords (append org-done-keywords done nil))
4955 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4956 (setq org-todo-key-alist
4957 (append org-todo-key-alist
4958 (and alist
4959 (append '((:startgroup))
4960 (nreverse alist)
4961 '((:endgroup))))))
4962 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4963 (setq org-todo-sets (nreverse org-todo-sets)
4964 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4965 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4966 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4967 ;; Compute the regular expressions and other local variables.
4968 ;; Using `org-outline-regexp-bol' would complicate them much,
4969 ;; because of the fixed white space at the end of that string.
4970 (unless org-done-keywords
4971 (setq org-done-keywords
4972 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4973 (setq org-not-done-keywords
4974 (org-delete-all org-done-keywords
4975 (copy-sequence org-todo-keywords-1))
4976 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4977 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4978 org-not-done-heading-regexp
4979 (format org-heading-keyword-regexp-format org-not-done-regexp)
4980 org-todo-line-regexp
4981 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4982 org-complex-heading-regexp
4983 (concat "^\\(\\*+\\)"
4984 "\\(?: +" org-todo-regexp "\\)?"
4985 "\\(?: +\\(\\[#.\\]\\)\\)?"
4986 "\\(?: +\\(.*?\\)\\)??"
4987 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4988 "[ \t]*$")
4989 org-complex-heading-regexp-format
4990 (concat "^\\(\\*+\\)"
4991 "\\(?: +" org-todo-regexp "\\)?"
4992 "\\(?: +\\(\\[#.\\]\\)\\)?"
4993 "\\(?: +"
4994 ;; Stats cookies can be stuck to body.
4995 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4996 "\\(%s\\)"
4997 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4998 "\\)"
4999 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5000 "[ \t]*$")
5001 org-todo-line-tags-regexp
5002 (concat "^\\(\\*+\\)"
5003 "\\(?: +" org-todo-regexp "\\)?"
5004 "\\(?: +\\(.*?\\)\\)??"
5005 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5006 "[ \t]*$"))
5007 (org-compute-latex-and-related-regexp)))))
5009 (defun org--setup-collect-keywords (regexp &optional files alist)
5010 "Return setup keywords values as an alist.
5012 REGEXP matches a subset of setup keywords. FILES is a list of
5013 file names already visited. It is used to avoid circular setup
5014 files. ALIST, when non-nil, is the alist computed so far.
5016 Return value contains the following keys: `archive', `category',
5017 `columns', `constants', `filetags', `link', `priorities',
5018 `property', `scripts', `startup', `tags' and `todo'."
5019 (org-with-wide-buffer
5020 (goto-char (point-min))
5021 (let ((case-fold-search t))
5022 (while (re-search-forward regexp nil t)
5023 (let ((element (org-element-at-point)))
5024 (when (eq (org-element-type element) 'keyword)
5025 (let ((key (org-element-property :key element))
5026 (value (org-element-property :value element)))
5027 (cond
5028 ((equal key "ARCHIVE")
5029 (when (org-string-nw-p value)
5030 (push (cons 'archive value) alist)))
5031 ((equal key "CATEGORY") (push (cons 'category value) alist))
5032 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5033 ((equal key "CONSTANTS")
5034 (let* ((constants (assq 'constants alist))
5035 (store (cdr constants)))
5036 (dolist (pair (split-string value))
5037 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5038 pair)
5039 (let* ((name (match-string 1 pair))
5040 (value (match-string 2 pair))
5041 (old (assoc name store)))
5042 (if old (setcdr old value)
5043 (push (cons name value) store)))))
5044 (if constants (setcdr constants store)
5045 (push (cons 'constants store) alist))))
5046 ((equal key "FILETAGS")
5047 (when (org-string-nw-p value)
5048 (let ((old (assq 'filetags alist))
5049 (new (apply #'nconc
5050 (mapcar (lambda (x) (org-split-string x ":"))
5051 (split-string value)))))
5052 (if old (setcdr old (append new (cdr old)))
5053 (push (cons 'filetags new) alist)))))
5054 ((equal key "LINK")
5055 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5056 (let ((links (assq 'link alist))
5057 (pair (cons (match-string-no-properties 1 value)
5058 (match-string-no-properties 2 value))))
5059 (if links (push pair (cdr links))
5060 (push (list 'link pair) alist)))))
5061 ((equal key "OPTIONS")
5062 (when (and (org-string-nw-p value)
5063 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5064 (push (cons 'scripts (read (match-string 1 value))) alist)))
5065 ((equal key "PRIORITIES")
5066 (push (cons 'priorities
5067 (let ((prio (split-string value)))
5068 (if (< (length prio) 3) '(?A ?C ?B)
5069 (mapcar #'string-to-char prio))))
5070 alist))
5071 ((equal key "PROPERTY")
5072 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5073 (let* ((property (assq 'property alist))
5074 (value (org--update-property-plist
5075 (match-string-no-properties 1 value)
5076 (match-string-no-properties 2 value)
5077 (cdr property))))
5078 (if property (setcdr property value)
5079 (push (cons 'property value) alist)))))
5080 ((equal key "STARTUP")
5081 (let ((startup (assq 'startup alist)))
5082 (if startup
5083 (setcdr startup
5084 (append (cdr startup) (split-string value)))
5085 (push (cons 'startup (split-string value)) alist))))
5086 ((equal key "TAGS")
5087 (let ((tag-cell (assq 'tags alist)))
5088 (if tag-cell
5089 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5090 (push (cons 'tags value) alist))))
5091 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5092 (let ((todo (assq 'todo alist))
5093 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5094 (split-string value))))
5095 (if todo (push value (cdr todo))
5096 (push (list 'todo value) alist))))
5097 ((equal key "SETUPFILE")
5098 (unless buffer-read-only ; Do not check in Gnus messages.
5099 (let ((f (and (org-string-nw-p value)
5100 (expand-file-name
5101 (org-unbracket-string "\"" "\"" value)))))
5102 (when (and f (file-readable-p f) (not (member f files)))
5103 (with-temp-buffer
5104 (setq default-directory (file-name-directory f))
5105 (insert-file-contents f)
5106 (setq alist
5107 ;; Fake Org mode to benefit from cache
5108 ;; without recurring needlessly.
5109 (let ((major-mode 'org-mode))
5110 (org--setup-collect-keywords
5111 regexp (cons f files) alist)))))))))))))))
5112 alist)
5114 (defun org-tag-string-to-alist (s)
5115 "Return tag alist associated to string S.
5116 S is a value for TAGS keyword or produced with
5117 `org-tag-alist-to-string'. Return value is an alist suitable for
5118 `org-tag-alist' or `org-tag-persistent-alist'."
5119 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5120 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5121 "\\(?:(\\(.\\))\\)?\\'"))
5122 alist group-flag)
5123 (dolist (tokens lines (cdr (nreverse alist)))
5124 (push '(:newline) alist)
5125 (while tokens
5126 (let ((token (pop tokens)))
5127 (pcase token
5128 ("{"
5129 (push '(:startgroup) alist)
5130 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5131 ("}"
5132 (push '(:endgroup) alist)
5133 (setq group-flag nil))
5134 ("["
5135 (push '(:startgrouptag) alist)
5136 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5137 ("]"
5138 (push '(:endgrouptag) alist)
5139 (setq group-flag nil))
5140 (":"
5141 (push '(:grouptags) alist))
5142 ((guard (string-match tag-re token))
5143 (let ((tag (match-string 1 token))
5144 (key (and (match-beginning 2)
5145 (string-to-char (match-string 2 token)))))
5146 ;; Push all tags in groups, no matter if they already
5147 ;; appear somewhere else in the list.
5148 (when (or group-flag (not (assoc tag alist)))
5149 (push (cons tag key) alist))))))))))
5151 (defun org-tag-alist-to-string (alist &optional skip-key)
5152 "Return tag string associated to ALIST.
5154 ALIST is an alist, as defined in `org-tag-alist' or
5155 `org-tag-persistent-alist', or produced with
5156 `org-tag-string-to-alist'.
5158 Return value is a string suitable as a value for \"TAGS\"
5159 keyword.
5161 When optional argument SKIP-KEY is non-nil, skip selection keys
5162 next to tags."
5163 (mapconcat (lambda (token)
5164 (pcase token
5165 (`(:startgroup) "{")
5166 (`(:endgroup) "}")
5167 (`(:startgrouptag) "[")
5168 (`(:endgrouptag) "]")
5169 (`(:grouptags) ":")
5170 (`(:newline) "\\n")
5171 ((and
5172 (guard (not skip-key))
5173 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5174 (format "%s(%c)" tag key))
5175 (`(,(and tag (pred stringp)) . ,_) tag)
5176 (_ (user-error "Invalid tag token: %S" token))))
5177 alist
5178 " "))
5180 (defun org-tag-alist-to-groups (alist)
5181 "Return group alist from tag ALIST.
5182 ALIST is an alist, as defined in `org-tag-alist' or
5183 `org-tag-persistent-alist', or produced with
5184 `org-tag-string-to-alist'. Return value is an alist following
5185 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5186 a string, summarizing TAGS, as a list of strings."
5187 (let (groups group-status current-group)
5188 (dolist (token alist (nreverse groups))
5189 (pcase token
5190 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5191 (`(,(or :endgroup :endgrouptag))
5192 (when (eq group-status 'append)
5193 (push (nreverse current-group) groups))
5194 (setq group-status nil current-group nil))
5195 (`(:grouptags) (setq group-status 'append))
5196 ((and `(,tag . ,_) (guard group-status))
5197 (if (eq group-status 'append) (push tag current-group)
5198 (setq current-group (list tag))))
5199 (_ nil)))))
5201 (defvar org--file-cache (make-hash-table :test #'equal)
5202 "Hash table to store contents of files referenced via a URL.
5203 This is the cache of file URLs read using `org-file-contents'.")
5205 (defun org-reset-file-cache ()
5206 "Reset the cache of files downloaded by `org-file-contents'."
5207 (clrhash org--file-cache))
5209 (defun org-file-url-p (file)
5210 "Non-nil if FILE is a URL."
5211 (require 'ffap)
5212 (string-match-p ffap-url-regexp file))
5214 (defun org-file-contents (file &optional noerror nocache)
5215 "Return the contents of FILE, as a string.
5217 FILE can be a file name or URL.
5219 If FILE is a URL, download the contents. If the URL contents are
5220 already cached in the `org--file-cache' hash table, the download step
5221 is skipped.
5223 If NOERROR is non-nil, ignore the error when unable to read the FILE
5224 from file or URL.
5226 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5227 is available. This option applies only if FILE is a URL."
5228 (let* ((is-url (org-file-url-p file))
5229 (cache (and is-url
5230 (not nocache)
5231 (gethash file org--file-cache))))
5232 (cond
5233 (cache)
5234 (is-url
5235 (with-current-buffer (url-retrieve-synchronously file)
5236 (goto-char (point-min))
5237 ;; Move point to after the url-retrieve header.
5238 (search-forward "\n\n" nil :move)
5239 ;; Search for the success code only in the url-retrieve header.
5240 (if (save-excursion
5241 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5242 ;; Update the cache `org--file-cache' and return contents.
5243 (puthash file
5244 (buffer-substring-no-properties (point) (point-max))
5245 org--file-cache)
5246 (funcall (if noerror #'message #'user-error)
5247 "Unable to fetch file from %S"
5248 file))))
5250 (with-temp-buffer
5251 (condition-case nil
5252 (progn
5253 (insert-file-contents file)
5254 (buffer-string))
5255 (file-error
5256 (funcall (if noerror #'message #'user-error)
5257 "Unable to read file %S"
5258 file))))))))
5260 (defun org-extract-log-state-settings (x)
5261 "Extract the log state setting from a TODO keyword string.
5262 This will extract info from a string like \"WAIT(w@/!)\"."
5263 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5264 (let ((kw (match-string 1 x))
5265 (log1 (and (match-end 3) (match-string 3 x)))
5266 (log2 (and (match-end 4) (match-string 4 x))))
5267 (and (or log1 log2)
5268 (list kw
5269 (and log1 (if (equal log1 "!") 'time 'note))
5270 (and log2 (if (equal log2 "!") 'time 'note)))))))
5272 (defun org-remove-keyword-keys (list)
5273 "Remove a pair of parenthesis at the end of each string in LIST."
5274 (mapcar (lambda (x)
5275 (if (string-match "(.*)$" x)
5276 (substring x 0 (match-beginning 0))
5278 list))
5280 (defun org-assign-fast-keys (alist)
5281 "Assign fast keys to a keyword-key alist.
5282 Respect keys that are already there."
5283 (let (new e (alt ?0))
5284 (while (setq e (pop alist))
5285 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5286 (cdr e)) ;; Key already assigned.
5287 (push e new)
5288 (let ((clist (string-to-list (downcase (car e))))
5289 (used (append new alist)))
5290 (when (= (car clist) ?@)
5291 (pop clist))
5292 (while (and clist (rassoc (car clist) used))
5293 (pop clist))
5294 (unless clist
5295 (while (rassoc alt used)
5296 (cl-incf alt)))
5297 (push (cons (car e) (or (car clist) alt)) new))))
5298 (nreverse new)))
5300 ;;; Some variables used in various places
5302 (defvar org-window-configuration nil
5303 "Used in various places to store a window configuration.")
5304 (defvar org-selected-window nil
5305 "Used in various places to store a window configuration.")
5306 (defvar org-finish-function nil
5307 "Function to be called when `C-c C-c' is used.
5308 This is for getting out of special buffers like capture.")
5309 (defvar org-last-state)
5311 ;; Defined somewhere in this file, but used before definition.
5312 (defvar org-entities) ;; defined in org-entities.el
5313 (defvar org-struct-menu)
5314 (defvar org-org-menu)
5315 (defvar org-tbl-menu)
5317 ;;;; Define the Org mode
5319 ;; We use a before-change function to check if a table might need
5320 ;; an update.
5321 (defvar org-table-may-need-update t
5322 "Indicates that a table might need an update.
5323 This variable is set by `org-before-change-function'.
5324 `org-table-align' sets it back to nil.")
5325 (defun org-before-change-function (_beg _end)
5326 "Every change indicates that a table might need an update."
5327 (setq org-table-may-need-update t))
5328 (defvar org-mode-map)
5329 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5330 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5331 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5332 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5333 (defvar org-table-buffer-is-an nil)
5335 (defvar bidi-paragraph-direction)
5336 (defvar buffer-face-mode-face)
5338 (require 'outline)
5340 ;; Other stuff we need.
5341 (require 'time-date)
5342 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5343 (require 'easymenu)
5344 (autoload 'easy-menu-add "easymenu")
5345 (require 'overlay)
5347 ;; (require 'org-macs) moved higher up in the file before it is first used
5348 (require 'org-entities)
5349 ;; (require 'org-compat) moved higher up in the file before it is first used
5350 (require 'org-faces)
5351 (require 'org-list)
5352 (require 'org-pcomplete)
5353 (require 'org-src)
5354 (require 'org-footnote)
5355 (require 'org-macro)
5357 ;; babel
5358 (require 'ob)
5360 ;;;###autoload
5361 (define-derived-mode org-mode outline-mode "Org"
5362 "Outline-based notes management and organizer, alias
5363 \"Carsten's outline-mode for keeping track of everything.\"
5365 Org mode develops organizational tasks around a NOTES file which
5366 contains information about projects as plain text. Org mode is
5367 implemented on top of Outline mode, which is ideal to keep the content
5368 of large files well structured. It supports ToDo items, deadlines and
5369 time stamps, which magically appear in the diary listing of the Emacs
5370 calendar. Tables are easily created with a built-in table editor.
5371 Plain text URL-like links connect to websites, emails (VM), Usenet
5372 messages (Gnus), BBDB entries, and any files related to the project.
5373 For printing and sharing of notes, an Org file (or a part of it)
5374 can be exported as a structured ASCII or HTML file.
5376 The following commands are available:
5378 \\{org-mode-map}"
5380 ;; Get rid of Outline menus, they are not needed
5381 ;; Need to do this here because define-derived-mode sets up
5382 ;; the keymap so late. Still, it is a waste to call this each time
5383 ;; we switch another buffer into Org mode.
5384 (define-key org-mode-map [menu-bar headings] 'undefined)
5385 (define-key org-mode-map [menu-bar hide] 'undefined)
5386 (define-key org-mode-map [menu-bar show] 'undefined)
5388 (org-load-modules-maybe)
5389 (org-install-agenda-files-menu)
5390 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5391 (add-to-invisibility-spec '(org-hide-block . t))
5392 (add-to-invisibility-spec '(org-hide-drawer . t))
5393 (setq-local outline-regexp org-outline-regexp)
5394 (setq-local outline-level 'org-outline-level)
5395 (setq bidi-paragraph-direction 'left-to-right)
5396 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5397 (unless org-display-table
5398 (setq org-display-table (make-display-table)))
5399 (set-display-table-slot
5400 org-display-table 4
5401 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5402 org-ellipsis)))
5403 (setq buffer-display-table org-display-table))
5404 (org-set-regexps-and-options)
5405 (org-set-font-lock-defaults)
5406 (when (and org-tag-faces (not org-tags-special-faces-re))
5407 ;; tag faces set outside customize.... force initialization.
5408 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5409 ;; Calc embedded
5410 (setq-local calc-embedded-open-mode "# ")
5411 ;; Modify a few syntax entries
5412 (modify-syntax-entry ?@ "w")
5413 (modify-syntax-entry ?\" "\"")
5414 (modify-syntax-entry ?\\ "_")
5415 (modify-syntax-entry ?~ "_")
5416 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5417 ;; Activate before-change-function
5418 (setq-local org-table-may-need-update t)
5419 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5420 ;; Check for running clock before killing a buffer
5421 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5422 ;; Initialize macros templates.
5423 (org-macro-initialize-templates)
5424 ;; Initialize radio targets.
5425 (org-update-radio-target-regexp)
5426 ;; Indentation.
5427 (setq-local indent-line-function 'org-indent-line)
5428 (setq-local indent-region-function 'org-indent-region)
5429 ;; Filling and auto-filling.
5430 (org-setup-filling)
5431 ;; Comments.
5432 (org-setup-comments-handling)
5433 ;; Initialize cache.
5434 (org-element-cache-reset)
5435 ;; Beginning/end of defun
5436 (setq-local beginning-of-defun-function 'org-backward-element)
5437 (setq-local end-of-defun-function
5438 (lambda ()
5439 (if (not (org-at-heading-p))
5440 (org-forward-element)
5441 (org-forward-element)
5442 (forward-char -1))))
5443 ;; Next error for sparse trees
5444 (setq-local next-error-function 'org-occur-next-match)
5445 ;; Make sure dependence stuff works reliably, even for users who set it
5446 ;; too late :-(
5447 (if org-enforce-todo-dependencies
5448 (add-hook 'org-blocker-hook
5449 'org-block-todo-from-children-or-siblings-or-parent)
5450 (remove-hook 'org-blocker-hook
5451 'org-block-todo-from-children-or-siblings-or-parent))
5452 (if org-enforce-todo-checkbox-dependencies
5453 (add-hook 'org-blocker-hook
5454 'org-block-todo-from-checkboxes)
5455 (remove-hook 'org-blocker-hook
5456 'org-block-todo-from-checkboxes))
5458 ;; Align options lines
5459 (setq-local
5460 align-mode-rules-list
5461 '((org-in-buffer-settings
5462 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5463 (modes . '(org-mode)))))
5465 ;; Imenu
5466 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5468 ;; Make isearch reveal context
5469 (setq-local outline-isearch-open-invisible-function
5470 (lambda (&rest _) (org-show-context 'isearch)))
5472 ;; Setup the pcomplete hooks
5473 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5474 (setq-local pcomplete-command-name-function 'org-command-at-point)
5475 (setq-local pcomplete-default-completion-function 'ignore)
5476 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5477 (setq-local pcomplete-termination-string "")
5478 (setq-local buffer-face-mode-face 'org-default)
5480 ;; If empty file that did not turn on Org mode automatically, make
5481 ;; it to.
5482 (when (and org-insert-mode-line-in-empty-file
5483 (called-interactively-p 'any)
5484 (= (point-min) (point-max)))
5485 (insert "# -*- mode: org -*-\n\n"))
5486 (unless org-inhibit-startup
5487 (org-unmodified
5488 (when org-startup-with-beamer-mode (org-beamer-mode))
5489 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5490 (org-table-map-tables
5491 (cond ((and org-startup-align-all-tables
5492 org-startup-shrink-all-tables)
5493 (lambda () (org-table-align) (org-table-shrink)))
5494 (org-startup-align-all-tables #'org-table-align)
5495 (t #'org-table-shrink))
5497 (when org-startup-with-inline-images (org-display-inline-images))
5498 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5499 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5500 (when org-startup-truncated (setq truncate-lines t))
5501 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5502 (org-refresh-effort-properties)))
5503 ;; Try to set `org-hide' face correctly.
5504 (let ((foreground (org-find-invisible-foreground)))
5505 (when foreground
5506 (set-face-foreground 'org-hide foreground))))
5508 ;; Update `customize-package-emacs-version-alist'
5509 (add-to-list 'customize-package-emacs-version-alist
5510 '(Org ("8.0" . "24.4")
5511 ("8.1" . "24.4")
5512 ("8.2" . "24.4")
5513 ("8.2.7" . "24.4")
5514 ("8.3" . "26.1")
5515 ("9.0" . "26.1")
5516 ("9.1" . "26.1")
5517 ("9.2" . "27.1")))
5519 (defvar org-mode-transpose-word-syntax-table
5520 (let ((st (make-syntax-table text-mode-syntax-table)))
5521 (dolist (c org-emphasis-alist st)
5522 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5524 (when (fboundp 'abbrev-table-put)
5525 (abbrev-table-put org-mode-abbrev-table
5526 :parents (list text-mode-abbrev-table)))
5528 (defun org-find-invisible-foreground ()
5529 (let ((candidates (remove
5530 "unspecified-bg"
5531 (nconc
5532 (list (face-background 'default)
5533 (face-background 'org-default))
5534 (mapcar
5535 (lambda (alist)
5536 (when (boundp alist)
5537 (cdr (assq 'background-color (symbol-value alist)))))
5538 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5539 (list (face-foreground 'org-hide))))))
5540 (car (remove nil candidates))))
5542 (defun org-current-time (&optional rounding-minutes past)
5543 "Current time, possibly rounded to ROUNDING-MINUTES.
5544 When ROUNDING-MINUTES is not an integer, fall back on the car of
5545 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5546 the rounding returns a past time."
5547 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5548 (car org-time-stamp-rounding-minutes)))
5549 (time (decode-time)) res)
5550 (if (< r 1)
5551 (current-time)
5552 (setq res
5553 (apply 'encode-time
5554 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5555 (nthcdr 2 time))))
5556 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5557 (seconds-to-time (- (float-time res) (* r 60)))
5558 res))))
5560 (defun org-today ()
5561 "Return today date, considering `org-extend-today-until'."
5562 (time-to-days
5563 (time-subtract (current-time)
5564 (list 0 (* 3600 org-extend-today-until) 0))))
5566 ;;;; Font-Lock stuff, including the activators
5568 (defvar org-mouse-map (make-sparse-keymap))
5569 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5570 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5571 (when org-mouse-1-follows-link
5572 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5573 (when org-tab-follows-link
5574 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5575 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5577 (require 'font-lock)
5579 (defconst org-non-link-chars "]\t\n\r<>")
5580 (defvar org-link-types-re nil
5581 "Matches a link that has a url-like prefix like \"http:\"")
5582 (defvar org-link-re-with-space nil
5583 "Matches a link with spaces, optional angular brackets around it.")
5584 (defvar org-link-re-with-space2 nil
5585 "Matches a link with spaces, optional angular brackets around it.")
5586 (defvar org-link-re-with-space3 nil
5587 "Matches a link with spaces, only for internal part in bracket links.")
5588 (defvar org-angle-link-re nil
5589 "Matches link with angular brackets, spaces are allowed.")
5590 (defvar org-plain-link-re nil
5591 "Matches plain link, without spaces.")
5592 (defvar org-bracket-link-regexp nil
5593 "Matches a link in double brackets.")
5594 (defvar org-bracket-link-analytic-regexp nil
5595 "Regular expression used to analyze links.
5596 Here is what the match groups contain after a match:
5597 1: http:
5598 2: http
5599 3: path
5600 4: [desc]
5601 5: desc")
5602 (defvar org-bracket-link-analytic-regexp++ nil
5603 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5604 (defvar org-any-link-re nil
5605 "Regular expression matching any link.")
5607 (defconst org-match-sexp-depth 3
5608 "Number of stacked braces for sub/superscript matching.")
5610 (defun org-create-multibrace-regexp (left right n)
5611 "Create a regular expression which will match a balanced sexp.
5612 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5613 as single character strings.
5614 The regexp returned will match the entire expression including the
5615 delimiters. It will also define a single group which contains the
5616 match except for the outermost delimiters. The maximum depth of
5617 stacked delimiters is N. Escaping delimiters is not possible."
5618 (let* ((nothing (concat "[^" left right "]*?"))
5619 (or "\\|")
5620 (re nothing)
5621 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5622 (while (> n 1)
5623 (setq n (1- n)
5624 re (concat re or next)
5625 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5626 (concat left "\\(" re "\\)" right)))
5628 (defconst org-match-substring-regexp
5629 (concat
5630 "\\(\\S-\\)\\([_^]\\)\\("
5631 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5632 "\\|"
5633 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5634 "\\|"
5635 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5636 "The regular expression matching a sub- or superscript.")
5638 (defconst org-match-substring-with-braces-regexp
5639 (concat
5640 "\\(\\S-\\)\\([_^]\\)"
5641 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5642 "The regular expression matching a sub- or superscript, forcing braces.")
5644 (defun org-make-link-regexps ()
5645 "Update the link regular expressions.
5646 This should be called after the variable `org-link-parameters' has changed."
5647 (let ((types-re (regexp-opt (org-link-types) t)))
5648 (setq org-link-types-re
5649 (concat "\\`" types-re ":")
5650 org-link-re-with-space
5651 (concat "<?" types-re ":"
5652 "\\([^" org-non-link-chars " ]"
5653 "[^" org-non-link-chars "]*"
5654 "[^" org-non-link-chars " ]\\)>?")
5655 org-link-re-with-space2
5656 (concat "<?" types-re ":"
5657 "\\([^" org-non-link-chars " ]"
5658 "[^\t\n\r]*"
5659 "[^" org-non-link-chars " ]\\)>?")
5660 org-link-re-with-space3
5661 (concat "<?" types-re ":"
5662 "\\([^" org-non-link-chars " ]"
5663 "[^\t\n\r]*\\)")
5664 org-angle-link-re
5665 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5666 types-re)
5667 org-plain-link-re
5668 (concat
5669 "\\<" types-re ":"
5670 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5671 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5672 org-bracket-link-regexp
5673 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5674 org-bracket-link-analytic-regexp
5675 (concat
5676 "\\[\\["
5677 "\\(" types-re ":\\)?"
5678 "\\([^]]+\\)"
5679 "\\]"
5680 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5681 "\\]")
5682 org-bracket-link-analytic-regexp++
5683 (concat
5684 "\\[\\["
5685 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5686 "\\([^]]+\\)"
5687 "\\]"
5688 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5689 "\\]")
5690 org-any-link-re
5691 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5692 org-angle-link-re "\\)\\|\\("
5693 org-plain-link-re "\\)"))))
5695 (org-make-link-regexps)
5697 (defvar org-emph-face nil)
5699 (defun org-do-emphasis-faces (limit)
5700 "Run through the buffer and emphasize strings."
5701 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5702 (car org-emphasis-regexp-components))))
5703 (catch :exit
5704 (while (re-search-forward quick-re limit t)
5705 (let* ((marker (match-string 2))
5706 (verbatim? (member marker '("~" "="))))
5707 (when (save-excursion
5708 (goto-char (match-beginning 0))
5709 (and
5710 ;; Do not match table hlines.
5711 (not (and (equal marker "+")
5712 (org-match-line
5713 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5714 ;; Do not match headline stars. Do not consider
5715 ;; stars of a headline as closing marker for bold
5716 ;; markup either.
5717 (not (and (equal marker "*")
5718 (save-excursion
5719 (forward-char)
5720 (skip-chars-backward "*")
5721 (looking-at-p org-outline-regexp-bol))))
5722 ;; Match full emphasis markup regexp.
5723 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5724 ;; Do not span over paragraph boundaries.
5725 (not (string-match-p org-element-paragraph-separate
5726 (match-string 2)))
5727 ;; Do not span over cells in table rows.
5728 (not (and (save-match-data (org-match-line "[ \t]*|"))
5729 (string-match-p "|" (match-string 4))))))
5730 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5731 (font-lock-prepend-text-property
5732 (match-beginning 2) (match-end 2) 'face face)
5733 (when verbatim?
5734 (org-remove-flyspell-overlays-in
5735 (match-beginning 0) (match-end 0)))
5736 (add-text-properties (match-beginning 2) (match-end 2)
5737 '(font-lock-multiline t org-emphasis t))
5738 (when org-hide-emphasis-markers
5739 (add-text-properties (match-end 4) (match-beginning 5)
5740 '(invisible org-link))
5741 (add-text-properties (match-beginning 3) (match-end 3)
5742 '(invisible org-link)))
5743 (throw :exit t))))))))
5745 (defun org-emphasize (&optional char)
5746 "Insert or change an emphasis, i.e. a font like bold or italic.
5747 If there is an active region, change that region to a new emphasis.
5748 If there is no region, just insert the marker characters and position
5749 the cursor between them.
5750 CHAR should be the marker character. If it is a space, it means to
5751 remove the emphasis of the selected region.
5752 If CHAR is not given (for example in an interactive call) it will be
5753 prompted for."
5754 (interactive)
5755 (let ((erc org-emphasis-regexp-components)
5756 (string "") beg end move s)
5757 (if (org-region-active-p)
5758 (setq beg (region-beginning)
5759 end (region-end)
5760 string (buffer-substring beg end))
5761 (setq move t))
5763 (unless char
5764 (message "Emphasis marker or tag: [%s]"
5765 (mapconcat #'car org-emphasis-alist ""))
5766 (setq char (read-char-exclusive)))
5767 (if (equal char ?\s)
5768 (setq s ""
5769 move nil)
5770 (unless (assoc (char-to-string char) org-emphasis-alist)
5771 (user-error "No such emphasis marker: \"%c\"" char))
5772 (setq s (char-to-string char)))
5773 (while (and (> (length string) 1)
5774 (equal (substring string 0 1) (substring string -1))
5775 (assoc (substring string 0 1) org-emphasis-alist))
5776 (setq string (substring string 1 -1)))
5777 (setq string (concat s string s))
5778 (when beg (delete-region beg end))
5779 (unless (or (bolp)
5780 (string-match (concat "[" (nth 0 erc) "\n]")
5781 (char-to-string (char-before (point)))))
5782 (insert " "))
5783 (unless (or (eobp)
5784 (string-match (concat "[" (nth 1 erc) "\n]")
5785 (char-to-string (char-after (point)))))
5786 (insert " ") (backward-char 1))
5787 (insert string)
5788 (and move (backward-char 1))))
5790 (defconst org-nonsticky-props
5791 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5793 (defsubst org-rear-nonsticky-at (pos)
5794 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5796 (defun org-activate-links (limit)
5797 "Add link properties to links.
5798 This includes angle, plain, and bracket links."
5799 (catch :exit
5800 (while (re-search-forward org-any-link-re limit t)
5801 (let* ((start (match-beginning 0))
5802 (end (match-end 0))
5803 (style (cond ((eq ?< (char-after start)) 'angle)
5804 ((eq ?\[ (char-after (1+ start))) 'bracket)
5805 (t 'plain))))
5806 (when (and (memq style org-highlight-links)
5807 ;; Do not confuse plain links with tags.
5808 (not (and (eq style 'plain)
5809 (let ((face (get-text-property
5810 (max (1- start) (point-min)) 'face)))
5811 (if (consp face) (memq 'org-tag face)
5812 (eq 'org-tag face))))))
5813 (let* ((link-object (save-excursion
5814 (goto-char start)
5815 (save-match-data (org-element-link-parser))))
5816 (link (org-element-property :raw-link link-object))
5817 (type (org-element-property :type link-object))
5818 (path (org-element-property :path link-object))
5819 (properties ;for link's visible part
5820 (list
5821 'face (pcase (org-link-get-parameter type :face)
5822 ((and (pred functionp) face) (funcall face path))
5823 ((and (pred facep) face) face)
5824 ((and (pred consp) face) face) ;anonymous
5825 (_ 'org-link))
5826 'mouse-face (or (org-link-get-parameter type :mouse-face)
5827 'highlight)
5828 'keymap (or (org-link-get-parameter type :keymap)
5829 org-mouse-map)
5830 'help-echo (pcase (org-link-get-parameter type :help-echo)
5831 ((and (pred stringp) echo) echo)
5832 ((and (pred functionp) echo) echo)
5833 (_ (concat "LINK: " link)))
5834 'htmlize-link (pcase (org-link-get-parameter type
5835 :htmlize-link)
5836 ((and (pred functionp) f) (funcall f))
5837 (_ `(:uri ,link)))
5838 'font-lock-multiline t)))
5839 (org-remove-flyspell-overlays-in start end)
5840 (org-rear-nonsticky-at end)
5841 (if (not (eq 'bracket style))
5842 (add-text-properties start end properties)
5843 ;; Handle invisible parts in bracket links.
5844 (remove-text-properties start end '(invisible nil))
5845 (let ((hidden
5846 (append `(invisible
5847 ,(or (org-link-get-parameter type :display)
5848 'org-link))
5849 properties))
5850 (visible-start (or (match-beginning 4) (match-beginning 2)))
5851 (visible-end (or (match-end 4) (match-end 2))))
5852 (add-text-properties start visible-start hidden)
5853 (add-text-properties visible-start visible-end properties)
5854 (add-text-properties visible-end end hidden)
5855 (org-rear-nonsticky-at visible-start)
5856 (org-rear-nonsticky-at visible-end)))
5857 (let ((f (org-link-get-parameter type :activate-func)))
5858 (when (functionp f)
5859 (funcall f start end path (eq style 'bracket))))
5860 (throw :exit t))))) ;signal success
5861 nil))
5863 (defun org-activate-code (limit)
5864 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5865 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5866 (remove-text-properties (match-beginning 0) (match-end 0)
5867 '(display t invisible t intangible t))
5870 (defcustom org-src-fontify-natively t
5871 "When non-nil, fontify code in code blocks.
5872 See also the `org-block' face."
5873 :type 'boolean
5874 :version "26.1"
5875 :package-version '(Org . "8.3")
5876 :group 'org-appearance
5877 :group 'org-babel)
5879 (defcustom org-allow-promoting-top-level-subtree nil
5880 "When non-nil, allow promoting a top level subtree.
5881 The leading star of the top level headline will be replaced
5882 by a #."
5883 :type 'boolean
5884 :version "24.1"
5885 :group 'org-appearance)
5887 (defun org-fontify-meta-lines-and-blocks (limit)
5888 (condition-case nil
5889 (org-fontify-meta-lines-and-blocks-1 limit)
5890 (error (message "Org mode fontification error in %S at %d"
5891 (current-buffer)
5892 (line-number-at-pos)))))
5894 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5895 "Fontify #+ lines and blocks."
5896 (let ((case-fold-search t))
5897 (when (re-search-forward
5898 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5899 limit t)
5900 (let ((beg (match-beginning 0))
5901 (block-start (match-end 0))
5902 (block-end nil)
5903 (lang (match-string 7))
5904 (beg1 (line-beginning-position 2))
5905 (dc1 (downcase (match-string 2)))
5906 (dc3 (downcase (match-string 3)))
5907 end end1 quoting block-type)
5908 (cond
5909 ((and (match-end 4) (equal dc3 "+begin"))
5910 ;; Truly a block
5911 (setq block-type (downcase (match-string 5))
5912 quoting (member block-type org-protecting-blocks))
5913 (when (re-search-forward
5914 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5915 nil t) ;; on purpose, we look further than LIMIT
5916 (setq end (min (point-max) (match-end 0))
5917 end1 (min (point-max) (1- (match-beginning 0))))
5918 (setq block-end (match-beginning 0))
5919 (when quoting
5920 (org-remove-flyspell-overlays-in beg1 end1)
5921 (remove-text-properties beg end
5922 '(display t invisible t intangible t)))
5923 (add-text-properties
5924 beg end '(font-lock-fontified t font-lock-multiline t))
5925 (add-text-properties beg beg1 '(face org-meta-line))
5926 (org-remove-flyspell-overlays-in beg beg1)
5927 (add-text-properties ; For end_src
5928 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5929 (org-remove-flyspell-overlays-in end1 end)
5930 (cond
5931 ((and lang (not (string= lang "")) org-src-fontify-natively)
5932 (org-src-font-lock-fontify-block lang block-start block-end)
5933 (add-text-properties beg1 block-end '(src-block t)))
5934 (quoting
5935 (add-text-properties beg1 (min (point-max) (1+ end1))
5936 (list 'face
5937 (list :inherit
5938 (let ((face-name
5939 (intern (format "org-block-%s" lang))))
5940 (append (and (facep face-name) (list face-name))
5941 '(org-block))))))) ; end of source block
5942 ((not org-fontify-quote-and-verse-blocks))
5943 ((string= block-type "quote")
5944 (add-face-text-property
5945 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5946 ((string= block-type "verse")
5947 (add-face-text-property
5948 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5949 (add-text-properties beg beg1 '(face org-block-begin-line))
5950 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5951 '(face org-block-end-line))
5953 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5954 (org-remove-flyspell-overlays-in
5955 (match-beginning 0)
5956 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5957 (add-text-properties
5958 beg (match-end 3)
5959 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5960 '(font-lock-fontified t invisible t)
5961 '(font-lock-fontified t face org-document-info-keyword)))
5962 (add-text-properties
5963 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5964 (if (string-equal dc1 "+title:")
5965 '(font-lock-fontified t face org-document-title)
5966 '(font-lock-fontified t face org-document-info))))
5967 ((string-prefix-p "+caption" dc1)
5968 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5969 (remove-text-properties (match-beginning 0) (match-end 0)
5970 '(display t invisible t intangible t))
5971 ;; Handle short captions.
5972 (save-excursion
5973 (beginning-of-line)
5974 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5975 (add-text-properties (line-beginning-position) (match-end 1)
5976 '(font-lock-fontified t face org-meta-line))
5977 (add-text-properties (match-end 0) (line-end-position)
5978 '(font-lock-fontified t face org-block))
5980 ((member dc3 '(" " ""))
5981 (org-remove-flyspell-overlays-in beg (match-end 0))
5982 (add-text-properties
5983 beg (match-end 0)
5984 '(font-lock-fontified t face font-lock-comment-face)))
5985 (t ;; just any other in-buffer setting, but not indented
5986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5987 (remove-text-properties (match-beginning 0) (match-end 0)
5988 '(display t invisible t intangible t))
5989 (add-text-properties beg (match-end 0)
5990 '(font-lock-fontified t face org-meta-line))
5991 t))))))
5993 (defun org-fontify-drawers (limit)
5994 "Fontify drawers."
5995 (when (re-search-forward org-drawer-regexp limit t)
5996 (add-text-properties
5997 (match-beginning 0) (match-end 0)
5998 '(font-lock-fontified t face org-special-keyword))
5999 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6002 (defun org-fontify-macros (limit)
6003 "Fontify macros."
6004 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6005 (let ((begin (match-beginning 0))
6006 (opening-end (match-beginning 1)))
6007 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6008 (match-string 1))
6009 (let ((end (match-end 1))
6010 (closing-start (match-beginning 1)))
6011 (add-text-properties
6012 begin end
6013 '(font-lock-multiline t font-lock-fontified t face org-macro))
6014 (org-remove-flyspell-overlays-in begin end)
6015 (when org-hide-macro-markers
6016 (add-text-properties begin opening-end '(invisible t))
6017 (add-text-properties closing-start end '(invisible t)))
6018 t)))))
6020 (defun org-activate-footnote-links (limit)
6021 "Add text properties for footnotes."
6022 (let ((fn (org-footnote-next-reference-or-definition limit)))
6023 (when fn
6024 (let* ((beg (nth 1 fn))
6025 (end (nth 2 fn))
6026 (label (car fn))
6027 (referencep (/= (line-beginning-position) beg)))
6028 (when (and referencep (nth 3 fn))
6029 (save-excursion
6030 (goto-char beg)
6031 (search-forward (or label "fn:"))
6032 (org-remove-flyspell-overlays-in beg (match-end 0))))
6033 (add-text-properties beg end
6034 (list 'mouse-face 'highlight
6035 'keymap org-mouse-map
6036 'help-echo
6037 (if referencep "Footnote reference"
6038 "Footnote definition")
6039 'font-lock-fontified t
6040 'font-lock-multiline t
6041 'face 'org-footnote))))))
6043 (defun org-activate-dates (limit)
6044 "Add text properties for dates."
6045 (when (and (re-search-forward org-tsr-regexp-both limit t)
6046 (not (equal (char-before (match-beginning 0)) 91)))
6047 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6048 (add-text-properties (match-beginning 0) (match-end 0)
6049 (list 'mouse-face 'highlight
6050 'keymap org-mouse-map))
6051 (org-rear-nonsticky-at (match-end 0))
6052 (when org-display-custom-times
6053 ;; If it's a date range, activate custom time for second date.
6054 (when (match-end 3)
6055 (org-display-custom-time (match-beginning 3) (match-end 3)))
6056 (org-display-custom-time (match-beginning 1) (match-end 1)))
6059 (defvar-local org-target-link-regexp nil
6060 "Regular expression matching radio targets in plain text.")
6062 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6063 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6064 border border border))
6065 "Regular expression matching a link target.")
6067 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6068 "Regular expression matching a radio target.")
6070 (defconst org-any-target-regexp
6071 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6072 "Regular expression matching any target.")
6074 (defun org-activate-target-links (limit)
6075 "Add text properties for target matches."
6076 (when org-target-link-regexp
6077 (let ((case-fold-search t))
6078 (when (re-search-forward org-target-link-regexp limit t)
6079 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6080 (add-text-properties (match-beginning 1) (match-end 1)
6081 (list 'mouse-face 'highlight
6082 'keymap org-mouse-map
6083 'help-echo "Radio target link"
6084 'org-linked-text t))
6085 (org-rear-nonsticky-at (match-end 1))
6086 t))))
6088 (defun org-update-radio-target-regexp ()
6089 "Find all radio targets in this file and update the regular expression.
6090 Also refresh fontification if needed."
6091 (interactive)
6092 (let ((old-regexp org-target-link-regexp)
6093 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6094 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6095 (targets
6096 (org-with-wide-buffer
6097 (goto-char (point-min))
6098 (let (rtn)
6099 (while (re-search-forward org-radio-target-regexp nil t)
6100 ;; Make sure point is really within the object.
6101 (backward-char)
6102 (let ((obj (org-element-context)))
6103 (when (eq (org-element-type obj) 'radio-target)
6104 (cl-pushnew (org-element-property :value obj) rtn
6105 :test #'equal))))
6106 rtn))))
6107 (setq org-target-link-regexp
6108 (and targets
6109 (concat before-re
6110 (mapconcat
6111 (lambda (x)
6112 (replace-regexp-in-string
6113 " +" "\\s-+" (regexp-quote x) t t))
6114 targets
6115 "\\|")
6116 after-re)))
6117 (unless (equal old-regexp org-target-link-regexp)
6118 ;; Clean-up cache.
6119 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6120 ((not org-target-link-regexp) old-regexp)
6122 (concat before-re
6123 (mapconcat
6124 (lambda (re)
6125 (substring re (length before-re)
6126 (- (length after-re))))
6127 (list old-regexp org-target-link-regexp)
6128 "\\|")
6129 after-re)))))
6130 (org-with-wide-buffer
6131 (goto-char (point-min))
6132 (while (re-search-forward regexp nil t)
6133 (org-element-cache-refresh (match-beginning 1)))))
6134 ;; Re fontify buffer.
6135 (when (memq 'radio org-highlight-links)
6136 (org-restart-font-lock)))))
6138 (defvar org-latex-and-related-regexp nil
6139 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6141 (defun org-compute-latex-and-related-regexp ()
6142 "Compute regular expression for LaTeX, entities and sub/superscript.
6143 Result depends on variable `org-highlight-latex-and-related'."
6144 (setq-local
6145 org-latex-and-related-regexp
6146 (let* ((re-sub
6147 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6148 ((eq org-use-sub-superscripts '{})
6149 (list org-match-substring-with-braces-regexp))
6150 (org-use-sub-superscripts (list org-match-substring-regexp))))
6151 (re-latex
6152 (when (memq 'latex org-highlight-latex-and-related)
6153 (let ((matchers (plist-get org-format-latex-options :matchers)))
6154 (delq nil
6155 (mapcar (lambda (x)
6156 (and (member (car x) matchers) (nth 1 x)))
6157 org-latex-regexps)))))
6158 (re-entities
6159 (when (memq 'entities org-highlight-latex-and-related)
6160 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6161 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6163 (defun org-do-latex-and-related (limit)
6164 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6165 LIMIT bounds the search for syntax to highlight. Stop at first
6166 highlighted object, if any. Return t if some highlighting was
6167 done, nil otherwise."
6168 (when (org-string-nw-p org-latex-and-related-regexp)
6169 (catch 'found
6170 (while (re-search-forward org-latex-and-related-regexp limit t)
6171 (unless
6172 (cl-some
6173 (lambda (f)
6174 (memq f '(org-code org-verbatim underline org-special-keyword)))
6175 (save-excursion
6176 (goto-char (1+ (match-beginning 0)))
6177 (face-at-point nil t)))
6178 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6179 '(?_ ?^))
6181 0)))
6182 (font-lock-prepend-text-property
6183 (+ offset (match-beginning 0)) (match-end 0)
6184 'face 'org-latex-and-related)
6185 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6186 '(font-lock-multiline t)))
6187 (throw 'found t)))
6188 nil)))
6190 (defun org-restart-font-lock ()
6191 "Restart `font-lock-mode', to force refontification."
6192 (when (and (boundp 'font-lock-mode) font-lock-mode)
6193 (font-lock-mode -1)
6194 (font-lock-mode 1)))
6196 (defun org-activate-tags (limit)
6197 (when (re-search-forward org-tag-line-re limit t)
6198 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6199 (add-text-properties (match-beginning 1) (match-end 1)
6200 (list 'mouse-face 'highlight
6201 'keymap org-mouse-map))
6202 (org-rear-nonsticky-at (match-end 1))
6205 (defun org-outline-level ()
6206 "Compute the outline level of the heading at point.
6208 If this is called at a normal headline, the level is the number
6209 of stars. Use `org-reduced-level' to remove the effect of
6210 `org-odd-levels'. Unlike to `org-current-level', this function
6211 takes into consideration inlinetasks."
6212 (org-with-wide-buffer
6213 (end-of-line)
6214 (if (re-search-backward org-outline-regexp-bol nil t)
6215 (1- (- (match-end 0) (match-beginning 0)))
6216 0)))
6218 (defvar org-font-lock-keywords nil)
6220 (defsubst org-re-property (property &optional literal allow-null value)
6221 "Return a regexp matching a PROPERTY line.
6223 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6224 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6225 non-nil, match properties even without a value.
6227 Match group 3 is set to the value when it exists. If there is no
6228 value and ALLOW-NULL is non-nil, it is set to the empty string.
6230 With optional argument VALUE, match only property lines with
6231 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6232 unless LITERAL is non-nil."
6233 (concat
6234 "^\\(?4:[ \t]*\\)"
6235 (format "\\(?1::\\(?2:%s\\):\\)"
6236 (if literal property (regexp-quote property)))
6237 (cond (value
6238 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6239 (if literal value (regexp-quote value))))
6240 (allow-null
6241 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6243 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6245 (defconst org-property-re
6246 (org-re-property "\\S-+" 'literal t)
6247 "Regular expression matching a property line.
6248 There are four matching groups:
6249 1: :PROPKEY: including the leading and trailing colon,
6250 2: PROPKEY without the leading and trailing colon,
6251 3: PROPVAL without leading or trailing spaces,
6252 4: the indentation of the current line,
6253 5: trailing whitespace.")
6255 (defvar org-font-lock-hook nil
6256 "Functions to be called for special font lock stuff.")
6258 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6260 (defvar org-font-lock-set-keywords-hook nil
6261 "Functions that can manipulate `org-font-lock-extra-keywords'.
6262 This is called after `org-font-lock-extra-keywords' is defined, but before
6263 it is installed to be used by font lock. This can be useful if something
6264 needs to be inserted at a specific position in the font-lock sequence.")
6266 (defun org-font-lock-hook (limit)
6267 "Run `org-font-lock-hook' within LIMIT."
6268 (run-hook-with-args 'org-font-lock-hook limit))
6270 (defun org-set-font-lock-defaults ()
6271 "Set font lock defaults for the current buffer."
6272 (let* ((em org-fontify-emphasized-text)
6273 (lk org-highlight-links)
6274 (org-font-lock-extra-keywords
6275 (list
6276 ;; Call the hook
6277 '(org-font-lock-hook)
6278 ;; Headlines
6279 `(,(if org-fontify-whole-heading-line
6280 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6281 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6282 (1 (org-get-level-face 1))
6283 (2 (org-get-level-face 2))
6284 (3 (org-get-level-face 3)))
6285 ;; Table lines
6286 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6287 (1 'org-table t))
6288 ;; Table internals
6289 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6290 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6291 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6292 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6293 ;; Drawers
6294 '(org-fontify-drawers)
6295 ;; Properties
6296 (list org-property-re
6297 '(1 'org-special-keyword t)
6298 '(3 'org-property-value t))
6299 ;; Link related fontification.
6300 '(org-activate-links)
6301 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6302 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6303 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6304 (when (memq 'footnote lk) '(org-activate-footnote-links))
6305 ;; Targets.
6306 (list org-any-target-regexp '(0 'org-target t))
6307 ;; Diary sexps.
6308 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6309 ;; Macro
6310 '(org-fontify-macros)
6311 ;; TODO keyword
6312 (list (format org-heading-keyword-regexp-format
6313 org-todo-regexp)
6314 '(2 (org-get-todo-face 2) t))
6315 ;; DONE
6316 (if org-fontify-done-headline
6317 (list (format org-heading-keyword-regexp-format
6318 (concat
6319 "\\(?:"
6320 (mapconcat 'regexp-quote org-done-keywords "\\|")
6321 "\\)"))
6322 '(2 'org-headline-done t))
6323 nil)
6324 ;; Priorities
6325 '(org-font-lock-add-priority-faces)
6326 ;; Tags
6327 '(org-font-lock-add-tag-faces)
6328 ;; Tags groups
6329 (when (and org-group-tags org-tag-groups-alist)
6330 (list (concat org-outline-regexp-bol ".+\\(:"
6331 (regexp-opt (mapcar 'car org-tag-groups-alist))
6332 ":\\).*$")
6333 '(1 'org-tag-group prepend)))
6334 ;; Special keywords
6335 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6336 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6337 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6338 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6339 ;; Emphasis
6340 (when em '(org-do-emphasis-faces))
6341 ;; Checkboxes
6342 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6343 1 'org-checkbox prepend)
6344 (when (cdr (assq 'checkbox org-list-automatic-rules))
6345 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6346 (0 (org-get-checkbox-statistics-face) t)))
6347 ;; Description list items
6348 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6349 1 'org-list-dt prepend)
6350 ;; ARCHIVEd headings
6351 (list (concat
6352 org-outline-regexp-bol
6353 "\\(.*:" org-archive-tag ":.*\\)")
6354 '(1 'org-archived prepend))
6355 ;; Specials
6356 '(org-do-latex-and-related)
6357 '(org-fontify-entities)
6358 '(org-raise-scripts)
6359 ;; Code
6360 '(org-activate-code (1 'org-code t))
6361 ;; COMMENT
6362 (list (format
6363 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6364 org-todo-regexp
6365 org-comment-string)
6366 '(9 'org-special-keyword t))
6367 ;; Blocks and meta lines
6368 '(org-fontify-meta-lines-and-blocks))))
6369 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6370 (run-hooks 'org-font-lock-set-keywords-hook)
6371 ;; Now set the full font-lock-keywords
6372 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6373 (setq-local font-lock-defaults
6374 '(org-font-lock-keywords t nil nil backward-paragraph))
6375 (kill-local-variable 'font-lock-keywords)
6376 nil))
6378 (defun org-toggle-pretty-entities ()
6379 "Toggle the composition display of entities as UTF8 characters."
6380 (interactive)
6381 (setq-local org-pretty-entities (not org-pretty-entities))
6382 (org-restart-font-lock)
6383 (if org-pretty-entities
6384 (message "Entities are now displayed as UTF8 characters")
6385 (save-restriction
6386 (widen)
6387 (decompose-region (point-min) (point-max))
6388 (message "Entities are now displayed as plain text"))))
6390 (defvar-local org-custom-properties-overlays nil
6391 "List of overlays used for custom properties.")
6393 (defun org-toggle-custom-properties-visibility ()
6394 "Display or hide properties in `org-custom-properties'."
6395 (interactive)
6396 (if org-custom-properties-overlays
6397 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6398 (setq org-custom-properties-overlays nil))
6399 (when org-custom-properties
6400 (org-with-wide-buffer
6401 (goto-char (point-min))
6402 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6403 (while (re-search-forward regexp nil t)
6404 (let ((end (cdr (save-match-data (org-get-property-block)))))
6405 (when (and end (< (point) end))
6406 ;; Hide first custom property in current drawer.
6407 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6408 (overlay-put o 'invisible t)
6409 (overlay-put o 'org-custom-property t)
6410 (push o org-custom-properties-overlays))
6411 ;; Hide additional custom properties in the same drawer.
6412 (while (re-search-forward regexp end t)
6413 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6414 (overlay-put o 'invisible t)
6415 (overlay-put o 'org-custom-property t)
6416 (push o org-custom-properties-overlays)))))
6417 ;; Each entry is limited to a single property drawer.
6418 (outline-next-heading)))))))
6420 (defun org-fontify-entities (limit)
6421 "Find an entity to fontify."
6422 (let (ee)
6423 (when org-pretty-entities
6424 (catch 'match
6425 ;; "\_ "-family is left out on purpose. Only the first one,
6426 ;; i.e., "\_ ", could be fontified anyway, and it would be
6427 ;; confusing when adding a second white space character.
6428 (while (re-search-forward
6429 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6430 limit t)
6431 (when (and (not (org-at-comment-p))
6432 (setq ee (org-entity-get (match-string 1)))
6433 (= (length (nth 6 ee)) 1))
6434 (let* ((end (if (equal (match-string 2) "{}")
6435 (match-end 2)
6436 (match-end 1))))
6437 (add-text-properties
6438 (match-beginning 0) end
6439 (list 'font-lock-fontified t))
6440 (compose-region (match-beginning 0) end
6441 (nth 6 ee) nil)
6442 (backward-char 1)
6443 (throw 'match t))))
6444 nil))))
6446 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6447 "Fontify string S like in Org mode."
6448 (with-temp-buffer
6449 (insert s)
6450 (let ((org-odd-levels-only odd-levels))
6451 (org-mode)
6452 (org-font-lock-ensure)
6453 (buffer-string))))
6455 (defvar org-m nil)
6456 (defvar org-l nil)
6457 (defvar org-f nil)
6458 (defun org-get-level-face (n)
6459 "Get the right face for match N in font-lock matching of headlines."
6460 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6461 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6462 (if org-cycle-level-faces
6463 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6464 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6465 (cond
6466 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6467 ((eq n 2) org-f)
6468 (t (unless org-level-color-stars-only org-f))))
6470 (defun org-face-from-face-or-color (context inherit face-or-color)
6471 "Create a face list that inherits INHERIT, but sets the foreground color.
6472 When FACE-OR-COLOR is not a string, just return it."
6473 (if (stringp face-or-color)
6474 (list :inherit inherit
6475 (cdr (assoc context org-faces-easy-properties))
6476 face-or-color)
6477 face-or-color))
6479 (defun org-get-todo-face (kwd)
6480 "Get the right face for a TODO keyword KWD.
6481 If KWD is a number, get the corresponding match group."
6482 (when (numberp kwd) (setq kwd (match-string kwd)))
6483 (or (org-face-from-face-or-color
6484 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6485 (and (member kwd org-done-keywords) 'org-done)
6486 'org-todo))
6488 (defun org-get-priority-face (priority)
6489 "Get the right face for PRIORITY.
6490 PRIORITY is a character."
6491 (or (org-face-from-face-or-color
6492 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6493 'org-priority))
6495 (defun org-get-tag-face (tag)
6496 "Get the right face for TAG.
6497 If TAG is a number, get the corresponding match group."
6498 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6499 (or (org-face-from-face-or-color
6500 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6501 'org-tag)))
6503 (defun org-font-lock-add-priority-faces (limit)
6504 "Add the special priority faces."
6505 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6506 (add-text-properties
6507 (match-beginning 1) (match-end 1)
6508 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6509 'font-lock-fontified t))))
6511 (defun org-font-lock-add-tag-faces (limit)
6512 "Add the special tag faces."
6513 (when (and org-tag-faces org-tags-special-faces-re)
6514 (while (re-search-forward org-tags-special-faces-re limit t)
6515 (add-text-properties (match-beginning 1) (match-end 1)
6516 (list 'face (org-get-tag-face 1)
6517 'font-lock-fontified t))
6518 (backward-char 1))))
6520 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6521 "Remove fontification and activation overlays from links."
6522 (font-lock-default-unfontify-region beg end)
6523 (let* ((buffer-undo-list t)
6524 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6525 (inhibit-modification-hooks t)
6526 deactivate-mark buffer-file-name buffer-file-truename)
6527 (decompose-region beg end)
6528 (remove-text-properties beg end
6529 '(mouse-face t keymap t org-linked-text t
6530 invisible t intangible t
6531 org-emphasis t))
6532 (org-remove-font-lock-display-properties beg end)))
6534 (defconst org-script-display '(((raise -0.3) (height 0.7))
6535 ((raise 0.3) (height 0.7))
6536 ((raise -0.5))
6537 ((raise 0.5)))
6538 "Display properties for showing superscripts and subscripts.")
6540 (defun org-remove-font-lock-display-properties (beg end)
6541 "Remove specific display properties that have been added by font lock.
6542 The will remove the raise properties that are used to show superscripts
6543 and subscripts."
6544 (let (next prop)
6545 (while (< beg end)
6546 (setq next (next-single-property-change beg 'display nil end)
6547 prop (get-text-property beg 'display))
6548 (when (member prop org-script-display)
6549 (put-text-property beg next 'display nil))
6550 (setq beg next))))
6552 (defun org-raise-scripts (limit)
6553 "Add raise properties to sub/superscripts."
6554 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6555 (re-search-forward
6556 (if (eq org-use-sub-superscripts t)
6557 org-match-substring-regexp
6558 org-match-substring-with-braces-regexp)
6559 limit t))
6560 (let* ((pos (point)) table-p comment-p
6561 (mpos (match-beginning 3))
6562 (emph-p (get-text-property mpos 'org-emphasis))
6563 (link-p (get-text-property mpos 'mouse-face))
6564 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6565 (goto-char (point-at-bol))
6566 (setq table-p (looking-at-p org-table-dataline-regexp)
6567 comment-p (looking-at-p "^[ \t]*#[ +]"))
6568 (goto-char pos)
6569 ;; Handle a_b^c
6570 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6571 (unless (or comment-p emph-p link-p keyw-p)
6572 (put-text-property (match-beginning 3) (match-end 0)
6573 'display
6574 (if (equal (char-after (match-beginning 2)) ?^)
6575 (nth (if table-p 3 1) org-script-display)
6576 (nth (if table-p 2 0) org-script-display)))
6577 (add-text-properties (match-beginning 2) (match-end 2)
6578 (list 'invisible t))
6579 (when (and (eq (char-after (match-beginning 3)) ?{)
6580 (eq (char-before (match-end 3)) ?}))
6581 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6582 (list 'invisible t))
6583 (add-text-properties (1- (match-end 3)) (match-end 3)
6584 (list 'invisible t))))
6585 t)))
6587 (defun org-remove-empty-overlays-at (pos)
6588 "Remove outline overlays that do not contain non-white stuff."
6589 (dolist (o (overlays-at pos))
6590 (and (eq 'outline (overlay-get o 'invisible))
6591 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6592 (overlay-end o))))
6593 (delete-overlay o))))
6595 (defun org-show-empty-lines-in-parent ()
6596 "Move to the parent and re-show empty lines before visible headlines."
6597 (save-excursion
6598 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6599 (org-cycle-show-empty-lines context))))
6601 (defun org-files-list ()
6602 "Return `org-agenda-files' list, plus all open Org files.
6603 This is useful for operations that need to scan all of a user's
6604 open and agenda-wise Org files."
6605 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6606 (dolist (buf (buffer-list))
6607 (with-current-buffer buf
6608 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6609 (cl-pushnew (expand-file-name (buffer-file-name)) files
6610 :test #'equal))))
6611 files))
6613 (defsubst org-entry-beginning-position ()
6614 "Return the beginning position of the current entry."
6615 (save-excursion (org-back-to-heading t) (point)))
6617 (defsubst org-entry-end-position ()
6618 "Return the end position of the current entry."
6619 (save-excursion (outline-next-heading) (point)))
6621 (defun org-subtree-end-visible-p ()
6622 "Is the end of the current subtree visible?"
6623 (pos-visible-in-window-p
6624 (save-excursion (org-end-of-subtree t) (point))))
6626 (defun org-first-headline-recenter ()
6627 "Move cursor to the first headline and recenter the headline."
6628 (let ((window (get-buffer-window)))
6629 (when window
6630 (goto-char (point-min))
6631 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6632 (set-window-start window (line-beginning-position))))))
6635 ;;; Visibility (headlines, blocks, drawers)
6637 ;;;; Headlines visibility
6639 (defun org-show-entry ()
6640 "Show the body directly following this heading.
6641 Show the heading too, if it is currently invisible."
6642 (interactive)
6643 (save-excursion
6644 (ignore-errors
6645 (org-back-to-heading t)
6646 (org-flag-region
6647 (line-end-position 0)
6648 (save-excursion
6649 (if (re-search-forward
6650 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6651 (match-beginning 1)
6652 (point-max)))
6654 'outline))))
6656 (defun org-show-children (&optional level)
6657 "Show all direct subheadings of this heading.
6658 Prefix arg LEVEL is how many levels below the current level
6659 should be shown. Default is enough to cause the following
6660 heading to appear."
6661 (interactive "p")
6662 (save-excursion
6663 (org-back-to-heading t)
6664 (let* ((current-level (funcall outline-level))
6665 (max-level (org-get-valid-level
6666 current-level
6667 (if level (prefix-numeric-value level) 1)))
6668 (end (save-excursion (org-end-of-subtree t t)))
6669 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6670 (past-first-child nil)
6671 ;; Make sure to skip inlinetasks.
6672 (re (format regexp-fmt
6673 current-level
6674 (cond
6675 ((not (featurep 'org-inlinetask)) "")
6676 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6678 (t (1- org-inlinetask-min-level))))))
6679 ;; Display parent heading.
6680 (org-flag-heading nil)
6681 (forward-line)
6682 ;; Display children. First child may be deeper than expected
6683 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6684 ;; MAX-LEVEL accordingly.
6685 (while (re-search-forward re end t)
6686 (unless past-first-child
6687 (setq re (format regexp-fmt
6688 current-level
6689 (max (funcall outline-level) max-level)))
6690 (setq past-first-child t))
6691 (org-flag-heading nil)))))
6693 (defun org-show-subtree ()
6694 "Show everything after this heading at deeper levels."
6695 (interactive)
6696 (org-flag-region
6697 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6699 ;;;; Blocks visibility
6701 (defun org-hide-block-toggle-maybe ()
6702 "Toggle visibility of block at point.
6703 Unlike to `org-hide-block-toggle', this function does not throw
6704 an error. Return a non-nil value when toggling is successful."
6705 (interactive)
6706 (ignore-errors (org-hide-block-toggle)))
6708 (defun org-hide-block-toggle (&optional force)
6709 "Toggle the visibility of the current block.
6710 When optional argument FORCE is `off', make block visible. If it
6711 is non-nil, hide it unconditionally. Throw an error when not at
6712 a block. Return a non-nil value when toggling is successful."
6713 (interactive)
6714 (let ((element (org-element-at-point)))
6715 (unless (memq (org-element-type element)
6716 '(center-block comment-block dynamic-block example-block
6717 export-block quote-block special-block
6718 src-block verse-block))
6719 (user-error "Not at a block"))
6720 (let* ((post (org-element-property :post-affiliated element))
6721 (start (save-excursion
6722 (goto-char post)
6723 (line-end-position)))
6724 (end (save-excursion
6725 (goto-char (org-element-property :end element))
6726 (skip-chars-backward " \t\n")
6727 (line-end-position))))
6728 ;; Do nothing when not before or at the block opening line or at
6729 ;; the block closing line.
6730 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6731 (cond ((eq force 'off)
6732 (org-flag-region start end nil 'org-hide-block))
6733 (force
6734 (org-flag-region start end t 'org-hide-block))
6735 ((eq (get-char-property start 'invisible) 'org-hide-block)
6736 (org-flag-region start end nil 'org-hide-block))
6738 (org-flag-region start end t 'org-hide-block)))
6739 ;; When the block is hidden away, make sure point is left in
6740 ;; a visible part of the buffer.
6741 (when (invisible-p (max (1- (point)) (point-min)))
6742 (goto-char post))
6743 ;; Signal success.
6744 t))))
6746 (defun org-hide-block-toggle-all ()
6747 "Toggle the visibility of all blocks in the current buffer."
6748 (org-block-map 'org-hide-block-toggle))
6750 (defun org-hide-block-all ()
6751 "Fold all blocks in the current buffer."
6752 (interactive)
6753 (org-show-all '(blocks))
6754 (org-block-map 'org-hide-block-toggle-maybe))
6756 ;;;; Drawers visibility
6758 (defun org-cycle-hide-drawers (state &optional exceptions)
6759 "Re-hide all drawers after a visibility state change.
6760 STATE should be one of the symbols listed in the docstring of
6761 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6762 a list of strings specifying which drawers should not be hidden."
6763 (when (and (derived-mode-p 'org-mode)
6764 (not (memq state '(overview folded contents))))
6765 (save-excursion
6766 (let* ((globalp (eq state 'all))
6767 (beg (if globalp (point-min) (point)))
6768 (end (if globalp (point-max)
6769 (if (eq state 'children)
6770 (save-excursion (outline-next-heading) (point))
6771 (org-end-of-subtree t)))))
6772 (goto-char beg)
6773 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6774 (unless (member-ignore-case (match-string 1) exceptions)
6775 (let ((drawer (org-element-at-point)))
6776 (when (memq (org-element-type drawer) '(drawer property-drawer))
6777 (org-flag-drawer t drawer)
6778 ;; Make sure to skip drawer entirely or we might flag
6779 ;; it another time when matching its ending line with
6780 ;; `org-drawer-regexp'.
6781 (goto-char (org-element-property :end drawer))))))))))
6783 (defun org-flag-drawer (flag &optional element)
6784 "When FLAG is non-nil, hide the drawer we are at.
6785 Otherwise make it visible. When optional argument ELEMENT is
6786 a parsed drawer, as returned by `org-element-at-point', hide or
6787 show that drawer instead."
6788 (let ((drawer (or element
6789 (and (save-excursion
6790 (beginning-of-line)
6791 (looking-at-p org-drawer-regexp))
6792 (org-element-at-point)))))
6793 (when (memq (org-element-type drawer) '(drawer property-drawer))
6794 (let ((post (org-element-property :post-affiliated drawer)))
6795 (org-flag-region
6796 (save-excursion (goto-char post) (line-end-position))
6797 (save-excursion (goto-char (org-element-property :end drawer))
6798 (skip-chars-backward " \t\n")
6799 (line-end-position))
6800 flag 'org-hide-drawer)
6801 ;; When the drawer is hidden away, make sure point lies in
6802 ;; a visible part of the buffer.
6803 (when (invisible-p (max (1- (point)) (point-min)))
6804 (goto-char post))))))
6806 ;;;; Visibility cycling
6808 (defvar-local org-cycle-global-status nil)
6809 (put 'org-cycle-global-status 'org-state t)
6810 (defvar-local org-cycle-subtree-status nil)
6811 (put 'org-cycle-subtree-status 'org-state t)
6813 (defun org-show-all (&optional types)
6814 "Show all contents in the visible part of the buffer.
6815 By default, the function expands headings, blocks and drawers.
6816 When optional argument TYPE is a list of symbols among `blocks',
6817 `drawers' and `headings', to only expand one specific type."
6818 (dolist (type (or types '(blocks drawers headings)))
6819 (org-flag-region (point-min) (point-max) nil
6820 (pcase type
6821 (`blocks 'org-hide-block)
6822 (`drawers 'org-hide-drawer)
6823 (`headings 'outline)
6824 (_ (error "Invalid type: %S" type))))))
6826 ;;;###autoload
6827 (defun org-cycle (&optional arg)
6828 "TAB-action and visibility cycling for Org mode.
6830 This is the command invoked in Org mode by the `TAB' key. Its main
6831 purpose is outline visibility cycling, but it also invokes other actions
6832 in special contexts.
6834 When this function is called with a `\\[universal-argument]' prefix, rotate \
6835 the entire
6836 buffer through 3 states (global cycling)
6837 1. OVERVIEW: Show only top-level headlines.
6838 2. CONTENTS: Show all headlines of all levels, but no body text.
6839 3. SHOW ALL: Show everything.
6841 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6842 switch to the startup visibility,
6843 determined by the variable `org-startup-folded', and by any VISIBILITY
6844 properties in the buffer.
6846 With a `\\[universal-argument] \\[universal-argument] \
6847 \\[universal-argument]' prefix argument, show the entire buffer, including
6848 any drawers.
6850 When inside a table, re-align the table and move to the next field.
6852 When point is at the beginning of a headline, rotate the subtree started
6853 by this line through 3 different states (local cycling)
6854 1. FOLDED: Only the main headline is shown.
6855 2. CHILDREN: The main headline and the direct children are shown.
6856 From this state, you can move to one of the children
6857 and zoom in further.
6858 3. SUBTREE: Show the entire subtree, including body text.
6859 If there is no subtree, switch directly from CHILDREN to FOLDED.
6861 When point is at the beginning of an empty headline and the variable
6862 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6863 of the headline by demoting and promoting it to likely levels. This
6864 speeds up creation document structure by pressing `TAB' once or several
6865 times right after creating a new headline.
6867 When there is a numeric prefix, go up to a heading with level ARG, do
6868 a `show-subtree' and return to the previous cursor position. If ARG
6869 is negative, go up that many levels.
6871 When point is not at the beginning of a headline, execute the global
6872 binding for `TAB', which is re-indenting the line. See the option
6873 `org-cycle-emulate-tab' for details.
6875 As a special case, if point is at the beginning of the buffer and there is
6876 no headline in line 1, this function will act as if called with prefix arg
6877 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6878 prefix arg, but only
6879 if the variable `org-cycle-global-at-bob' is t."
6880 (interactive "P")
6881 (org-load-modules-maybe)
6882 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6883 (and org-cycle-level-after-item/entry-creation
6884 (or (org-cycle-level)
6885 (org-cycle-item-indentation))))
6886 (let* ((limit-level
6887 (or org-cycle-max-level
6888 (and (boundp 'org-inlinetask-min-level)
6889 org-inlinetask-min-level
6890 (1- org-inlinetask-min-level))))
6891 (nstars (and limit-level
6892 (if org-odd-levels-only
6893 (and limit-level (1- (* limit-level 2)))
6894 limit-level)))
6895 (org-outline-regexp
6896 (if (not (derived-mode-p 'org-mode))
6897 outline-regexp
6898 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6899 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6900 (not (looking-at org-outline-regexp))))
6901 (org-cycle-hook
6902 (if bob-special
6903 (delq 'org-optimize-window-after-visibility-change
6904 (copy-sequence org-cycle-hook))
6905 org-cycle-hook))
6906 (pos (point)))
6908 (cond
6910 ((equal arg '(16))
6911 (setq last-command 'dummy)
6912 (org-set-startup-visibility)
6913 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6915 ((equal arg '(64))
6916 (org-show-all)
6917 (org-unlogged-message "Entire buffer visible, including drawers"))
6919 ((equal arg '(4)) (org-cycle-internal-global))
6921 ;; Try hiding block at point.
6922 ((org-hide-block-toggle-maybe))
6924 ;; Try cdlatex TAB completion
6925 ((org-try-cdlatex-tab))
6927 ;; Table: enter it or move to the next field.
6928 ((org-at-table-p 'any)
6929 (if (org-at-table.el-p)
6930 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6931 Use `\\[org-edit-special]' to edit table.el tables"))
6932 (if arg (org-table-edit-field t)
6933 (org-table-justify-field-maybe)
6934 (call-interactively 'org-table-next-field))))
6936 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6938 ;; Global cycling: delegate to `org-cycle-internal-global'.
6939 (bob-special (org-cycle-internal-global))
6941 ;; Drawers: delegate to `org-flag-drawer'.
6942 ((save-excursion
6943 (beginning-of-line 1)
6944 (looking-at org-drawer-regexp))
6945 (org-flag-drawer ; toggle block visibility
6946 (not (get-char-property (match-end 0) 'invisible))))
6948 ;; Show-subtree, ARG levels up from here.
6949 ((integerp arg)
6950 (save-excursion
6951 (org-back-to-heading)
6952 (outline-up-heading (if (< arg 0) (- arg)
6953 (- (funcall outline-level) arg)))
6954 (org-show-subtree)))
6956 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6957 ((and (featurep 'org-inlinetask)
6958 (org-inlinetask-at-task-p)
6959 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6960 (org-inlinetask-toggle-visibility))
6962 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6963 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6964 (save-excursion (move-beginning-of-line 1)
6965 (looking-at org-outline-regexp)))
6966 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6967 (org-cycle-internal-local))
6969 ;; From there: TAB emulation and template completion.
6970 (buffer-read-only (org-back-to-heading))
6972 ((run-hook-with-args-until-success
6973 'org-tab-after-check-for-cycling-hook))
6975 ((run-hook-with-args-until-success
6976 'org-tab-before-tab-emulation-hook))
6978 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6979 (or (not (bolp))
6980 (not (looking-at org-outline-regexp))))
6981 (call-interactively (global-key-binding "\t")))
6983 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6984 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6985 (or (and (eq org-cycle-emulate-tab 'white)
6986 (= (match-end 0) (point-at-eol)))
6987 (and (eq org-cycle-emulate-tab 'whitestart)
6988 (>= (match-end 0) pos))))
6990 (eq org-cycle-emulate-tab t))
6991 (call-interactively (global-key-binding "\t")))
6993 (t (save-excursion
6994 (org-back-to-heading)
6995 (org-cycle)))))))
6997 (defun org-cycle-internal-global ()
6998 "Do the global cycling action."
6999 ;; Hack to avoid display of messages for .org attachments in Gnus
7000 (let ((ga (string-match "\\*fontification" (buffer-name))))
7001 (cond
7002 ((and (eq last-command this-command)
7003 (eq org-cycle-global-status 'overview))
7004 ;; We just created the overview - now do table of contents
7005 ;; This can be slow in very large buffers, so indicate action
7006 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7007 (unless ga (org-unlogged-message "CONTENTS..."))
7008 (org-content)
7009 (unless ga (org-unlogged-message "CONTENTS...done"))
7010 (setq org-cycle-global-status 'contents)
7011 (run-hook-with-args 'org-cycle-hook 'contents))
7013 ((and (eq last-command this-command)
7014 (eq org-cycle-global-status 'contents))
7015 ;; We just showed the table of contents - now show everything
7016 (run-hook-with-args 'org-pre-cycle-hook 'all)
7017 (org-show-all '(headings blocks))
7018 (unless ga (org-unlogged-message "SHOW ALL"))
7019 (setq org-cycle-global-status 'all)
7020 (run-hook-with-args 'org-cycle-hook 'all))
7023 ;; Default action: go to overview
7024 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7025 (org-overview)
7026 (unless ga (org-unlogged-message "OVERVIEW"))
7027 (setq org-cycle-global-status 'overview)
7028 (run-hook-with-args 'org-cycle-hook 'overview)))))
7030 (defvar org-called-with-limited-levels nil
7031 "Non-nil when `org-with-limited-levels' is currently active.")
7033 (defun org-cycle-internal-local ()
7034 "Do the local cycling action."
7035 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7036 ;; First, determine end of headline (EOH), end of subtree or item
7037 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7038 (save-excursion
7039 (if (org-at-item-p)
7040 (progn
7041 (beginning-of-line)
7042 (setq struct (org-list-struct))
7043 (setq eoh (point-at-eol))
7044 (setq eos (org-list-get-item-end-before-blank (point) struct))
7045 (setq has-children (org-list-has-child-p (point) struct)))
7046 (org-back-to-heading)
7047 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7048 (setq eos (save-excursion (org-end-of-subtree t t)
7049 (when (bolp) (backward-char)) (point)))
7050 (setq has-children
7051 (or (save-excursion
7052 (let ((level (funcall outline-level)))
7053 (outline-next-heading)
7054 (and (org-at-heading-p t)
7055 (> (funcall outline-level) level))))
7056 (save-excursion
7057 (org-list-search-forward (org-item-beginning-re) eos t)))))
7058 ;; Determine end invisible part of buffer (EOL)
7059 (beginning-of-line 2)
7060 (while (and (not (eobp)) ;This is like `next-line'.
7061 (get-char-property (1- (point)) 'invisible))
7062 (goto-char (next-single-char-property-change (point) 'invisible))
7063 (and (eolp) (beginning-of-line 2)))
7064 (setq eol (point)))
7065 ;; Find out what to do next and set `this-command'
7066 (cond
7067 ((= eos eoh)
7068 ;; Nothing is hidden behind this heading
7069 (unless (org-before-first-heading-p)
7070 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7071 (org-unlogged-message "EMPTY ENTRY")
7072 (setq org-cycle-subtree-status nil)
7073 (save-excursion
7074 (goto-char eos)
7075 (outline-next-heading)
7076 (when (org-invisible-p) (org-flag-heading nil))))
7077 ((and (or (>= eol eos)
7078 (not (string-match "\\S-" (buffer-substring eol eos))))
7079 (or has-children
7080 (not (setq children-skipped
7081 org-cycle-skip-children-state-if-no-children))))
7082 ;; Entire subtree is hidden in one line: children view
7083 (unless (org-before-first-heading-p)
7084 (run-hook-with-args 'org-pre-cycle-hook 'children))
7085 (if (org-at-item-p)
7086 (org-list-set-item-visibility (point-at-bol) struct 'children)
7087 (org-show-entry)
7088 (org-with-limited-levels (org-show-children))
7089 (org-show-set-visibility 'canonical)
7090 ;; Fold every list in subtree to top-level items.
7091 (when (eq org-cycle-include-plain-lists 'integrate)
7092 (save-excursion
7093 (org-back-to-heading)
7094 (while (org-list-search-forward (org-item-beginning-re) eos t)
7095 (beginning-of-line 1)
7096 (let* ((struct (org-list-struct))
7097 (prevs (org-list-prevs-alist struct))
7098 (end (org-list-get-bottom-point struct)))
7099 (dolist (e (org-list-get-all-items (point) struct prevs))
7100 (org-list-set-item-visibility e struct 'folded))
7101 (goto-char (if (< end eos) end eos)))))))
7102 (org-unlogged-message "CHILDREN")
7103 (save-excursion
7104 (goto-char eos)
7105 (outline-next-heading)
7106 (when (org-invisible-p) (org-flag-heading nil)))
7107 (setq org-cycle-subtree-status 'children)
7108 (unless (org-before-first-heading-p)
7109 (run-hook-with-args 'org-cycle-hook 'children)))
7110 ((or children-skipped
7111 (and (eq last-command this-command)
7112 (eq org-cycle-subtree-status 'children)))
7113 ;; We just showed the children, or no children are there,
7114 ;; now show everything.
7115 (unless (org-before-first-heading-p)
7116 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7117 (org-flag-region eoh eos nil 'outline)
7118 (org-unlogged-message
7119 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7120 (setq org-cycle-subtree-status 'subtree)
7121 (unless (org-before-first-heading-p)
7122 (run-hook-with-args 'org-cycle-hook 'subtree)))
7124 ;; Default action: hide the subtree.
7125 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7126 (org-flag-region eoh eos t 'outline)
7127 (org-unlogged-message "FOLDED")
7128 (setq org-cycle-subtree-status 'folded)
7129 (unless (org-before-first-heading-p)
7130 (run-hook-with-args 'org-cycle-hook 'folded))))))
7132 ;;;###autoload
7133 (defun org-global-cycle (&optional arg)
7134 "Cycle the global visibility. For details see `org-cycle'.
7135 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7136 With a numeric prefix, show all headlines up to that level."
7137 (interactive "P")
7138 (let ((org-cycle-include-plain-lists
7139 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7140 (cond
7141 ((integerp arg)
7142 (org-show-all '(headings blocks))
7143 (outline-hide-sublevels arg)
7144 (setq org-cycle-global-status 'contents))
7145 ((equal arg '(4))
7146 (org-set-startup-visibility)
7147 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7149 (org-cycle '(4))))))
7151 (defun org-set-startup-visibility ()
7152 "Set the visibility required by startup options and properties."
7153 (cond
7154 ((eq org-startup-folded t)
7155 (org-overview))
7156 ((eq org-startup-folded 'content)
7157 (org-content))
7158 ((or (eq org-startup-folded 'showeverything)
7159 (eq org-startup-folded nil))
7160 (org-show-all)))
7161 (unless (eq org-startup-folded 'showeverything)
7162 (when org-hide-block-startup (org-hide-block-all))
7163 (org-set-visibility-according-to-property)
7164 (org-cycle-hide-archived-subtrees 'all)
7165 (org-cycle-hide-drawers 'all)
7166 (org-cycle-show-empty-lines t)))
7168 (defun org-set-visibility-according-to-property ()
7169 "Switch subtree visibilities according to :VISIBILITY: property."
7170 (interactive)
7171 (org-with-wide-buffer
7172 (goto-char (point-min))
7173 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7174 (if (not (org-at-property-p)) (outline-next-heading)
7175 (let ((state (match-string 3)))
7176 (save-excursion
7177 (org-back-to-heading t)
7178 (outline-hide-subtree)
7179 (org-reveal)
7180 (cond
7181 ((equal state "folded")
7182 (outline-hide-subtree))
7183 ((equal state "children")
7184 (org-show-hidden-entry)
7185 (org-show-children))
7186 ((equal state "content")
7187 (save-excursion
7188 (save-restriction
7189 (org-narrow-to-subtree)
7190 (org-content))))
7191 ((member state '("all" "showall"))
7192 (outline-show-subtree)))))))))
7194 (defun org-overview ()
7195 "Switch to overview mode, showing only top-level headlines.
7196 This shows all headlines with a level equal or greater than the level
7197 of the first headline in the buffer. This is important, because if the
7198 first headline is not level one, then (hide-sublevels 1) gives confusing
7199 results."
7200 (interactive)
7201 (save-excursion
7202 (let ((level
7203 (save-excursion
7204 (goto-char (point-min))
7205 (when (re-search-forward org-outline-regexp-bol nil t)
7206 (goto-char (match-beginning 0))
7207 (funcall outline-level)))))
7208 (and level (outline-hide-sublevels level)))))
7210 (defun org-content (&optional arg)
7211 "Show all headlines in the buffer, like a table of contents.
7212 With numerical argument N, show content up to level N."
7213 (interactive "P")
7214 (org-overview)
7215 (save-excursion
7216 ;; Visit all headings and show their offspring
7217 (and (integerp arg) (org-overview))
7218 (goto-char (point-max))
7219 (catch 'exit
7220 (while (and (progn (condition-case nil
7221 (outline-previous-visible-heading 1)
7222 (error (goto-char (point-min))))
7224 (looking-at org-outline-regexp))
7225 (if (integerp arg)
7226 (org-show-children (1- arg))
7227 (outline-show-branches))
7228 (when (bobp) (throw 'exit nil))))))
7230 (defun org-optimize-window-after-visibility-change (state)
7231 "Adjust the window after a change in outline visibility.
7232 This function is the default value of the hook `org-cycle-hook'."
7233 (when (get-buffer-window (current-buffer))
7234 (cond
7235 ((eq state 'content) nil)
7236 ((eq state 'all) nil)
7237 ((eq state 'folded) nil)
7238 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7239 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7241 (defun org-clean-visibility-after-subtree-move ()
7242 "Fix visibility issues after moving a subtree."
7243 ;; First, find a reasonable region to look at:
7244 ;; Start two siblings above, end three below
7245 (let* ((beg (save-excursion
7246 (and (org-get-last-sibling)
7247 (org-get-last-sibling))
7248 (point)))
7249 (end (save-excursion
7250 (and (org-get-next-sibling)
7251 (org-get-next-sibling)
7252 (org-get-next-sibling))
7253 (if (org-at-heading-p)
7254 (point-at-eol)
7255 (point))))
7256 (level (looking-at "\\*+"))
7257 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7258 (save-excursion
7259 (save-restriction
7260 (narrow-to-region beg end)
7261 (when re
7262 ;; Properly fold already folded siblings
7263 (goto-char (point-min))
7264 (while (re-search-forward re nil t)
7265 (when (and (not (org-invisible-p))
7266 (org-invisible-p (line-end-position)))
7267 (outline-hide-entry))))
7268 (org-cycle-hide-drawers 'all)
7269 (org-cycle-show-empty-lines 'overview)))))
7271 (defun org-cycle-show-empty-lines (state)
7272 "Show empty lines above all visible headlines.
7273 The region to be covered depends on STATE when called through
7274 `org-cycle-hook'. Lisp program can use t for STATE to get the
7275 entire buffer covered. Note that an empty line is only shown if there
7276 are at least `org-cycle-separator-lines' empty lines before the headline."
7277 (when (/= org-cycle-separator-lines 0)
7278 (save-excursion
7279 (let* ((n (abs org-cycle-separator-lines))
7280 (re (cond
7281 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7282 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7283 (t (let ((ns (number-to-string (- n 2))))
7284 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7285 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7286 beg end)
7287 (cond
7288 ((memq state '(overview contents t))
7289 (setq beg (point-min) end (point-max)))
7290 ((memq state '(children folded))
7291 (setq beg (point)
7292 end (progn (org-end-of-subtree t t)
7293 (line-beginning-position 2)))))
7294 (when beg
7295 (goto-char beg)
7296 (while (re-search-forward re end t)
7297 (unless (get-char-property (match-end 1) 'invisible)
7298 (let ((e (match-end 1))
7299 (b (if (>= org-cycle-separator-lines 0)
7300 (match-beginning 1)
7301 (save-excursion
7302 (goto-char (match-beginning 0))
7303 (skip-chars-backward " \t\n")
7304 (line-end-position)))))
7305 (org-flag-region b e nil 'outline))))))))
7306 ;; Never hide empty lines at the end of the file.
7307 (save-excursion
7308 (goto-char (point-max))
7309 (outline-previous-heading)
7310 (outline-end-of-heading)
7311 (when (and (looking-at "[ \t\n]+")
7312 (= (match-end 0) (point-max)))
7313 (org-flag-region (point) (match-end 0) nil 'outline))))
7315 ;;;; Reveal point location
7317 (defun org-show-context (&optional key)
7318 "Make sure point and context are visible.
7319 Optional argument KEY, when non-nil, is a symbol. See
7320 `org-show-context-detail' for allowed values and how much is to
7321 be shown."
7322 (org-show-set-visibility
7323 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7324 ((cdr (assq key org-show-context-detail)))
7325 (t (cdr (assq 'default org-show-context-detail))))))
7327 (defun org-show-set-visibility (detail)
7328 "Set visibility around point according to DETAIL.
7329 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7330 `tree', `canonical' or t. See `org-show-context-detail' for more
7331 information."
7332 ;; Show current heading and possibly its entry, following headline
7333 ;; or all children.
7334 (if (and (org-at-heading-p) (not (eq detail 'local)))
7335 (org-flag-heading nil)
7336 (org-show-entry)
7337 ;; If point is hidden within a drawer or a block, make sure to
7338 ;; expose it.
7339 (dolist (o (overlays-at (point)))
7340 (when (memq (overlay-get o 'invisible)
7341 '(org-hide-block org-hide-drawer outline))
7342 (delete-overlay o)))
7343 (unless (org-before-first-heading-p)
7344 (org-with-limited-levels
7345 (cl-case detail
7346 ((tree canonical t) (org-show-children))
7347 ((nil minimal ancestors))
7348 (t (save-excursion
7349 (outline-next-heading)
7350 (org-flag-heading nil)))))))
7351 ;; Show all siblings.
7352 (when (eq detail 'lineage) (org-show-siblings))
7353 ;; Show ancestors, possibly with their children.
7354 (when (memq detail '(ancestors lineage tree canonical t))
7355 (save-excursion
7356 (while (org-up-heading-safe)
7357 (org-flag-heading nil)
7358 (when (memq detail '(canonical t)) (org-show-entry))
7359 (when (memq detail '(tree canonical t)) (org-show-children))))))
7361 (defvar org-reveal-start-hook nil
7362 "Hook run before revealing a location.")
7364 (defun org-reveal (&optional siblings)
7365 "Show current entry, hierarchy above it, and the following headline.
7367 This can be used to show a consistent set of context around
7368 locations exposed with `org-show-context'.
7370 With optional argument SIBLINGS, on each level of the hierarchy all
7371 siblings are shown. This repairs the tree structure to what it would
7372 look like when opened with hierarchical calls to `org-cycle'.
7374 With a \\[universal-argument] \\[universal-argument] prefix, \
7375 go to the parent and show the entire tree."
7376 (interactive "P")
7377 (run-hooks 'org-reveal-start-hook)
7378 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7379 ((equal siblings '(16))
7380 (save-excursion
7381 (when (org-up-heading-safe)
7382 (org-show-subtree)
7383 (run-hook-with-args 'org-cycle-hook 'subtree))))
7384 (t (org-show-set-visibility 'lineage))))
7387 ;;; Indirect buffer display of subtrees
7389 (defvar org-indirect-dedicated-frame nil
7390 "This is the frame being used for indirect tree display.")
7391 (defvar org-last-indirect-buffer nil)
7393 (defun org-tree-to-indirect-buffer (&optional arg)
7394 "Create indirect buffer and narrow it to current subtree.
7396 With a numerical prefix ARG, go up to this level and then take that tree.
7397 If ARG is negative, go up that many levels.
7399 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7400 indirect buffer previously made with this command, to avoid proliferation of
7401 indirect buffers. However, when you call the command with a \
7402 `\\[universal-argument]' prefix, or
7403 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7404 so that you can work with several indirect buffers at the same time. If
7405 `org-indirect-buffer-display' is `dedicated-frame', the \
7406 `\\[universal-argument]' prefix also
7407 requests that a new frame be made for the new buffer, so that the dedicated
7408 frame is not changed."
7409 (interactive "P")
7410 (let ((cbuf (current-buffer))
7411 (cwin (selected-window))
7412 (pos (point))
7413 beg end level heading ibuf)
7414 (save-excursion
7415 (org-back-to-heading t)
7416 (when (numberp arg)
7417 (setq level (org-outline-level))
7418 (when (< arg 0) (setq arg (+ level arg)))
7419 (while (> (setq level (org-outline-level)) arg)
7420 (org-up-heading-safe)))
7421 (setq beg (point)
7422 heading (org-get-heading 'no-tags))
7423 (org-end-of-subtree t t)
7424 (when (org-at-heading-p) (backward-char 1))
7425 (setq end (point)))
7426 (when (and (buffer-live-p org-last-indirect-buffer)
7427 (not (eq org-indirect-buffer-display 'new-frame))
7428 (not arg))
7429 (kill-buffer org-last-indirect-buffer))
7430 (setq ibuf (org-get-indirect-buffer cbuf heading)
7431 org-last-indirect-buffer ibuf)
7432 (cond
7433 ((or (eq org-indirect-buffer-display 'new-frame)
7434 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7435 (select-frame (make-frame))
7436 (delete-other-windows)
7437 (pop-to-buffer-same-window ibuf)
7438 (org-set-frame-title heading))
7439 ((eq org-indirect-buffer-display 'dedicated-frame)
7440 (raise-frame
7441 (select-frame (or (and org-indirect-dedicated-frame
7442 (frame-live-p org-indirect-dedicated-frame)
7443 org-indirect-dedicated-frame)
7444 (setq org-indirect-dedicated-frame (make-frame)))))
7445 (delete-other-windows)
7446 (pop-to-buffer-same-window ibuf)
7447 (org-set-frame-title (concat "Indirect: " heading)))
7448 ((eq org-indirect-buffer-display 'current-window)
7449 (pop-to-buffer-same-window ibuf))
7450 ((eq org-indirect-buffer-display 'other-window)
7451 (pop-to-buffer ibuf))
7452 (t (error "Invalid value")))
7453 (narrow-to-region beg end)
7454 (org-show-all '(headings blocks))
7455 (goto-char pos)
7456 (run-hook-with-args 'org-cycle-hook 'all)
7457 (and (window-live-p cwin) (select-window cwin))))
7459 (defun org-get-indirect-buffer (&optional buffer heading)
7460 (setq buffer (or buffer (current-buffer)))
7461 (let ((n 1) (base (buffer-name buffer)) bname)
7462 (while (buffer-live-p
7463 (get-buffer
7464 (setq bname
7465 (concat base "-"
7466 (if heading (concat heading "-" (number-to-string n))
7467 (number-to-string n))))))
7468 (setq n (1+ n)))
7469 (condition-case nil
7470 (make-indirect-buffer buffer bname 'clone)
7471 (error (make-indirect-buffer buffer bname)))))
7473 (defun org-set-frame-title (title)
7474 "Set the title of the current frame to the string TITLE."
7475 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7477 ;;;; Structure editing
7479 ;;; Inserting headlines
7481 (defun org--line-empty-p (n)
7482 "Is the Nth next line empty?
7484 Counts the current line as N = 1 and the previous line as N = 0;
7485 see `beginning-of-line'."
7486 (save-excursion
7487 (and (not (bobp))
7488 (or (beginning-of-line n) t)
7489 (save-match-data
7490 (looking-at "[ \t]*$")))))
7492 (defun org-previous-line-empty-p ()
7493 "Is the previous line a blank line?
7494 When NEXT is non-nil, check the next line instead."
7495 (org--line-empty-p 0))
7497 (defun org-next-line-empty-p ()
7498 "Is the previous line a blank line?
7499 When NEXT is non-nil, check the next line instead."
7500 (org--line-empty-p 2))
7502 (defun org--blank-before-heading-p (&optional parent)
7503 "Non-nil when an empty line should precede a new heading here.
7504 When optional argument PARENT is non-nil, consider parent
7505 headline instead of current one."
7506 (pcase (assq 'heading org-blank-before-new-entry)
7507 (`(heading . auto)
7508 (save-excursion
7509 (org-with-limited-levels
7510 (unless (and (org-before-first-heading-p)
7511 (not (outline-next-heading)))
7512 (org-back-to-heading t)
7513 (when parent (org-up-heading-safe))
7514 (cond ((not (bobp))
7515 (org-previous-line-empty-p))
7516 ((outline-next-heading)
7517 (org-previous-line-empty-p))
7518 ;; Ignore trailing spaces on last buffer line.
7519 ((progn (skip-chars-backward " \t") (bolp))
7520 (org-previous-line-empty-p))
7521 (t nil))))))
7522 (`(heading . ,value) value)
7523 (_ nil)))
7525 (defun org-insert-heading (&optional arg invisible-ok top)
7526 "Insert a new heading or an item with the same depth at point.
7528 If point is at the beginning of a heading, insert a new heading
7529 or a new headline above the current one. When at the beginning
7530 of a regular line of text, turn it into a heading.
7532 If point is in the middle of a line, split it and create a new
7533 headline with the text in the current line after point (see
7534 `org-M-RET-may-split-line' on how to modify this behavior). As
7535 a special case, on a headline, splitting can only happen on the
7536 title itself. E.g., this excludes breaking stars or tags.
7538 With a `\\[universal-argument]' prefix, set \
7539 `org-insert-heading-respect-content' to
7540 a non-nil value for the duration of the command. This forces the
7541 insertion of a heading after the current subtree, independently
7542 on the location of point.
7544 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7545 insert the heading at the end of the tree
7546 above the current heading. For example, if point is within a
7547 2nd-level heading, then it will insert a 2nd-level heading at
7548 the end of the 1st-level parent subtree.
7550 When INVISIBLE-OK is set, stop at invisible headlines when going
7551 back. This is important for non-interactive uses of the
7552 command.
7554 When optional argument TOP is non-nil, insert a level 1 heading,
7555 unconditionally."
7556 (interactive "P")
7557 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7558 (level (org-current-level))
7559 (stars (make-string (if (and level (not top)) level 1) ?*)))
7560 (cond
7561 ((or org-insert-heading-respect-content
7562 (member arg '((4) (16)))
7563 (and (not invisible-ok)
7564 (invisible-p (max (1- (point)) (point-min)))))
7565 ;; Position point at the location of insertion.
7566 (if (not level) ;before first headline
7567 (org-with-limited-levels (outline-next-heading))
7568 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7569 ;; is nil.
7570 (org-with-limited-levels (org-back-to-heading invisible-ok))
7571 (cond ((equal arg '(16))
7572 (org-up-heading-safe)
7573 (org-end-of-subtree t t))
7575 (org-end-of-subtree t t))))
7576 (unless (bolp) (insert "\n")) ;ensure final newline
7577 (unless (and blank? (org-previous-line-empty-p))
7578 (org-N-empty-lines-before-current (if blank? 1 0)))
7579 (insert stars " \n")
7580 (forward-char -1))
7581 ;; At a headline...
7582 ((org-at-heading-p)
7583 (cond ((bolp)
7584 (when blank? (save-excursion (insert "\n")))
7585 (save-excursion (insert stars " \n"))
7586 (unless (and blank? (org-previous-line-empty-p))
7587 (org-N-empty-lines-before-current (if blank? 1 0)))
7588 (end-of-line))
7589 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7590 (org-match-line org-complex-heading-regexp)
7591 (org-pos-in-match-range (point) 4))
7592 ;; Grab the text that should moved to the new headline.
7593 ;; Preserve tags.
7594 (let ((split (delete-and-extract-region (point) (match-end 4))))
7595 (if (looking-at "[ \t]*$") (replace-match "")
7596 (org-set-tags nil t))
7597 (end-of-line)
7598 (when blank? (insert "\n"))
7599 (insert "\n" stars " ")
7600 (when (org-string-nw-p split) (insert split))
7601 (when (eobp) (save-excursion (insert "\n")))))
7603 (end-of-line)
7604 (when blank? (insert "\n"))
7605 (insert "\n" stars " ")
7606 (when (eobp) (save-excursion (insert "\n"))))))
7607 ;; On regular text, turn line into a headline or split, if
7608 ;; appropriate.
7609 ((bolp)
7610 (insert stars " ")
7611 (unless (and blank? (org-previous-line-empty-p))
7612 (org-N-empty-lines-before-current (if blank? 1 0))))
7614 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7615 (end-of-line))
7616 (insert "\n" stars " ")
7617 (unless (and blank? (org-previous-line-empty-p))
7618 (org-N-empty-lines-before-current (if blank? 1 0))))))
7619 (run-hooks 'org-insert-heading-hook))
7621 (defun org-N-empty-lines-before-current (n)
7622 "Make the number of empty lines before current exactly N.
7623 So this will delete or add empty lines."
7624 (let ((column (current-column)))
7625 (beginning-of-line)
7626 (unless (bobp)
7627 (let ((start (save-excursion
7628 (skip-chars-backward " \r\t\n")
7629 (line-end-position))))
7630 (delete-region start (line-end-position 0))))
7631 (insert (make-string n ?\n))
7632 (move-to-column column)))
7634 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7635 "Return the heading of the current entry, without the stars.
7636 When NO-TAGS is non-nil, don't include tags.
7637 When NO-TODO is non-nil, don't include TODO keywords.
7638 When NO-PRIORITY is non-nil, don't include priority cookie.
7639 When NO-COMMENT is non-nil, don't include COMMENT string."
7640 (save-excursion
7641 (org-back-to-heading t)
7642 (let ((case-fold-search nil))
7643 (looking-at org-complex-heading-regexp)
7644 (let ((todo (and (not no-todo) (match-string 2)))
7645 (priority (and (not no-priority) (match-string 3)))
7646 (headline (pcase (match-string 4)
7647 (`nil "")
7648 ((and (guard no-comment) h)
7649 (replace-regexp-in-string
7650 (eval-when-compile
7651 (format "\\`%s[ \t]+" org-comment-string))
7652 "" h))
7653 (h h)))
7654 (tags (and (not no-tags) (match-string 5))))
7655 (mapconcat #'identity
7656 (delq nil (list todo priority headline tags))
7657 " ")))))
7659 (defun org-heading-components ()
7660 "Return the components of the current heading.
7661 This is a list with the following elements:
7662 - the level as an integer
7663 - the reduced level, different if `org-odd-levels-only' is set.
7664 - the TODO keyword, or nil
7665 - the priority character, like ?A, or nil if no priority is given
7666 - the headline text itself, or the tags string if no headline text
7667 - the tags string, or nil."
7668 (save-excursion
7669 (org-back-to-heading t)
7670 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7671 (list (length (match-string 1))
7672 (org-reduced-level (length (match-string 1)))
7673 (match-string-no-properties 2)
7674 (and (match-end 3) (aref (match-string 3) 2))
7675 (match-string-no-properties 4)
7676 (match-string-no-properties 5)))))
7678 (defun org-get-entry ()
7679 "Get the entry text, after heading, entire subtree."
7680 (save-excursion
7681 (org-back-to-heading t)
7682 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7684 (defun org-edit-headline (&optional heading)
7685 "Edit the current headline.
7686 Set it to HEADING when provided."
7687 (interactive)
7688 (org-with-wide-buffer
7689 (org-back-to-heading t)
7690 (let ((case-fold-search nil))
7691 (when (looking-at org-complex-heading-regexp)
7692 (let* ((old (match-string-no-properties 4))
7693 (new (save-match-data
7694 (org-trim (or heading (read-string "Edit: " old))))))
7695 (unless (equal old new)
7696 (if old (replace-match new t t nil 4)
7697 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7698 (insert " " new))
7699 (org-set-tags nil t)
7700 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7702 (defun org-insert-heading-after-current ()
7703 "Insert a new heading with same level as current, after current subtree."
7704 (interactive)
7705 (org-back-to-heading)
7706 (org-insert-heading)
7707 (org-move-subtree-down)
7708 (end-of-line 1))
7710 (defun org-insert-heading-respect-content (&optional invisible-ok)
7711 "Insert heading with `org-insert-heading-respect-content' set to t."
7712 (interactive)
7713 (org-insert-heading '(4) invisible-ok))
7715 (defun org-insert-todo-heading-respect-content (&optional force-state)
7716 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7717 (interactive)
7718 (org-insert-todo-heading force-state '(4)))
7720 (defun org-insert-todo-heading (arg &optional force-heading)
7721 "Insert a new heading with the same level and TODO state as current heading.
7723 If the heading has no TODO state, or if the state is DONE, use
7724 the first state (TODO by default). Also with one prefix arg,
7725 force first state. With two prefix args, force inserting at the
7726 end of the parent subtree.
7728 When called at a plain list item, insert a new item with an
7729 unchecked check box."
7730 (interactive "P")
7731 (when (or force-heading (not (org-insert-item 'checkbox)))
7732 (org-insert-heading (or (and (equal arg '(16)) '(16))
7733 force-heading))
7734 (save-excursion
7735 (org-forward-heading-same-level -1)
7736 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7737 (let* ((new-mark-x
7738 (if (or (equal arg '(4))
7739 (not (match-beginning 2))
7740 (member (match-string 2) org-done-keywords))
7741 (car org-todo-keywords-1)
7742 (match-string 2)))
7743 (new-mark
7745 (run-hook-with-args-until-success
7746 'org-todo-get-default-hook new-mark-x nil)
7747 new-mark-x)))
7748 (beginning-of-line 1)
7749 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7750 (if org-treat-insert-todo-heading-as-state-change
7751 (org-todo new-mark)
7752 (insert new-mark " "))))
7753 (when org-provide-todo-statistics
7754 (org-update-parent-todo-statistics))))
7756 (defun org-insert-subheading (arg)
7757 "Insert a new subheading and demote it.
7758 Works for outline headings and for plain lists alike."
7759 (interactive "P")
7760 (org-insert-heading arg)
7761 (cond
7762 ((org-at-heading-p) (org-do-demote))
7763 ((org-at-item-p) (org-indent-item))))
7765 (defun org-insert-todo-subheading (arg)
7766 "Insert a new subheading with TODO keyword or checkbox and demote it.
7767 Works for outline headings and for plain lists alike."
7768 (interactive "P")
7769 (org-insert-todo-heading arg)
7770 (cond
7771 ((org-at-heading-p) (org-do-demote))
7772 ((org-at-item-p) (org-indent-item))))
7774 ;;; Promotion and Demotion
7776 (defvar org-after-demote-entry-hook nil
7777 "Hook run after an entry has been demoted.
7778 The cursor will be at the beginning of the entry.
7779 When a subtree is being demoted, the hook will be called for each node.")
7781 (defvar org-after-promote-entry-hook nil
7782 "Hook run after an entry has been promoted.
7783 The cursor will be at the beginning of the entry.
7784 When a subtree is being promoted, the hook will be called for each node.")
7786 (defun org-promote-subtree ()
7787 "Promote the entire subtree.
7788 See also `org-promote'."
7789 (interactive)
7790 (save-excursion
7791 (org-with-limited-levels (org-map-tree 'org-promote)))
7792 (org-fix-position-after-promote))
7794 (defun org-demote-subtree ()
7795 "Demote the entire subtree.
7796 See `org-demote' and `org-promote'."
7797 (interactive)
7798 (save-excursion
7799 (org-with-limited-levels (org-map-tree 'org-demote)))
7800 (org-fix-position-after-promote))
7802 (defun org-do-promote ()
7803 "Promote the current heading higher up the tree.
7804 If the region is active in `transient-mark-mode', promote all
7805 headings in the region."
7806 (interactive)
7807 (save-excursion
7808 (if (org-region-active-p)
7809 (org-map-region 'org-promote (region-beginning) (region-end))
7810 (org-promote)))
7811 (org-fix-position-after-promote))
7813 (defun org-do-demote ()
7814 "Demote the current heading lower down the tree.
7815 If the region is active in `transient-mark-mode', demote all
7816 headings in the region."
7817 (interactive)
7818 (save-excursion
7819 (if (org-region-active-p)
7820 (org-map-region 'org-demote (region-beginning) (region-end))
7821 (org-demote)))
7822 (org-fix-position-after-promote))
7824 (defun org-fix-position-after-promote ()
7825 "Fix cursor position and indentation after demoting/promoting."
7826 (let ((pos (point)))
7827 (when (save-excursion
7828 (beginning-of-line)
7829 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7830 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7831 (cond ((eobp) (insert " "))
7832 ((eolp) (insert " "))
7833 ((equal (char-after) ?\s) (forward-char 1))))))
7835 (defun org-current-level ()
7836 "Return the level of the current entry, or nil if before the first headline.
7837 The level is the number of stars at the beginning of the
7838 headline. Use `org-reduced-level' to remove the effect of
7839 `org-odd-levels'. Unlike to `org-outline-level', this function
7840 ignores inlinetasks."
7841 (let ((level (org-with-limited-levels (org-outline-level))))
7842 (and (> level 0) level)))
7844 (defun org-get-previous-line-level ()
7845 "Return the outline depth of the last headline before the current line.
7846 Returns 0 for the first headline in the buffer, and nil if before the
7847 first headline."
7848 (and (org-current-level)
7849 (or (and (/= (line-beginning-position) (point-min))
7850 (save-excursion (beginning-of-line 0) (org-current-level)))
7851 0)))
7853 (defun org-reduced-level (l)
7854 "Compute the effective level of a heading.
7855 This takes into account the setting of `org-odd-levels-only'."
7856 (cond
7857 ((zerop l) 0)
7858 (org-odd-levels-only (1+ (floor (/ l 2))))
7859 (t l)))
7861 (defun org-level-increment ()
7862 "Return the number of stars that will be added or removed at a
7863 time to headlines when structure editing, based on the value of
7864 `org-odd-levels-only'."
7865 (if org-odd-levels-only 2 1))
7867 (defun org-get-valid-level (level &optional change)
7868 "Rectify a level change under the influence of `org-odd-levels-only'.
7869 LEVEL is a current level, CHANGE is by how much the level should
7870 be modified. Even if CHANGE is nil, LEVEL may be returned
7871 modified because even level numbers will become the next higher
7872 odd number. Returns values greater than 0."
7873 (if org-odd-levels-only
7874 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7875 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7876 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7877 (max 1 (+ level (or change 0)))))
7879 (defun org-promote ()
7880 "Promote the current heading higher up the tree."
7881 (org-with-wide-buffer
7882 (org-back-to-heading t)
7883 (let* ((after-change-functions (remq 'flyspell-after-change-function
7884 after-change-functions))
7885 (level (save-match-data (funcall outline-level)))
7886 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7887 (diff (abs (- level (length up-head) -1))))
7888 (cond
7889 ((and (= level 1) org-allow-promoting-top-level-subtree)
7890 (replace-match "# " nil t))
7891 ((= level 1)
7892 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7893 (t (replace-match up-head nil t)))
7894 (unless (= level 1)
7895 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7896 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7897 (run-hooks 'org-after-promote-entry-hook))))
7899 (defun org-demote ()
7900 "Demote the current heading lower down the tree."
7901 (org-with-wide-buffer
7902 (org-back-to-heading t)
7903 (let* ((after-change-functions (remq 'flyspell-after-change-function
7904 after-change-functions))
7905 (level (save-match-data (funcall outline-level)))
7906 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7907 (diff (abs (- level (length down-head) -1))))
7908 (replace-match down-head nil t)
7909 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7910 (when org-adapt-indentation (org-fixup-indentation diff))
7911 (run-hooks 'org-after-demote-entry-hook))))
7913 (defun org-cycle-level ()
7914 "Cycle the level of an empty headline through possible states.
7915 This goes first to child, then to parent, level, then up the hierarchy.
7916 After top level, it switches back to sibling level."
7917 (interactive)
7918 (let ((org-adapt-indentation nil))
7919 (when (org-point-at-end-of-empty-headline)
7920 (setq this-command 'org-cycle-level) ; Only needed for caching
7921 (let ((cur-level (org-current-level))
7922 (prev-level (org-get-previous-line-level)))
7923 (cond
7924 ;; If first headline in file, promote to top-level.
7925 ((= prev-level 0)
7926 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7927 do (org-do-promote)))
7928 ;; If same level as prev, demote one.
7929 ((= prev-level cur-level)
7930 (org-do-demote))
7931 ;; If parent is top-level, promote to top level if not already.
7932 ((= prev-level 1)
7933 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7934 do (org-do-promote)))
7935 ;; If top-level, return to prev-level.
7936 ((= cur-level 1)
7937 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7938 do (org-do-demote)))
7939 ;; If less than prev-level, promote one.
7940 ((< cur-level prev-level)
7941 (org-do-promote))
7942 ;; If deeper than prev-level, promote until higher than
7943 ;; prev-level.
7944 ((> cur-level prev-level)
7945 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7946 do (org-do-promote))))
7947 t))))
7949 (defun org-map-tree (fun)
7950 "Call FUN for every heading underneath the current one."
7951 (org-back-to-heading t)
7952 (let ((level (funcall outline-level)))
7953 (save-excursion
7954 (funcall fun)
7955 (while (and (progn
7956 (outline-next-heading)
7957 (> (funcall outline-level) level))
7958 (not (eobp)))
7959 (funcall fun)))))
7961 (defun org-map-region (fun beg end)
7962 "Call FUN for every heading between BEG and END."
7963 (let ((org-ignore-region t))
7964 (save-excursion
7965 (setq end (copy-marker end))
7966 (goto-char beg)
7967 (when (and (re-search-forward org-outline-regexp-bol nil t)
7968 (< (point) end))
7969 (funcall fun))
7970 (while (and (progn
7971 (outline-next-heading)
7972 (< (point) end))
7973 (not (eobp)))
7974 (funcall fun)))))
7976 (defun org-fixup-indentation (diff)
7977 "Change the indentation in the current entry by DIFF.
7979 DIFF is an integer. Indentation is done according to the
7980 following rules:
7982 - Planning information and property drawers are always indented
7983 according to the new level of the headline;
7985 - Footnote definitions and their contents are ignored;
7987 - Inlinetasks' boundaries are not shifted;
7989 - Empty lines are ignored;
7991 - Other lines' indentation are shifted by DIFF columns, unless
7992 it would introduce a structural change in the document, in
7993 which case no shifting is done at all.
7995 Assume point is at a heading or an inlinetask beginning."
7996 (org-with-wide-buffer
7997 (narrow-to-region (line-beginning-position)
7998 (save-excursion
7999 (if (org-with-limited-levels (org-at-heading-p))
8000 (org-with-limited-levels (outline-next-heading))
8001 (org-inlinetask-goto-end))
8002 (point)))
8003 (forward-line)
8004 ;; Indent properly planning info and property drawer.
8005 (when (looking-at-p org-planning-line-re)
8006 (org-indent-line)
8007 (forward-line))
8008 (when (looking-at org-property-drawer-re)
8009 (goto-char (match-end 0))
8010 (forward-line)
8011 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8012 (catch 'no-shift
8013 (when (zerop diff) (throw 'no-shift nil))
8014 ;; If DIFF is negative, first check if a shift is possible at all
8015 ;; (e.g., it doesn't break structure). This can only happen if
8016 ;; some contents are not properly indented.
8017 (let ((case-fold-search t))
8018 (when (< diff 0)
8019 (let ((diff (- diff))
8020 (forbidden-re (concat org-outline-regexp
8021 "\\|"
8022 (substring org-footnote-definition-re 1))))
8023 (save-excursion
8024 (while (not (eobp))
8025 (cond
8026 ((looking-at-p "[ \t]*$") (forward-line))
8027 ((and (looking-at-p org-footnote-definition-re)
8028 (let ((e (org-element-at-point)))
8029 (and (eq (org-element-type e) 'footnote-definition)
8030 (goto-char (org-element-property :end e))))))
8031 ((looking-at-p org-outline-regexp) (forward-line))
8032 ;; Give up if shifting would move before column 0 or
8033 ;; if it would introduce a headline or a footnote
8034 ;; definition.
8036 (skip-chars-forward " \t")
8037 (let ((ind (current-column)))
8038 (when (or (< ind diff)
8039 (and (= ind diff) (looking-at-p forbidden-re)))
8040 (throw 'no-shift nil)))
8041 ;; Ignore contents of example blocks and source
8042 ;; blocks if their indentation is meant to be
8043 ;; preserved. Jump to block's closing line.
8044 (beginning-of-line)
8045 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8046 (let ((e (org-element-at-point)))
8047 (and (memq (org-element-type e)
8048 '(example-block src-block))
8049 (or org-src-preserve-indentation
8050 (org-element-property :preserve-indent e))
8051 (goto-char (org-element-property :end e))
8052 (progn (skip-chars-backward " \r\t\n")
8053 (beginning-of-line)
8054 t))))
8055 (forward-line))))))))
8056 ;; Shift lines but footnote definitions, inlinetasks boundaries
8057 ;; by DIFF. Also skip contents of source or example blocks
8058 ;; when indentation is meant to be preserved.
8059 (while (not (eobp))
8060 (cond
8061 ((and (looking-at-p org-footnote-definition-re)
8062 (let ((e (org-element-at-point)))
8063 (and (eq (org-element-type e) 'footnote-definition)
8064 (goto-char (org-element-property :end e))))))
8065 ((looking-at-p org-outline-regexp) (forward-line))
8066 ((looking-at-p "[ \t]*$") (forward-line))
8068 (indent-line-to (+ (org-get-indentation) diff))
8069 (beginning-of-line)
8070 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8071 (let ((e (org-element-at-point)))
8072 (and (memq (org-element-type e)
8073 '(example-block src-block))
8074 (or org-src-preserve-indentation
8075 (org-element-property :preserve-indent e))
8076 (goto-char (org-element-property :end e))
8077 (progn (skip-chars-backward " \r\t\n")
8078 (beginning-of-line)
8079 t))))
8080 (forward-line)))))))))
8082 (defun org-convert-to-odd-levels ()
8083 "Convert an Org file with all levels allowed to one with odd levels.
8084 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8085 level 5 etc."
8086 (interactive)
8087 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8088 (let ((outline-level 'org-outline-level)
8089 (org-odd-levels-only nil) n)
8090 (save-excursion
8091 (goto-char (point-min))
8092 (while (re-search-forward "^\\*\\*+ " nil t)
8093 (setq n (- (length (match-string 0)) 2))
8094 (while (>= (setq n (1- n)) 0)
8095 (org-demote))
8096 (end-of-line 1))))))
8098 (defun org-convert-to-oddeven-levels ()
8099 "Convert an Org file with only odd levels to one with odd/even levels.
8100 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8101 file contains a section with an even level, conversion would
8102 destroy the structure of the file. An error is signaled in this
8103 case."
8104 (interactive)
8105 (goto-char (point-min))
8106 ;; First check if there are no even levels
8107 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8108 (org-show-set-visibility 'canonical)
8109 (error "Not all levels are odd in this file. Conversion not possible"))
8110 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8111 (let ((outline-regexp org-outline-regexp)
8112 (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 (/ (1- (length (match-string 0))) 2))
8118 (while (>= (setq n (1- n)) 0)
8119 (org-promote))
8120 (end-of-line 1))))))
8122 (defun org-tr-level (n)
8123 "Make N odd if required."
8124 (if org-odd-levels-only (1+ (/ n 2)) n))
8126 ;;; Vertical tree motion, cutting and pasting of subtrees
8128 (defun org-move-subtree-up (&optional arg)
8129 "Move the current subtree up past ARG headlines of the same level."
8130 (interactive "p")
8131 (org-move-subtree-down (- (prefix-numeric-value arg))))
8133 (defun org-move-subtree-down (&optional arg)
8134 "Move the current subtree down past ARG headlines of the same level."
8135 (interactive "p")
8136 (setq arg (prefix-numeric-value arg))
8137 (org-preserve-local-variables
8138 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8139 'org-get-last-sibling))
8140 (ins-point (make-marker))
8141 (cnt (abs arg))
8142 (col (current-column))
8143 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8144 ;; Select the tree
8145 (org-back-to-heading)
8146 (setq beg0 (point))
8147 (save-excursion
8148 (setq ne-beg (org-back-over-empty-lines))
8149 (setq beg (point)))
8150 (save-match-data
8151 (save-excursion (outline-end-of-heading)
8152 (setq folded (org-invisible-p)))
8153 (progn (org-end-of-subtree nil t)
8154 (unless (eobp) (backward-char))))
8155 (outline-next-heading)
8156 (setq ne-end (org-back-over-empty-lines))
8157 (setq end (point))
8158 (goto-char beg0)
8159 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8160 ;; include less whitespace
8161 (save-excursion
8162 (goto-char beg)
8163 (forward-line (- ne-beg ne-end))
8164 (setq beg (point))))
8165 ;; Find insertion point, with error handling
8166 (while (> cnt 0)
8167 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8168 (goto-char beg0)
8169 (user-error "Cannot move past superior level or buffer limit"))
8170 (setq cnt (1- cnt)))
8171 (when (> arg 0)
8172 ;; Moving forward - still need to move over subtree
8173 (org-end-of-subtree t t)
8174 (save-excursion
8175 (org-back-over-empty-lines)
8176 (or (bolp) (newline))))
8177 (setq ne-ins (org-back-over-empty-lines))
8178 (move-marker ins-point (point))
8179 (setq txt (buffer-substring beg end))
8180 (org-save-markers-in-region beg end)
8181 (delete-region beg end)
8182 (org-remove-empty-overlays-at beg)
8183 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8184 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8185 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8186 (let ((bbb (point)))
8187 (insert-before-markers txt)
8188 (org-reinstall-markers-in-region bbb)
8189 (move-marker ins-point bbb))
8190 (or (bolp) (insert "\n"))
8191 (setq ins-end (point))
8192 (goto-char ins-point)
8193 (org-skip-whitespace)
8194 (when (and (< arg 0)
8195 (org-first-sibling-p)
8196 (> ne-ins ne-beg))
8197 ;; Move whitespace back to beginning
8198 (save-excursion
8199 (goto-char ins-end)
8200 (let ((kill-whole-line t))
8201 (kill-line (- ne-ins ne-beg)) (point)))
8202 (insert (make-string (- ne-ins ne-beg) ?\n)))
8203 (move-marker ins-point nil)
8204 (if folded
8205 (outline-hide-subtree)
8206 (org-show-entry)
8207 (org-show-children))
8208 (org-clean-visibility-after-subtree-move)
8209 ;; move back to the initial column we were at
8210 (move-to-column col))))
8212 (defvar org-subtree-clip ""
8213 "Clipboard for cut and paste of subtrees.
8214 This is actually only a copy of the kill, because we use the normal kill
8215 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8217 (defvar org-subtree-clip-folded nil
8218 "Was the last copied subtree folded?
8219 This is used to fold the tree back after pasting.")
8221 (defun org-cut-subtree (&optional n)
8222 "Cut the current subtree into the clipboard.
8223 With prefix arg N, cut this many sequential subtrees.
8224 This is a short-hand for marking the subtree and then cutting it."
8225 (interactive "p")
8226 (org-copy-subtree n 'cut))
8228 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8229 "Copy the current subtree into the clipboard.
8230 With prefix arg N, copy this many sequential subtrees.
8231 This is a short-hand for marking the subtree and then copying it.
8232 If CUT is non-nil, actually cut the subtree.
8233 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8234 of some markers in the region, even if CUT is non-nil. This is
8235 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8236 (interactive "p")
8237 (org-preserve-local-variables
8238 (let (beg end folded (beg0 (point)))
8239 (if (called-interactively-p 'any)
8240 (org-back-to-heading nil) ; take what looks like a subtree
8241 (org-back-to-heading t)) ; take what is really there
8242 (setq beg (point))
8243 (skip-chars-forward " \t\r\n")
8244 (save-match-data
8245 (if nosubtrees
8246 (outline-next-heading)
8247 (save-excursion (outline-end-of-heading)
8248 (setq folded (org-invisible-p)))
8249 (ignore-errors (org-forward-heading-same-level (1- n) t))
8250 (org-end-of-subtree t t)))
8251 ;; Include the end of an inlinetask
8252 (when (and (featurep 'org-inlinetask)
8253 (looking-at-p (concat (org-inlinetask-outline-regexp)
8254 "END[ \t]*$")))
8255 (end-of-line))
8256 (setq end (point))
8257 (goto-char beg0)
8258 (when (> end beg)
8259 (setq org-subtree-clip-folded folded)
8260 (when (or cut force-store-markers)
8261 (org-save-markers-in-region beg end))
8262 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8263 (setq org-subtree-clip (current-kill 0))
8264 (message "%s: Subtree(s) with %d characters"
8265 (if cut "Cut" "Copied")
8266 (length org-subtree-clip))))))
8268 (defun org-paste-subtree (&optional level tree for-yank remove)
8269 "Paste the clipboard as a subtree, with modification of headline level.
8271 The entire subtree is promoted or demoted in order to match a new headline
8272 level.
8274 If the cursor is at the beginning of a headline, the same level as
8275 that headline is used to paste the tree.
8277 If not, the new level is derived from the *visible* headings
8278 before and after the insertion point, and taken to be the inferior headline
8279 level of the two. So if the previous visible heading is level 3 and the
8280 next is level 4 (or vice versa), level 4 will be used for insertion.
8281 This makes sure that the subtree remains an independent subtree and does
8282 not swallow low level entries.
8284 You can also force a different level, either by using a numeric prefix
8285 argument, or by inserting the heading marker by hand. For example, if the
8286 cursor is after \"*****\", then the tree will be shifted to level 5.
8288 If optional TREE is given, use this text instead of the kill ring.
8290 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8291 move back over whitespace before inserting, and move point to the end of
8292 the inserted text when done.
8294 When REMOVE is non-nil, remove the subtree from the clipboard."
8295 (interactive "P")
8296 (setq tree (or tree (and kill-ring (current-kill 0))))
8297 (unless (org-kill-is-subtree-p tree)
8298 (user-error
8299 (substitute-command-keys
8300 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8301 (org-with-limited-levels
8302 (let* ((visp (not (org-invisible-p)))
8303 (txt tree)
8304 (old-level (if (string-match org-outline-regexp-bol txt)
8305 (- (match-end 0) (match-beginning 0) 1)
8306 -1))
8307 (force-level
8308 (cond
8309 (level (prefix-numeric-value level))
8310 ;; When point is right after the stars in an otherwise
8311 ;; empty headline, use stars as the forced level.
8312 ((and (looking-at-p "[ \t]*$")
8313 (string-match-p "^\\*+ *"
8314 (buffer-substring (line-beginning-position)
8315 (point))))
8316 (org-outline-level))
8317 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8318 (previous-level
8319 (save-excursion
8320 (org-previous-visible-heading 1)
8321 (if (org-at-heading-p) (org-outline-level) 1)))
8322 (next-level
8323 (save-excursion
8324 (if (org-at-heading-p) (org-outline-level)
8325 (org-next-visible-heading 1)
8326 (if (org-at-heading-p) (org-outline-level) 1))))
8327 (new-level (or force-level (max previous-level next-level)))
8328 (shift (if (or (= old-level -1)
8329 (= new-level -1)
8330 (= old-level new-level))
8332 (- new-level old-level)))
8333 (delta (if (> shift 0) -1 1))
8334 (func (if (> shift 0) #'org-demote #'org-promote))
8335 (org-odd-levels-only nil)
8336 beg end newend)
8337 ;; Remove the forced level indicator.
8338 (when (and force-level (not level))
8339 (delete-region (line-beginning-position) (point)))
8340 ;; Paste before the next visible heading or at end of buffer,
8341 ;; unless point is at the beginning of a headline.
8342 (unless (and (bolp) (org-at-heading-p))
8343 (org-next-visible-heading 1)
8344 (unless (bolp) (insert "\n")))
8345 (setq beg (point))
8346 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8347 (insert-before-markers txt)
8348 (unless (string-suffix-p "\n" txt) (insert "\n"))
8349 (setq newend (point))
8350 (org-reinstall-markers-in-region beg)
8351 (setq end (point))
8352 (goto-char beg)
8353 (skip-chars-forward " \t\n\r")
8354 (setq beg (point))
8355 (when (and (org-invisible-p) visp)
8356 (save-excursion (outline-show-heading)))
8357 ;; Shift if necessary.
8358 (unless (= shift 0)
8359 (save-restriction
8360 (narrow-to-region beg end)
8361 (while (not (= shift 0))
8362 (org-map-region func (point-min) (point-max))
8363 (setq shift (+ delta shift)))
8364 (goto-char (point-min))
8365 (setq newend (point-max))))
8366 (when (or for-yank (called-interactively-p 'interactive))
8367 (message "Clipboard pasted as level %d subtree" new-level))
8368 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8369 kill-ring
8370 (equal org-subtree-clip (current-kill 0))
8371 org-subtree-clip-folded)
8372 ;; The tree was folded before it was killed/copied
8373 (outline-hide-subtree))
8374 (when for-yank (goto-char newend))
8375 (when remove (pop kill-ring)))))
8377 (defun org-kill-is-subtree-p (&optional txt)
8378 "Check if the current kill is an outline subtree, or a set of trees.
8379 Returns nil if kill does not start with a headline, or if the first
8380 headline level is not the largest headline level in the tree.
8381 So this will actually accept several entries of equal levels as well,
8382 which is OK for `org-paste-subtree'.
8383 If optional TXT is given, check this string instead of the current kill."
8384 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8385 (re (org-get-limited-outline-regexp))
8386 (^re (concat "^" re))
8387 (start-level (and kill
8388 (string-match
8389 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8390 kill)
8391 (- (match-end 2) (match-beginning 2) 1)))
8392 (start (1+ (or (match-beginning 2) -1))))
8393 (if (not start-level)
8394 (progn
8395 nil) ;; does not even start with a heading
8396 (catch 'exit
8397 (while (setq start (string-match ^re kill (1+ start)))
8398 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8399 (throw 'exit nil)))
8400 t))))
8402 (defvar org-markers-to-move nil
8403 "Markers that should be moved with a cut-and-paste operation.
8404 Those markers are stored together with their positions relative to
8405 the start of the region.")
8407 (defun org-save-markers-in-region (beg end)
8408 "Check markers in region.
8409 If these markers are between BEG and END, record their position relative
8410 to BEG, so that after moving the block of text, we can put the markers back
8411 into place.
8412 This function gets called just before an entry or tree gets cut from the
8413 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8414 called immediately, to move the markers with the entries."
8415 (setq org-markers-to-move nil)
8416 (when (featurep 'org-clock)
8417 (org-clock-save-markers-for-cut-and-paste beg end))
8418 (when (featurep 'org-agenda)
8419 (org-agenda-save-markers-for-cut-and-paste beg end)))
8421 (defun org-check-and-save-marker (marker beg end)
8422 "Check if MARKER is between BEG and END.
8423 If yes, remember the marker and the distance to BEG."
8424 (when (and (marker-buffer marker)
8425 (equal (marker-buffer marker) (current-buffer))
8426 (>= marker beg) (< marker end))
8427 (push (cons marker (- marker beg)) org-markers-to-move)))
8429 (defun org-reinstall-markers-in-region (beg)
8430 "Move all remembered markers to their position relative to BEG."
8431 (dolist (x org-markers-to-move)
8432 (move-marker (car x) (+ beg (cdr x))))
8433 (setq org-markers-to-move nil))
8435 (defun org-narrow-to-subtree ()
8436 "Narrow buffer to the current subtree."
8437 (interactive)
8438 (save-excursion
8439 (save-match-data
8440 (org-with-limited-levels
8441 (narrow-to-region
8442 (progn (org-back-to-heading t) (point))
8443 (progn (org-end-of-subtree t t)
8444 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8445 (point)))))))
8447 (defun org-narrow-to-block ()
8448 "Narrow buffer to the current block."
8449 (interactive)
8450 (let* ((case-fold-search t)
8451 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8452 "^[ \t]*#\\+end_.*")))
8453 (if blockp
8454 (narrow-to-region (car blockp) (cdr blockp))
8455 (user-error "Not in a block"))))
8457 (defun org-clone-subtree-with-time-shift (n &optional shift)
8458 "Clone the task (subtree) at point N times.
8459 The clones will be inserted as siblings.
8461 In interactive use, the user will be prompted for the number of
8462 clones to be produced. If the entry has a timestamp, the user
8463 will also be prompted for a time shift, which may be a repeater
8464 as used in time stamps, for example `+3d'. To disable this,
8465 you can call the function with a universal prefix argument.
8467 When a valid repeater is given and the entry contains any time
8468 stamps, the clones will become a sequence in time, with time
8469 stamps in the subtree shifted for each clone produced. If SHIFT
8470 is nil or the empty string, time stamps will be left alone. The
8471 ID property of the original subtree is removed.
8473 In each clone, all the CLOCK entries will be removed. This
8474 prevents Org from considering that the clocked times overlap.
8476 If the original subtree did contain time stamps with a repeater,
8477 the following will happen:
8478 - the repeater will be removed in each clone
8479 - an additional clone will be produced, with the current, unshifted
8480 date(s) in the entry.
8481 - the original entry will be placed *after* all the clones, with
8482 repeater intact.
8483 - the start days in the repeater in the original entry will be shifted
8484 to past the last clone.
8485 In this way you can spell out a number of instances of a repeating task,
8486 and still retain the repeater to cover future instances of the task.
8488 As described above, N+1 clones are produced when the original
8489 subtree has a repeater. Setting N to 0, then, can be used to
8490 remove the repeater from a subtree and create a shifted clone
8491 with the original repeater."
8492 (interactive "nNumber of clones to produce: ")
8493 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8494 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8495 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8496 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8497 (shift
8498 (or shift
8499 (if (and (not (equal current-prefix-arg '(4)))
8500 (save-excursion
8501 (goto-char beg)
8502 (re-search-forward org-ts-regexp-both end-of-tree t)))
8503 (read-from-minibuffer
8504 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8505 ""))) ;No time shift
8506 (doshift
8507 (and (org-string-nw-p shift)
8508 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8509 shift)
8510 (user-error "Invalid shift specification %s" shift)))))
8511 (goto-char end-of-tree)
8512 (unless (bolp) (insert "\n"))
8513 (let* ((end (point))
8514 (template (buffer-substring beg end))
8515 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8516 (shift-what (pcase (and doshift (match-string 2 shift))
8517 (`nil nil)
8518 ("d" 'day)
8519 ("w" (setq shift-n (* 7 shift-n)) 'day)
8520 ("m" 'month)
8521 ("y" 'year)
8522 (_ (error "Unsupported time unit"))))
8523 (nmin 1)
8524 (nmax n)
8525 (n-no-remove -1)
8526 (idprop (org-entry-get nil "ID")))
8527 (when (and doshift
8528 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8529 template))
8530 (delete-region beg end)
8531 (setq end beg)
8532 (setq nmin 0)
8533 (setq nmax (1+ nmax))
8534 (setq n-no-remove nmax))
8535 (goto-char end)
8536 (cl-loop for n from nmin to nmax do
8537 (insert
8538 ;; Prepare clone.
8539 (with-temp-buffer
8540 (insert template)
8541 (org-mode)
8542 (goto-char (point-min))
8543 (org-show-subtree)
8544 (and idprop (if org-clone-delete-id
8545 (org-entry-delete nil "ID")
8546 (org-id-get-create t)))
8547 (unless (= n 0)
8548 (while (re-search-forward org-clock-line-re nil t)
8549 (delete-region (line-beginning-position)
8550 (line-beginning-position 2)))
8551 (goto-char (point-min))
8552 (while (re-search-forward org-drawer-regexp nil t)
8553 (org-remove-empty-drawer-at (point))))
8554 (goto-char (point-min))
8555 (when doshift
8556 (while (re-search-forward org-ts-regexp-both nil t)
8557 (org-timestamp-change (* n shift-n) shift-what))
8558 (unless (= n n-no-remove)
8559 (goto-char (point-min))
8560 (while (re-search-forward org-ts-regexp nil t)
8561 (save-excursion
8562 (goto-char (match-beginning 0))
8563 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8564 (delete-region (match-beginning 1) (match-end 1)))))))
8565 (buffer-string)))))
8566 (goto-char beg)))
8568 ;;; Outline Sorting
8570 (defun org-sort (&optional with-case)
8571 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8572 Optional argument WITH-CASE means sort case-sensitively."
8573 (interactive "P")
8574 (org-call-with-arg
8575 (cond ((org-at-table-p) #'org-table-sort-lines)
8576 ((org-at-item-p) #'org-sort-list)
8577 (t #'org-sort-entries))
8578 with-case))
8580 (defun org-sort-remove-invisible (s)
8581 "Remove invisible part of links and emphasis markers from string S."
8582 (remove-text-properties 0 (length s) org-rm-props s)
8583 (replace-regexp-in-string
8584 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8585 (replace-regexp-in-string
8586 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8587 (org-link-display-format s)
8588 t t) t t))
8590 (defvar org-priority-regexp) ; defined later in the file
8592 (defvar org-after-sorting-entries-or-items-hook nil
8593 "Hook that is run after a bunch of entries or items have been sorted.
8594 When children are sorted, the cursor is in the parent line when this
8595 hook gets called. When a region or a plain list is sorted, the cursor
8596 will be in the first entry of the sorted region/list.")
8598 (defun org-sort-entries
8599 (&optional with-case sorting-type getkey-func compare-func property
8600 interactive?)
8601 "Sort entries on a certain level of an outline tree.
8602 If there is an active region, the entries in the region are sorted.
8603 Else, if the cursor is before the first entry, sort the top-level items.
8604 Else, the children of the entry at point are sorted.
8606 Sorting can be alphabetically, numerically, by date/time as given by
8607 a time stamp, by a property, by priority order, or by a custom function.
8609 The command prompts for the sorting type unless it has been given to the
8610 function through the SORTING-TYPE argument, which needs to be a character,
8611 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8612 the precise meaning of each character:
8614 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8615 c By creation time, which is assumed to be the first inactive time stamp
8616 at the beginning of a line.
8617 d By deadline date/time.
8618 k By clocking time.
8619 n Numerically, by converting the beginning of the entry/item to a number.
8620 o By order of TODO keywords.
8621 p By priority according to the cookie.
8622 r By the value of a property.
8623 s By scheduled date/time.
8624 t By date/time, either the first active time stamp in the entry, or, if
8625 none exist, by the first inactive one.
8627 Capital letters will reverse the sort order.
8629 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8630 called with point at the beginning of the record. It must return a
8631 value that is compatible with COMPARE-FUNC, the function used to
8632 compare entries.
8634 Comparing entries ignores case by default. However, with an optional argument
8635 WITH-CASE, the sorting considers case as well.
8637 Sorting is done against the visible part of the headlines, it ignores hidden
8638 links.
8640 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8642 A non-nil value for INTERACTIVE? is used to signal that this
8643 function is being called interactively."
8644 (interactive (list current-prefix-arg nil nil nil nil t))
8645 (let ((case-func (if with-case 'identity 'downcase))
8646 start beg end stars re re2
8647 txt what tmp)
8648 ;; Find beginning and end of region to sort
8649 (cond
8650 ((org-region-active-p)
8651 ;; we will sort the region
8652 (setq end (region-end)
8653 what "region")
8654 (goto-char (region-beginning))
8655 (unless (org-at-heading-p) (outline-next-heading))
8656 (setq start (point)))
8657 ((or (org-at-heading-p)
8658 (ignore-errors (progn (org-back-to-heading) t)))
8659 ;; we will sort the children of the current headline
8660 (org-back-to-heading)
8661 (setq start (point)
8662 end (progn (org-end-of-subtree t t)
8663 (or (bolp) (insert "\n"))
8664 (when (>= (org-back-over-empty-lines) 1)
8665 (forward-line 1))
8666 (point))
8667 what "children")
8668 (goto-char start)
8669 (outline-show-subtree)
8670 (outline-next-heading))
8672 ;; we will sort the top-level entries in this file
8673 (goto-char (point-min))
8674 (or (org-at-heading-p) (outline-next-heading))
8675 (setq start (point))
8676 (goto-char (point-max))
8677 (beginning-of-line 1)
8678 (when (looking-at ".*?\\S-")
8679 ;; File ends in a non-white line
8680 (end-of-line 1)
8681 (insert "\n"))
8682 (setq end (point-max))
8683 (setq what "top-level")
8684 (goto-char start)
8685 (org-show-all '(headings blocks))))
8687 (setq beg (point))
8688 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8690 (looking-at "\\(\\*+\\)")
8691 (setq stars (match-string 1)
8692 re (concat "^" (regexp-quote stars) " +")
8693 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8694 txt (buffer-substring beg end))
8695 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8696 (when (and (not (equal stars "*")) (string-match re2 txt))
8697 (user-error "Region to sort contains a level above the first entry"))
8699 (unless sorting-type
8700 (message
8701 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8702 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8703 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8704 what)
8705 (setq sorting-type (read-char-exclusive)))
8707 (unless getkey-func
8708 (and (= (downcase sorting-type) ?f)
8709 (setq getkey-func
8710 (or (and interactive?
8711 (org-read-function
8712 "Function for extracting keys: "))
8713 (error "Missing key extractor")))))
8715 (and (= (downcase sorting-type) ?r)
8716 (not property)
8717 (setq property
8718 (completing-read "Property: "
8719 (mapcar #'list (org-buffer-property-keys t))
8720 nil t)))
8722 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8723 (message "Sorting entries...")
8725 (save-restriction
8726 (narrow-to-region start end)
8727 (let ((restore-clock?
8728 ;; The clock marker is lost when using `sort-subr'; mark
8729 ;; the clock with temporary `:org-clock-marker-backup'
8730 ;; text property.
8731 (when (and (eq (org-clock-is-active) (current-buffer))
8732 (<= start (marker-position org-clock-marker))
8733 (>= end (marker-position org-clock-marker)))
8734 (org-with-silent-modifications
8735 (put-text-property (1- org-clock-marker) org-clock-marker
8736 :org-clock-marker-backup t))
8738 (dcst (downcase sorting-type))
8739 (case-fold-search nil)
8740 (now (current-time)))
8741 (org-preserve-local-variables
8742 (sort-subr
8743 (/= dcst sorting-type)
8744 ;; This function moves to the beginning character of the
8745 ;; "record" to be sorted.
8746 (lambda nil
8747 (if (re-search-forward re nil t)
8748 (goto-char (match-beginning 0))
8749 (goto-char (point-max))))
8750 ;; This function moves to the last character of the "record" being
8751 ;; sorted.
8752 (lambda nil
8753 (save-match-data
8754 (condition-case nil
8755 (outline-forward-same-level 1)
8756 (error
8757 (goto-char (point-max))))))
8758 ;; This function returns the value that gets sorted against.
8759 (lambda ()
8760 (cond
8761 ((= dcst ?n)
8762 (string-to-number
8763 (org-sort-remove-invisible (org-get-heading t t t t))))
8764 ((= dcst ?a)
8765 (funcall case-func
8766 (org-sort-remove-invisible (org-get-heading t t t t))))
8767 ((= dcst ?k)
8768 (or (get-text-property (point) :org-clock-minutes) 0))
8769 ((= dcst ?t)
8770 (let ((end (save-excursion (outline-next-heading) (point))))
8771 (if (or (re-search-forward org-ts-regexp end t)
8772 (re-search-forward org-ts-regexp-both end t))
8773 (org-time-string-to-seconds (match-string 0))
8774 (float-time now))))
8775 ((= dcst ?c)
8776 (let ((end (save-excursion (outline-next-heading) (point))))
8777 (if (re-search-forward
8778 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8779 end t)
8780 (org-time-string-to-seconds (match-string 0))
8781 (float-time now))))
8782 ((= dcst ?s)
8783 (let ((end (save-excursion (outline-next-heading) (point))))
8784 (if (re-search-forward org-scheduled-time-regexp end t)
8785 (org-time-string-to-seconds (match-string 1))
8786 (float-time now))))
8787 ((= dcst ?d)
8788 (let ((end (save-excursion (outline-next-heading) (point))))
8789 (if (re-search-forward org-deadline-time-regexp end t)
8790 (org-time-string-to-seconds (match-string 1))
8791 (float-time now))))
8792 ((= dcst ?p)
8793 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8794 (string-to-char (match-string 2))
8795 org-default-priority))
8796 ((= dcst ?r)
8797 (or (org-entry-get nil property) ""))
8798 ((= dcst ?o)
8799 (when (looking-at org-complex-heading-regexp)
8800 (let* ((m (match-string 2))
8801 (s (if (member m org-done-keywords) '- '+)))
8802 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8803 ((= dcst ?f)
8804 (if getkey-func
8805 (progn
8806 (setq tmp (funcall getkey-func))
8807 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8808 tmp)
8809 (error "Invalid key function `%s'" getkey-func)))
8810 (t (error "Invalid sorting type `%c'" sorting-type))))
8812 (cond
8813 ((= dcst ?a) 'org-string-collate-lessp)
8814 ((= dcst ?f)
8815 (or compare-func
8816 (and interactive?
8817 (org-read-function
8818 (concat "Function for comparing keys "
8819 "(empty for default `sort-subr' predicate): ")
8820 'allow-empty))))
8821 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8822 (when restore-clock?
8823 (move-marker org-clock-marker
8824 (1+ (next-single-property-change
8825 start :org-clock-marker-backup)))
8826 (remove-text-properties (1- org-clock-marker) org-clock-marker
8827 '(:org-clock-marker-backup t)))))
8828 (run-hooks 'org-after-sorting-entries-or-items-hook)
8829 (message "Sorting entries...done")))
8831 (defun org-contextualize-keys (alist contexts)
8832 "Return valid elements in ALIST depending on CONTEXTS.
8834 `org-agenda-custom-commands' or `org-capture-templates' are the
8835 values used for ALIST, and `org-agenda-custom-commands-contexts'
8836 or `org-capture-templates-contexts' are the associated contexts
8837 definitions."
8838 (let ((contexts
8839 ;; normalize contexts
8840 (mapcar
8841 (lambda(c) (cond ((listp (cadr c))
8842 (list (car c) (car c) (nth 1 c)))
8843 ((string= "" (cadr c))
8844 (list (car c) (car c) (nth 2 c)))
8845 (t c)))
8846 contexts))
8847 (a alist) r s)
8848 ;; loop over all commands or templates
8849 (dolist (c a)
8850 (let (vrules repl)
8851 (cond
8852 ((not (assoc (car c) contexts))
8853 (push c r))
8854 ((and (assoc (car c) contexts)
8855 (setq vrules (org-contextualize-validate-key
8856 (car c) contexts)))
8857 (mapc (lambda (vr)
8858 (unless (equal (car vr) (cadr vr))
8859 (setq repl vr)))
8860 vrules)
8861 (if (not repl) (push c r)
8862 (push (cadr repl) s)
8863 (push
8864 (cons (car c)
8865 (cdr (or (assoc (cadr repl) alist)
8866 (error "Undefined key `%s' as contextual replacement for `%s'"
8867 (cadr repl) (car c)))))
8868 r))))))
8869 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8870 (delq
8872 (delete-dups
8873 (mapcar (lambda (x)
8874 (let ((tpl (car x)))
8875 (unless (delq
8877 (mapcar (lambda (y)
8878 (equal y tpl))
8880 x)))
8881 (reverse r))))))
8883 (defun org-contextualize-validate-key (key contexts)
8884 "Check CONTEXTS for agenda or capture KEY."
8885 (let (res)
8886 (dolist (r contexts)
8887 (dolist (rr (car (last r)))
8888 (when
8889 (and (equal key (car r))
8890 (if (functionp rr) (funcall rr)
8891 (or (and (eq (car rr) 'in-file)
8892 (buffer-file-name)
8893 (string-match (cdr rr) (buffer-file-name)))
8894 (and (eq (car rr) 'in-mode)
8895 (string-match (cdr rr) (symbol-name major-mode)))
8896 (and (eq (car rr) 'in-buffer)
8897 (string-match (cdr rr) (buffer-name)))
8898 (when (and (eq (car rr) 'not-in-file)
8899 (buffer-file-name))
8900 (not (string-match (cdr rr) (buffer-file-name))))
8901 (when (eq (car rr) 'not-in-mode)
8902 (not (string-match (cdr rr) (symbol-name major-mode))))
8903 (when (eq (car rr) 'not-in-buffer)
8904 (not (string-match (cdr rr) (buffer-name)))))))
8905 (push r res))))
8906 (delete-dups (delq nil res))))
8908 ;; Defined to provide a value for defcustom, since there is no
8909 ;; string-collate-greaterp in Emacs.
8910 (defun org-string-collate-greaterp (s1 s2)
8911 "Return non-nil if S1 is greater than S2 in collation order."
8912 (not (org-string-collate-lessp s1 s2)))
8914 ;;;###autoload
8915 (defun org-run-like-in-org-mode (cmd)
8916 "Run a command, pretending that the current buffer is in Org mode.
8917 This will temporarily bind local variables that are typically bound in
8918 Org mode to the values they have in Org mode, and then interactively
8919 call CMD."
8920 (org-load-modules-maybe)
8921 (let (binds)
8922 (dolist (var (org-get-local-variables))
8923 (when (or (not (boundp (car var)))
8924 (eq (symbol-value (car var))
8925 (default-value (car var))))
8926 (push (list (car var) `(quote ,(cadr var))) binds)))
8927 (eval `(let ,binds
8928 (call-interactively (quote ,cmd))))))
8930 (defun org-get-category (&optional pos force-refresh)
8931 "Get the category applying to position POS."
8932 (save-match-data
8933 (when force-refresh (org-refresh-category-properties))
8934 (let ((pos (or pos (point))))
8935 (or (get-text-property pos 'org-category)
8936 (progn (org-refresh-category-properties)
8937 (get-text-property pos 'org-category))))))
8939 ;;; Refresh properties
8941 (defun org-refresh-properties (dprop tprop)
8942 "Refresh buffer text properties.
8943 DPROP is the drawer property and TPROP is either the
8944 corresponding text property to set, or an alist with each element
8945 being a text property (as a symbol) and a function to apply to
8946 the value of the drawer property."
8947 (let* ((case-fold-search t)
8948 (inhibit-read-only t)
8949 (inherit? (org-property-inherit-p dprop))
8950 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8951 (global (and inherit? (org--property-global-value dprop nil))))
8952 (org-with-silent-modifications
8953 (org-with-point-at 1
8954 ;; Set global values (e.g., values defined through
8955 ;; "#+PROPERTY:" keywords) to the whole buffer.
8956 (when global (put-text-property (point-min) (point-max) tprop global))
8957 ;; Set local values.
8958 (while (re-search-forward property-re nil t)
8959 (when (org-at-property-p)
8960 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8961 (outline-next-heading))))))
8963 (defun org-refresh-property (tprop p &optional inherit)
8964 "Refresh the buffer text property TPROP from the drawer property P.
8965 The refresh happens only for the current headline, or the whole
8966 sub-tree if optional argument INHERIT is non-nil."
8967 (unless (org-before-first-heading-p)
8968 (save-excursion
8969 (org-back-to-heading t)
8970 (let ((start (point))
8971 (end (save-excursion
8972 (if inherit (org-end-of-subtree t t)
8973 (or (outline-next-heading) (point-max))))))
8974 (if (symbolp tprop)
8975 ;; TPROP is a text property symbol.
8976 (put-text-property start end tprop p)
8977 ;; TPROP is an alist with (property . function) elements.
8978 (pcase-dolist (`(,prop . ,f) tprop)
8979 (put-text-property start end prop (funcall f p))))))))
8981 (defun org-refresh-category-properties ()
8982 "Refresh category text properties in the buffer."
8983 (let ((case-fold-search t)
8984 (inhibit-read-only t)
8985 (default-category
8986 (cond ((null org-category)
8987 (if buffer-file-name
8988 (file-name-sans-extension
8989 (file-name-nondirectory buffer-file-name))
8990 "???"))
8991 ((symbolp org-category) (symbol-name org-category))
8992 (t org-category))))
8993 (org-with-silent-modifications
8994 (org-with-wide-buffer
8995 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8996 ;; This is the default category for the buffer. If none is
8997 ;; found, fall-back to `org-category' or buffer file name.
8998 (put-text-property
8999 (point-min) (point-max)
9000 'org-category
9001 (catch 'buffer-category
9002 (goto-char (point-max))
9003 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9004 (let ((element (org-element-at-point)))
9005 (when (eq (org-element-type element) 'keyword)
9006 (throw 'buffer-category
9007 (org-element-property :value element)))))
9008 default-category))
9009 ;; Set sub-tree specific categories.
9010 (goto-char (point-min))
9011 (let ((regexp (org-re-property "CATEGORY")))
9012 (while (re-search-forward regexp nil t)
9013 (let ((value (match-string-no-properties 3)))
9014 (when (org-at-property-p)
9015 (put-text-property
9016 (save-excursion (org-back-to-heading t) (point))
9017 (save-excursion (org-end-of-subtree t t) (point))
9018 'org-category
9019 value)))))))))
9021 (defun org-refresh-stats-properties ()
9022 "Refresh stats text properties in the buffer."
9023 (org-with-silent-modifications
9024 (org-with-point-at 1
9025 (let ((regexp (concat org-outline-regexp-bol
9026 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9027 (while (re-search-forward regexp nil t)
9028 (let* ((numerator (string-to-number (match-string 1)))
9029 (denominator (and (match-end 2)
9030 (string-to-number (match-string 2))))
9031 (stats (cond ((not denominator) numerator) ;percent
9032 ((= denominator 0) 0)
9033 (t (/ (* numerator 100) denominator)))))
9034 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9035 'org-stats stats)))))))
9037 (defun org-refresh-effort-properties ()
9038 "Refresh effort properties"
9039 (org-refresh-properties
9040 org-effort-property
9041 '((effort . identity)
9042 (effort-minutes . org-duration-to-minutes))))
9044 ;;;; Link Stuff
9046 ;;; Link abbreviations
9048 (defun org-link-expand-abbrev (link)
9049 "Apply replacements as defined in `org-link-abbrev-alist'."
9050 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9051 (let* ((key (match-string 1 link))
9052 (as (or (assoc key org-link-abbrev-alist-local)
9053 (assoc key org-link-abbrev-alist)))
9054 (tag (and (match-end 2) (match-string 3 link)))
9055 rpl)
9056 (if (not as)
9057 link
9058 (setq rpl (cdr as))
9059 (cond
9060 ((symbolp rpl) (funcall rpl tag))
9061 ((string-match "%(\\([^)]+\\))" rpl)
9062 (replace-match
9063 (save-match-data
9064 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9065 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9066 ((string-match "%h" rpl)
9067 (replace-match (url-hexify-string (or tag "")) t t rpl))
9068 (t (concat rpl tag)))))
9069 link))
9071 ;;; Storing and inserting links
9073 (defvar org-insert-link-history nil
9074 "Minibuffer history for links inserted with `org-insert-link'.")
9076 (defvar org-stored-links nil
9077 "Contains the links stored with `org-store-link'.")
9079 (defvar org-store-link-plist nil
9080 "Plist with info about the most recently link created with `org-store-link'.")
9082 (defun org-store-link-functions ()
9083 "Return a list of functions that are called to create and store a link.
9084 The functions defined in the :store property of
9085 `org-link-parameters'.
9087 Each function will be called in turn until one returns a non-nil
9088 value. Each function should check if it is responsible for
9089 creating this link (for example by looking at the major mode).
9090 If not, it must exit and return nil. If yes, it should return
9091 a non-nil value after calling `org-store-link-props' with a list
9092 of properties and values. Special properties are:
9094 :type The link prefix, like \"http\". This must be given.
9095 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9096 This is obligatory as well.
9097 :description Optional default description for the second pair
9098 of brackets in an Org mode link. The user can still change
9099 this when inserting this link into an Org mode buffer.
9101 In addition to these, any additional properties can be specified
9102 and then used in capture templates."
9103 (cl-loop for link in org-link-parameters
9104 with store-func
9105 do (setq store-func (org-link-get-parameter (car link) :store))
9106 if store-func
9107 collect store-func))
9109 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9110 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9112 ;;;###autoload
9113 (defun org-store-link (arg &optional interactive?)
9114 "Store an org-link to the current location.
9115 \\<org-mode-map>
9116 This link is added to `org-stored-links' and can later be inserted
9117 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9119 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9120 A single
9121 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9122 `org-gnus-prefer-web-links' for links to Usenet articles.
9124 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9125 skipping storing functions that are not
9126 part of Org core.
9128 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9129 prefix ARG forces storing a link for each line in the
9130 active region.
9132 Assume the function is called interactively if INTERACTIVE? is
9133 non-nil."
9134 (interactive "P\np")
9135 (org-load-modules-maybe)
9136 (if (and (equal arg '(64)) (org-region-active-p))
9137 (save-excursion
9138 (let ((end (region-end)))
9139 (goto-char (region-beginning))
9140 (set-mark (point))
9141 (while (< (point-at-eol) end)
9142 (move-end-of-line 1) (activate-mark)
9143 (let (current-prefix-arg)
9144 (call-interactively 'org-store-link))
9145 (move-beginning-of-line 2)
9146 (set-mark (point)))))
9147 (setq org-store-link-plist nil)
9148 (let (link cpltxt desc description search txt custom-id agenda-link)
9149 (cond
9150 ;; Store a link using an external link type, if any function is
9151 ;; available. If more than one can generate a link from current
9152 ;; location, ask which one to use.
9153 ((and (not (equal arg '(16)))
9154 (let ((results-alist nil))
9155 (dolist (f (org-store-link-functions))
9156 (when (funcall f)
9157 ;; XXX: return value is not link's plist, so we
9158 ;; store the new value before it is modified. It
9159 ;; would be cleaner to ask store link functions to
9160 ;; return the plist instead.
9161 (push (cons f (copy-sequence org-store-link-plist))
9162 results-alist)))
9163 (pcase results-alist
9164 (`nil nil)
9165 (`((,_ . ,_)) t) ;single choice: nothing to do
9166 (`((,name . ,_) . ,_)
9167 ;; Reinstate link plist associated to the chosen
9168 ;; function.
9169 (apply #'org-store-link-props
9170 (cdr (assoc-string
9171 (completing-read
9172 "Which function for creating the link? "
9173 (mapcar #'car results-alist)
9174 nil t (symbol-name name))
9175 results-alist)))
9176 t))))
9177 (setq link (plist-get org-store-link-plist :link))
9178 (setq desc (or (plist-get org-store-link-plist :description)
9179 link)))
9181 ;; Store a link from a source code buffer.
9182 ((org-src-edit-buffer-p)
9183 (let ((coderef-format (org-src-coderef-format)))
9184 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9185 (setq link (format "(%s)" (match-string-no-properties 3))))
9186 (interactive?
9187 (let ((label (read-string "Code line label: ")))
9188 (end-of-line)
9189 (setq link (format coderef-format label))
9190 (let ((gc (- 79 (length link))))
9191 (if (< (current-column) gc)
9192 (org-move-to-column gc t)
9193 (insert " ")))
9194 (insert link)
9195 (setq link (concat "(" label ")"))
9196 (setq desc nil)))
9197 (t (setq link nil)))))
9199 ;; We are in the agenda, link to referenced location
9200 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9201 (let ((m (or (get-text-property (point) 'org-hd-marker)
9202 (get-text-property (point) 'org-marker))))
9203 (when m
9204 (org-with-point-at m
9205 (setq agenda-link (org-store-link nil interactive?))))))
9207 ((eq major-mode 'calendar-mode)
9208 (let ((cd (calendar-cursor-to-date)))
9209 (setq link
9210 (format-time-string
9211 (car org-time-stamp-formats)
9212 (apply 'encode-time
9213 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9214 nil nil nil))))
9215 (org-store-link-props :type "calendar" :date cd)))
9217 ((eq major-mode 'help-mode)
9218 (setq link (concat "help:" (save-excursion
9219 (goto-char (point-min))
9220 (looking-at "^[^ ]+")
9221 (match-string 0))))
9222 (org-store-link-props :type "help"))
9224 ((eq major-mode 'w3-mode)
9225 (setq cpltxt (if (and (buffer-name)
9226 (not (string-match "Untitled" (buffer-name))))
9227 (buffer-name)
9228 (url-view-url t))
9229 link (url-view-url t))
9230 (org-store-link-props :type "w3" :url (url-view-url t)))
9232 ((eq major-mode 'image-mode)
9233 (setq cpltxt (concat "file:"
9234 (abbreviate-file-name buffer-file-name))
9235 link cpltxt)
9236 (org-store-link-props :type "image" :file buffer-file-name))
9238 ;; In dired, store a link to the file of the current line
9239 ((derived-mode-p 'dired-mode)
9240 (let ((file (dired-get-filename nil t)))
9241 (setq file (if file
9242 (abbreviate-file-name
9243 (expand-file-name (dired-get-filename nil t)))
9244 ;; otherwise, no file so use current directory.
9245 default-directory))
9246 (setq cpltxt (concat "file:" file)
9247 link cpltxt)))
9249 ((setq search (run-hook-with-args-until-success
9250 'org-create-file-search-functions))
9251 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9252 "::" search))
9253 (setq cpltxt (or description link)))
9255 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9256 (org-with-limited-levels
9257 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9258 (cond
9259 ;; Store a link using the target at point
9260 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9261 (setq cpltxt
9262 (concat "file:"
9263 (abbreviate-file-name
9264 (buffer-file-name (buffer-base-buffer)))
9265 "::" (match-string 1))
9266 link cpltxt))
9267 ((and (featurep 'org-id)
9268 (or (eq org-id-link-to-org-use-id t)
9269 (and interactive?
9270 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9271 (and (eq org-id-link-to-org-use-id
9272 'create-if-interactive-and-no-custom-id)
9273 (not custom-id))))
9274 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9275 ;; Store a link using the ID at point
9276 (setq link (condition-case nil
9277 (prog1 (org-id-store-link)
9278 (setq desc (or (plist-get org-store-link-plist
9279 :description)
9280 "")))
9281 (error
9282 ;; Probably before first headline, link only to file
9283 (concat "file:"
9284 (abbreviate-file-name
9285 (buffer-file-name (buffer-base-buffer))))))))
9287 ;; Just link to current headline
9288 (setq cpltxt (concat "file:"
9289 (abbreviate-file-name
9290 (buffer-file-name (buffer-base-buffer)))))
9291 ;; Add a context search string
9292 (when (org-xor org-context-in-file-links
9293 (equal arg '(4)))
9294 (let* ((element (org-element-at-point))
9295 (name (org-element-property :name element)))
9296 (setq txt (cond
9297 ((org-at-heading-p) nil)
9298 (name)
9299 ((org-region-active-p)
9300 (buffer-substring (region-beginning) (region-end)))))
9301 (when (or (null txt) (string-match "\\S-" txt))
9302 (setq cpltxt
9303 (concat cpltxt "::"
9304 (condition-case nil
9305 (org-make-org-heading-search-string txt)
9306 (error "")))
9307 desc (or name
9308 (nth 4 (ignore-errors (org-heading-components)))
9309 "NONE")))))
9310 (when (string-match "::\\'" cpltxt)
9311 (setq cpltxt (substring cpltxt 0 -2)))
9312 (setq link cpltxt)))))
9314 ((buffer-file-name (buffer-base-buffer))
9315 ;; Just link to this file here.
9316 (setq cpltxt (concat "file:"
9317 (abbreviate-file-name
9318 (buffer-file-name (buffer-base-buffer)))))
9319 ;; Add a context string.
9320 (when (org-xor org-context-in-file-links
9321 (equal arg '(4)))
9322 (setq txt (if (org-region-active-p)
9323 (buffer-substring (region-beginning) (region-end))
9324 (buffer-substring (point-at-bol) (point-at-eol))))
9325 ;; Only use search option if there is some text.
9326 (when (string-match "\\S-" txt)
9327 (setq cpltxt
9328 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9329 desc "NONE")))
9330 (setq link cpltxt))
9332 (interactive?
9333 (user-error "No method for storing a link from this buffer"))
9335 (t (setq link nil)))
9337 ;; We're done setting link and desc, clean up
9338 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9339 (setq link (or link cpltxt)
9340 desc (or desc cpltxt))
9341 (cond ((not desc))
9342 ((equal desc "NONE") (setq desc nil))
9343 (t (setq desc
9344 (replace-regexp-in-string
9345 org-bracket-link-analytic-regexp
9346 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9347 desc))))
9348 ;; Return the link
9349 (if (not (and interactive? link))
9350 (or agenda-link (and link (org-make-link-string link desc)))
9351 (push (list link desc) org-stored-links)
9352 (message "Stored: %s" (or desc link))
9353 (when custom-id
9354 (setq link (concat "file:" (abbreviate-file-name
9355 (buffer-file-name)) "::#" custom-id))
9356 (push (list link desc) org-stored-links))
9357 (car org-stored-links)))))
9359 (defun org-store-link-props (&rest plist)
9360 "Store link properties.
9361 The properties are pre-processed by extracting names, addresses
9362 and dates."
9363 (let ((x (plist-get plist :from)))
9364 (when x
9365 (let ((adr (mail-extract-address-components x)))
9366 (setq plist (plist-put plist :fromname (car adr)))
9367 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9368 (let ((x (plist-get plist :to)))
9369 (when x
9370 (let ((adr (mail-extract-address-components x)))
9371 (setq plist (plist-put plist :toname (car adr)))
9372 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9373 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9374 (when x
9375 (setq plist (plist-put plist :date-timestamp
9376 (format-time-string
9377 (org-time-stamp-format t) x)))
9378 (setq plist (plist-put plist :date-timestamp-inactive
9379 (format-time-string
9380 (org-time-stamp-format t t) x)))))
9381 (let ((from (plist-get plist :from))
9382 (to (plist-get plist :to)))
9383 (when (and from to org-from-is-user-regexp)
9384 (setq plist
9385 (plist-put plist :fromto
9386 (if (string-match org-from-is-user-regexp from)
9387 (concat "to %t")
9388 (concat "from %f"))))))
9389 (setq org-store-link-plist plist))
9391 (defun org-add-link-props (&rest plist)
9392 "Add these properties to the link property list."
9393 (let (key value)
9394 (while plist
9395 (setq key (pop plist) value (pop plist))
9396 (setq org-store-link-plist
9397 (plist-put org-store-link-plist key value)))))
9399 (defun org-email-link-description (&optional fmt)
9400 "Return the description part of an email link.
9401 This takes information from `org-store-link-plist' and formats it
9402 according to FMT (default from `org-email-link-description-format')."
9403 (setq fmt (or fmt org-email-link-description-format))
9404 (let* ((p org-store-link-plist)
9405 (to (plist-get p :toaddress))
9406 (from (plist-get p :fromaddress))
9407 (table
9408 (list
9409 (cons "%c" (plist-get p :fromto))
9410 (cons "%F" (plist-get p :from))
9411 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9412 (cons "%T" (plist-get p :to))
9413 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9414 (cons "%s" (plist-get p :subject))
9415 (cons "%d" (plist-get p :date))
9416 (cons "%m" (plist-get p :message-id)))))
9417 (when (string-match "%c" fmt)
9418 ;; Check if the user wrote this message
9419 (if (and org-from-is-user-regexp from to
9420 (save-match-data (string-match org-from-is-user-regexp from)))
9421 (setq fmt (replace-match "to %t" t t fmt))
9422 (setq fmt (replace-match "from %f" t t fmt))))
9423 (org-replace-escapes fmt table)))
9425 (defun org-make-org-heading-search-string (&optional string)
9426 "Make search string for the current headline or STRING."
9427 (let ((s (or string
9428 (and (derived-mode-p 'org-mode)
9429 (save-excursion
9430 (org-back-to-heading t)
9431 (org-element-property :raw-value (org-element-at-point))))))
9432 (lines org-context-in-file-links))
9433 (unless string (setq s (concat "*" s))) ;Add * for headlines
9434 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9435 (when (and string (integerp lines) (> lines 0))
9436 (let ((slines (org-split-string s "\n")))
9437 (when (< lines (length slines))
9438 (setq s (mapconcat
9439 'identity
9440 (reverse (nthcdr (- (length slines) lines)
9441 (reverse slines))) "\n")))))
9442 (mapconcat #'identity (split-string s) " ")))
9444 (defconst org-link-escape-chars
9445 ;;%20 %5B %5D %25
9446 '(?\s ?\[ ?\] ?%)
9447 "List of characters that should be escaped in a link when stored to Org.
9448 This is the list that is used for internal purposes.")
9450 (defun org-make-link-string (link &optional description)
9451 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9452 (unless (org-string-nw-p link) (error "Empty link"))
9453 (let ((uri (cond ((string-match org-link-types-re link)
9454 (concat (match-string 1 link)
9455 (org-link-escape (substring link (match-end 1)))))
9456 ((or (file-name-absolute-p link)
9457 (string-match-p "\\`\\.\\.?/" link))
9458 (org-link-escape link))
9459 ;; For readability, do not encode space characters
9460 ;; in fuzzy links.
9461 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9462 (description
9463 (and (org-string-nw-p description)
9464 ;; Remove brackets from description, as they are fatal.
9465 (replace-regexp-in-string
9466 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9467 (org-trim description)))))
9468 (format "[[%s]%s]"
9470 (if description (format "[%s]" description) ""))))
9472 (defun org-link-escape (text &optional table merge)
9473 "Return percent escaped representation of TEXT.
9474 TEXT is a string with the text to escape.
9475 Optional argument TABLE is a list with characters that should be
9476 escaped. When nil, `org-link-escape-chars' is used.
9477 If optional argument MERGE is set, merge TABLE into
9478 `org-link-escape-chars'."
9479 (let ((characters-to-encode
9480 (cond ((null table) org-link-escape-chars)
9481 (merge (append org-link-escape-chars table))
9482 (t table))))
9483 (mapconcat
9484 (lambda (c)
9485 (if (or (memq c characters-to-encode)
9486 (and org-url-hexify-p (or (< c 32) (> c 126))))
9487 (mapconcat (lambda (e) (format "%%%.2X" e))
9488 (or (encode-coding-char c 'utf-8)
9489 (error "Unable to percent escape character: %c" c))
9491 (char-to-string c)))
9492 text "")))
9494 (defun org-link-unescape (str)
9495 "Unhex hexified Unicode parts in string STR.
9496 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9497 reciprocal of `org-link-escape', which see."
9498 (if (org-string-nw-p str)
9499 (replace-regexp-in-string
9500 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9501 str))
9503 (defun org-link-unescape-compound (hex)
9504 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9505 Note: this function also decodes single byte encodings like
9506 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9507 (save-match-data
9508 (let* ((bytes (cdr (split-string hex "%")))
9509 (ret "")
9510 (eat 0)
9511 (sum 0))
9512 (while bytes
9513 (let* ((val (string-to-number (pop bytes) 16))
9514 (shift-xor
9515 (if (= 0 eat)
9516 (cond
9517 ((>= val 252) (cons 6 252))
9518 ((>= val 248) (cons 5 248))
9519 ((>= val 240) (cons 4 240))
9520 ((>= val 224) (cons 3 224))
9521 ((>= val 192) (cons 2 192))
9522 (t (cons 0 0)))
9523 (cons 6 128))))
9524 (when (>= val 192) (setq eat (car shift-xor)))
9525 (setq val (logxor val (cdr shift-xor)))
9526 (setq sum (+ (lsh sum (car shift-xor)) val))
9527 (when (> eat 0) (setq eat (- eat 1)))
9528 (cond
9529 ((= 0 eat) ;multi byte
9530 (setq ret (concat ret (char-to-string sum)))
9531 (setq sum 0))
9532 ((not bytes) ; single byte(s)
9533 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9534 ret)))
9536 (defun org-link-unescape-single-byte-sequence (hex)
9537 "Unhexify hex-encoded single byte character sequences."
9538 (mapconcat (lambda (byte)
9539 (char-to-string (string-to-number byte 16)))
9540 (cdr (split-string hex "%")) ""))
9542 (defun org-fixup-message-id-for-http (s)
9543 "Replace special characters in a message id, so it can be used in an http query."
9544 (when (string-match "%" s)
9545 (setq s (mapconcat (lambda (c)
9546 (if (eq c ?%)
9547 "%25"
9548 (char-to-string c)))
9549 s "")))
9550 (while (string-match "<" s)
9551 (setq s (replace-match "%3C" t t s)))
9552 (while (string-match ">" s)
9553 (setq s (replace-match "%3E" t t s)))
9554 (while (string-match "@" s)
9555 (setq s (replace-match "%40" t t s)))
9558 (defun org-link-prettify (link)
9559 "Return a human-readable representation of LINK.
9560 The car of LINK must be a raw link.
9561 The cdr of LINK must be either a link description or nil."
9562 (let ((desc (or (cadr link) "<no description>")))
9563 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9564 "<" (car link) ">")))
9566 ;;;###autoload
9567 (defun org-insert-link-global ()
9568 "Insert a link like Org mode does.
9569 This command can be called in any mode to insert a link in Org syntax."
9570 (interactive)
9571 (org-load-modules-maybe)
9572 (org-run-like-in-org-mode 'org-insert-link))
9574 (defun org-insert-all-links (arg &optional pre post)
9575 "Insert all links in `org-stored-links'.
9576 When a universal prefix, do not delete the links from `org-stored-links'.
9577 When `ARG' is a number, insert the last N link(s).
9578 `PRE' and `POST' are optional arguments to define a string to
9579 prepend or to append."
9580 (interactive "P")
9581 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9582 (links (copy-sequence org-stored-links))
9583 (pr (or pre "- "))
9584 (po (or post "\n"))
9585 (cnt 1) l)
9586 (if (null org-stored-links)
9587 (message "No link to insert")
9588 (while (and (or (listp arg) (>= arg cnt))
9589 (setq l (if (listp arg)
9590 (pop links)
9591 (pop org-stored-links))))
9592 (setq cnt (1+ cnt))
9593 (insert pr)
9594 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9595 (insert po)))))
9597 (defun org-insert-last-stored-link (arg)
9598 "Insert the last link stored in `org-stored-links'."
9599 (interactive "p")
9600 (org-insert-all-links arg "" "\n"))
9602 (defun org-link-fontify-links-to-this-file ()
9603 "Fontify links to the current file in `org-stored-links'."
9604 (let ((f (buffer-file-name)) a b)
9605 (setq a (mapcar (lambda(l)
9606 (let ((ll (car l)))
9607 (when (and (string-match "^file:\\(.+\\)::" ll)
9608 (equal f (expand-file-name (match-string 1 ll))))
9609 ll)))
9610 org-stored-links))
9611 (when (featurep 'org-id)
9612 (setq b (mapcar (lambda(l)
9613 (let ((ll (car l)))
9614 (when (and (string-match "^id:\\(.+\\)$" ll)
9615 (equal f (expand-file-name
9616 (or (org-id-find-id-file
9617 (match-string 1 ll)) ""))))
9618 ll)))
9619 org-stored-links)))
9620 (mapcar (lambda(l)
9621 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9622 (delq nil (append a b)))))
9624 (defvar org--links-history nil)
9625 (defun org-insert-link (&optional complete-file link-location default-description)
9626 "Insert a link. At the prompt, enter the link.
9628 Completion can be used to insert any of the link protocol prefixes in use.
9630 The history can be used to select a link previously stored with
9631 `org-store-link'. When the empty string is entered (i.e. if you just
9632 press `RET' at the prompt), the link defaults to the most recently
9633 stored link. As `SPC' triggers completion in the minibuffer, you need to
9634 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9636 You will also be prompted for a description, and if one is given, it will
9637 be displayed in the buffer instead of the link.
9639 If there is already a link at point, this command will allow you to edit
9640 link and description parts.
9642 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9643 file name can be
9644 selected using completion. The path to the file will be relative to the
9645 current directory if the file is in the current directory or a subdirectory.
9646 Otherwise, the link will be the absolute path as completed in the minibuffer
9647 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9648 option `org-link-file-path-type'.
9650 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9651 absolute path even if the file is in
9652 the current directory or below.
9654 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9655 prefix negates `org-keep-stored-link-after-insertion'.
9657 If the LINK-LOCATION parameter is non-nil, this value will be used as
9658 the link location instead of reading one interactively.
9660 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9661 be used as the default description. Otherwise, if
9662 `org-make-link-description-function' is non-nil, this function
9663 will be called with the link target, and the result will be the
9664 default link description. When called non-interactivily, don't
9665 allow to edit the default description."
9666 (interactive "P")
9667 (let* ((wcf (current-window-configuration))
9668 (origbuf (current-buffer))
9669 (region (when (org-region-active-p)
9670 (buffer-substring (region-beginning) (region-end))))
9671 (remove (and region (list (region-beginning) (region-end))))
9672 (desc region)
9673 (link link-location)
9674 (abbrevs org-link-abbrev-alist-local)
9675 entry all-prefixes auto-desc)
9676 (cond
9677 (link-location) ; specified by arg, just use it.
9678 ((org-in-regexp org-bracket-link-regexp 1)
9679 ;; We do have a link at point, and we are going to edit it.
9680 (setq remove (list (match-beginning 0) (match-end 0)))
9681 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9682 (setq link (read-string "Link: "
9683 (org-link-unescape
9684 (match-string-no-properties 1)))))
9685 ((or (org-in-regexp org-angle-link-re)
9686 (org-in-regexp org-plain-link-re))
9687 ;; Convert to bracket link
9688 (setq remove (list (match-beginning 0) (match-end 0))
9689 link (read-string "Link: "
9690 (org-unbracket-string "<" ">" (match-string 0)))))
9691 ((member complete-file '((4) (16)))
9692 ;; Completing read for file names.
9693 (setq link (org-file-complete-link complete-file)))
9695 ;; Read link, with completion for stored links.
9696 (org-link-fontify-links-to-this-file)
9697 (org-switch-to-buffer-other-window "*Org Links*")
9698 (with-current-buffer "*Org Links*"
9699 (erase-buffer)
9700 (insert "Insert a link.
9701 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9702 (when org-stored-links
9703 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9704 (insert (mapconcat 'org-link-prettify
9705 (reverse org-stored-links) "\n")))
9706 (goto-char (point-min)))
9707 (let ((cw (selected-window)))
9708 (select-window (get-buffer-window "*Org Links*" 'visible))
9709 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9710 (unless (pos-visible-in-window-p (point-max))
9711 (org-fit-window-to-buffer))
9712 (and (window-live-p cw) (select-window cw)))
9713 (setq all-prefixes (append (mapcar 'car abbrevs)
9714 (mapcar 'car org-link-abbrev-alist)
9715 (org-link-types)))
9716 (unwind-protect
9717 ;; Fake a link history, containing the stored links.
9718 (let ((org--links-history
9719 (append (mapcar #'car org-stored-links)
9720 org-insert-link-history)))
9721 (setq link
9722 (org-completing-read
9723 "Link: "
9724 (append
9725 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9726 (mapcar #'car org-stored-links))
9727 nil nil nil
9728 'org--links-history
9729 (caar org-stored-links)))
9730 (unless (org-string-nw-p link) (user-error "No link selected"))
9731 (dolist (l org-stored-links)
9732 (when (equal link (cadr l))
9733 (setq link (car l))
9734 (setq auto-desc t)))
9735 (when (or (member link all-prefixes)
9736 (and (equal ":" (substring link -1))
9737 (member (substring link 0 -1) all-prefixes)
9738 (setq link (substring link 0 -1))))
9739 (setq link (with-current-buffer origbuf
9740 (org-link-try-special-completion link)))))
9741 (set-window-configuration wcf)
9742 (kill-buffer "*Org Links*"))
9743 (setq entry (assoc link org-stored-links))
9744 (or entry (push link org-insert-link-history))
9745 (setq desc (or desc (nth 1 entry)))))
9747 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9748 (not org-keep-stored-link-after-insertion))
9749 (setq org-stored-links (delq (assoc link org-stored-links)
9750 org-stored-links)))
9752 (when (and (string-match org-plain-link-re link)
9753 (not (string-match org-ts-regexp link)))
9754 ;; URL-like link, normalize the use of angular brackets.
9755 (setq link (org-unbracket-string "<" ">" link)))
9757 ;; Check if we are linking to the current file with a search
9758 ;; option If yes, simplify the link by using only the search
9759 ;; option.
9760 (when (and buffer-file-name
9761 (let ((case-fold-search nil))
9762 (string-match "\\`file:\\(.+?\\)::" link)))
9763 (let ((path (match-string-no-properties 1 link))
9764 (search (substring-no-properties link (match-end 0))))
9765 (save-match-data
9766 (when (equal (file-truename buffer-file-name) (file-truename path))
9767 ;; We are linking to this same file, with a search option
9768 (setq link search)))))
9770 ;; Check if we can/should use a relative path. If yes, simplify
9771 ;; the link.
9772 (let ((case-fold-search nil))
9773 (when (string-match "\\`\\(file\\|docview\\):" link)
9774 (let* ((type (match-string-no-properties 0 link))
9775 (path-start (match-end 0))
9776 (search (and (string-match "::\\(.*\\)\\'" link)
9777 (match-string 1 link)))
9778 (path
9779 (if search
9780 (substring-no-properties
9781 link path-start (match-beginning 0))
9782 (substring-no-properties link (match-end 0))))
9783 (origpath path))
9784 (cond
9785 ((or (eq org-link-file-path-type 'absolute)
9786 (equal complete-file '(16)))
9787 (setq path (abbreviate-file-name (expand-file-name path))))
9788 ((eq org-link-file-path-type 'noabbrev)
9789 (setq path (expand-file-name path)))
9790 ((eq org-link-file-path-type 'relative)
9791 (setq path (file-relative-name path)))
9793 (save-match-data
9794 (if (string-match (concat "^" (regexp-quote
9795 (expand-file-name
9796 (file-name-as-directory
9797 default-directory))))
9798 (expand-file-name path))
9799 ;; We are linking a file with relative path name.
9800 (setq path (substring (expand-file-name path)
9801 (match-end 0)))
9802 (setq path (abbreviate-file-name (expand-file-name path)))))))
9803 (setq link (concat type path (and search (concat "::" search))))
9804 (when (equal desc origpath)
9805 (setq desc path)))))
9807 (unless auto-desc
9808 (let ((initial-input
9809 (cond
9810 (default-description)
9811 ((not org-make-link-description-function) desc)
9812 (t (condition-case nil
9813 (funcall org-make-link-description-function link desc)
9814 (error
9815 (message "Can't get link description from `%s'"
9816 (symbol-name org-make-link-description-function))
9817 (sit-for 2)
9818 nil))))))
9819 (setq desc (if (called-interactively-p 'any)
9820 (read-string "Description: " initial-input)
9821 initial-input))))
9823 (unless (string-match "\\S-" desc) (setq desc nil))
9824 (when remove (apply 'delete-region remove))
9825 (insert (org-make-link-string link desc))
9826 ;; Redisplay so as the new link has proper invisible characters.
9827 (sit-for 0)))
9829 (defun org-link-try-special-completion (type)
9830 "If there is completion support for link type TYPE, offer it."
9831 (let ((fun (org-link-get-parameter type :complete)))
9832 (if (functionp fun)
9833 (funcall fun)
9834 (read-string "Link (no completion support): " (concat type ":")))))
9836 (defun org-file-complete-link (&optional arg)
9837 "Create a file link using completion."
9838 (let ((file (read-file-name "File: "))
9839 (pwd (file-name-as-directory (expand-file-name ".")))
9840 (pwd1 (file-name-as-directory (abbreviate-file-name
9841 (expand-file-name ".")))))
9842 (cond ((equal arg '(16))
9843 (concat "file:"
9844 (abbreviate-file-name (expand-file-name file))))
9845 ((string-match
9846 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9847 (concat "file:" (match-string 1 file)))
9848 ((string-match
9849 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9850 (expand-file-name file))
9851 (concat "file:"
9852 (match-string 1 (expand-file-name file))))
9853 (t (concat "file:" file)))))
9856 ;;; Opening/following a link
9858 (defvar org-link-search-failed nil)
9860 (defvar org-open-link-functions nil
9861 "Hook for functions finding a plain text link.
9862 These functions must take a single argument, the link content.
9863 They will be called for links that look like [[link text][description]]
9864 when LINK TEXT does not have a protocol like \"http:\" and does not look
9865 like a filename (e.g. \"./blue.png\").
9867 These functions will be called *before* Org attempts to resolve the
9868 link by doing text searches in the current buffer - so if you want a
9869 link \"[[target]]\" to still find \"<<target>>\", your function should
9870 handle this as a special case.
9872 When the function does handle the link, it must return a non-nil value.
9873 If it decides that it is not responsible for this link, it must return
9874 nil to indicate that that Org can continue with other options like
9875 exact and fuzzy text search.")
9877 (defun org-next-link (&optional search-backward)
9878 "Move forward to the next link.
9879 If the link is in hidden text, expose it."
9880 (interactive "P")
9881 (when (and org-link-search-failed (eq this-command last-command))
9882 (goto-char (point-min))
9883 (message "Link search wrapped back to beginning of buffer"))
9884 (setq org-link-search-failed nil)
9885 (let* ((pos (point))
9886 (ct (org-context))
9887 (a (assq :link ct))
9888 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9889 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9890 ((looking-at org-any-link-re)
9891 ;; Don't stay stuck at link without an org-link face
9892 (forward-char (if search-backward -1 1))))
9893 (if (funcall srch-fun org-any-link-re nil t)
9894 (progn
9895 (goto-char (match-beginning 0))
9896 (when (org-invisible-p) (org-show-context)))
9897 (goto-char pos)
9898 (setq org-link-search-failed t)
9899 (message "No further link found"))))
9901 (defun org-previous-link ()
9902 "Move backward to the previous link.
9903 If the link is in hidden text, expose it."
9904 (interactive)
9905 (funcall 'org-next-link t))
9907 (defun org-translate-link (s)
9908 "Translate a link string if a translation function has been defined."
9909 (with-temp-buffer
9910 (insert (org-trim s))
9911 (org-trim (org-element-interpret-data (org-element-context)))))
9913 (defun org-translate-link-from-planner (type path)
9914 "Translate a link from Emacs Planner syntax so that Org can follow it.
9915 This is still an experimental function, your mileage may vary."
9916 (cond
9917 ((member type '("http" "https" "news" "ftp"))
9918 ;; standard Internet links are the same.
9919 nil)
9920 ((and (equal type "irc") (string-match "^//" path))
9921 ;; Planner has two / at the beginning of an irc link, we have 1.
9922 ;; We should have zero, actually....
9923 (setq path (substring path 1)))
9924 ((and (equal type "lisp") (string-match "^/" path))
9925 ;; Planner has a slash, we do not.
9926 (setq type "elisp" path (substring path 1)))
9927 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9928 ;; A typical message link. Planner has the id after the final slash,
9929 ;; we separate it with a hash mark
9930 (setq path (concat (match-string 1 path) "#"
9931 (org-unbracket-string "<" ">" (match-string 2 path))))))
9932 (cons type path))
9934 (defun org-find-file-at-mouse (ev)
9935 "Open file link or URL at mouse."
9936 (interactive "e")
9937 (mouse-set-point ev)
9938 (org-open-at-point 'in-emacs))
9940 (defun org-open-at-mouse (ev)
9941 "Open file link or URL at mouse.
9942 See the docstring of `org-open-file' for details."
9943 (interactive "e")
9944 (mouse-set-point ev)
9945 (when (eq major-mode 'org-agenda-mode)
9946 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9947 (org-open-at-point))
9949 (defvar org-window-config-before-follow-link nil
9950 "The window configuration before following a link.
9951 This is saved in case the need arises to restore it.")
9953 ;;;###autoload
9954 (defun org-open-at-point-global ()
9955 "Follow a link or time-stamp like Org mode does.
9956 This command can be called in any mode to follow an external link
9957 or a time-stamp that has Org mode syntax. Its behavior is
9958 undefined when called on internal links (e.g., fuzzy links).
9959 Raise an error when there is nothing to follow. "
9960 (interactive)
9961 (cond ((org-in-regexp org-any-link-re)
9962 (org-open-link-from-string (match-string-no-properties 0)))
9963 ((or (org-in-regexp org-ts-regexp-both nil t)
9964 (org-in-regexp org-tsr-regexp-both nil t))
9965 (org-follow-timestamp-link))
9966 (t (user-error "No link found"))))
9968 ;;;###autoload
9969 (defun org-open-link-from-string (s &optional arg reference-buffer)
9970 "Open a link in the string S, as if it was in Org mode."
9971 (interactive "sLink: \nP")
9972 (let ((reference-buffer (or reference-buffer (current-buffer))))
9973 (with-temp-buffer
9974 (let ((org-inhibit-startup (not reference-buffer)))
9975 (org-mode)
9976 (insert s)
9977 (goto-char (point-min))
9978 (when reference-buffer
9979 (setq org-link-abbrev-alist-local
9980 (with-current-buffer reference-buffer
9981 org-link-abbrev-alist-local)))
9982 (org-open-at-point arg reference-buffer)))))
9984 (defvar org-open-at-point-functions nil
9985 "Hook that is run when following a link at point.
9987 Functions in this hook must return t if they identify and follow
9988 a link at point. If they don't find anything interesting at point,
9989 they must return nil.")
9991 (defvar org-link-search-inhibit-query nil)
9992 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9993 (defun org--open-doi-link (path)
9994 "Open a \"doi\" type link.
9995 PATH is a the path to search for, as a string."
9996 (browse-url (url-encode-url (concat org-doi-server-url path))))
9998 (defun org--open-elisp-link (path)
9999 "Open a \"elisp\" type link.
10000 PATH is the sexp to evaluate, as a string."
10001 (let ((cmd path))
10002 (if (or (and (org-string-nw-p
10003 org-confirm-elisp-link-not-regexp)
10004 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10005 (not org-confirm-elisp-link-function)
10006 (funcall org-confirm-elisp-link-function
10007 (format "Execute \"%s\" as elisp? "
10008 (org-add-props cmd nil 'face 'org-warning))))
10009 (message "%s => %s" cmd
10010 (if (eq (string-to-char cmd) ?\()
10011 (eval (read cmd))
10012 (call-interactively (read cmd))))
10013 (user-error "Abort"))))
10015 (defun org--open-help-link (path)
10016 "Open a \"help\" type link.
10017 PATH is a symbol name, as a string."
10018 (pcase (intern path)
10019 ((and (pred fboundp) variable) (describe-function variable))
10020 ((and (pred boundp) function) (describe-variable function))
10021 (name (user-error "Unknown function or variable: %s" name))))
10023 (defun org--open-shell-link (path)
10024 "Open a \"shell\" type link.
10025 PATH is the command to execute, as a string."
10026 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10027 (cmd path))
10028 (if (or (and (org-string-nw-p
10029 org-confirm-shell-link-not-regexp)
10030 (string-match
10031 org-confirm-shell-link-not-regexp cmd))
10032 (not org-confirm-shell-link-function)
10033 (funcall org-confirm-shell-link-function
10034 (format "Execute \"%s\" in shell? "
10035 (org-add-props cmd nil
10036 'face 'org-warning))))
10037 (progn
10038 (message "Executing %s" cmd)
10039 (shell-command cmd buf)
10040 (when (featurep 'midnight)
10041 (setq clean-buffer-list-kill-buffer-names
10042 (cons (buffer-name buf)
10043 clean-buffer-list-kill-buffer-names))))
10044 (user-error "Abort"))))
10046 (defun org-open-at-point (&optional arg reference-buffer)
10047 "Open link, timestamp, footnote or tags at point.
10049 When point is on a link, follow it. Normally, files will be
10050 opened by an appropriate application. If the optional prefix
10051 argument ARG is non-nil, Emacs will visit the file. With
10052 a double prefix argument, try to open outside of Emacs, in the
10053 application the system uses for this file type.
10055 When point is on a timestamp, open the agenda at the day
10056 specified.
10058 When point is a footnote definition, move to the first reference
10059 found. If it is on a reference, move to the associated
10060 definition.
10062 When point is on a headline, display a list of every link in the
10063 entry, so it is possible to pick one, or all, of them. If point
10064 is on a tag, call `org-tags-view' instead.
10066 When optional argument REFERENCE-BUFFER is non-nil, it should
10067 specify a buffer from where the link search should happen. This
10068 is used internally by `org-open-link-from-string'.
10070 On top of syntactically correct links, this function will also
10071 try to open links and time-stamps in comments, example
10072 blocks... i.e., whenever point is on something looking like
10073 a timestamp or a link."
10074 (interactive "P")
10075 ;; On a code block, open block's results.
10076 (unless (call-interactively 'org-babel-open-src-block-result)
10077 (org-load-modules-maybe)
10078 (setq org-window-config-before-follow-link (current-window-configuration))
10079 (org-remove-occur-highlights nil nil t)
10080 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10081 (let* ((context
10082 ;; Only consider supported types, even if they are not
10083 ;; the closest one.
10084 (org-element-lineage
10085 (org-element-context)
10086 '(clock footnote-definition footnote-reference headline
10087 inlinetask link timestamp)
10089 (type (org-element-type context))
10090 (value (org-element-property :value context)))
10091 (cond
10092 ;; On a headline or an inlinetask, but not on a timestamp,
10093 ;; a link, a footnote reference.
10094 ((memq type '(headline inlinetask))
10095 (org-match-line org-complex-heading-regexp)
10096 (if (and (match-beginning 5)
10097 (>= (point) (match-beginning 5))
10098 (< (point) (match-end 5)))
10099 ;; On tags.
10100 (org-tags-view arg (substring (match-string 5) 0 -1))
10101 ;; Not on tags.
10102 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10103 (`(nil . ,_)
10104 (require 'org-attach)
10105 (org-attach-reveal 'if-exists))
10106 (`(,links . ,links-end)
10107 (dolist (link (if (stringp links) (list links) links))
10108 (search-forward link nil links-end)
10109 (goto-char (match-beginning 0))
10110 (org-open-at-point))))))
10111 ;; On a footnote reference or at definition's label.
10112 ((or (eq type 'footnote-reference)
10113 (and (eq type 'footnote-definition)
10114 (save-excursion
10115 ;; Do not validate action when point is on the
10116 ;; spaces right after the footnote label, in
10117 ;; order to be on par with behavior on links.
10118 (skip-chars-forward " \t")
10119 (let ((begin
10120 (org-element-property :contents-begin context)))
10121 (if begin (< (point) begin)
10122 (= (org-element-property :post-affiliated context)
10123 (line-beginning-position)))))))
10124 (org-footnote-action))
10125 ;; No valid context. Ignore catch-all types like `headline'.
10126 ;; If point is on something looking like a link or
10127 ;; a time-stamp, try opening it. It may be useful in
10128 ;; comments, example blocks...
10129 ((memq type '(footnote-definition headline inlinetask nil))
10130 (call-interactively #'org-open-at-point-global))
10131 ;; On a clock line, make sure point is on the timestamp
10132 ;; before opening it.
10133 ((and (eq type 'clock)
10134 value
10135 (>= (point) (org-element-property :begin value))
10136 (<= (point) (org-element-property :end value)))
10137 (org-follow-timestamp-link))
10138 ;; Do nothing on white spaces after an object.
10139 ((>= (point)
10140 (save-excursion
10141 (goto-char (org-element-property :end context))
10142 (skip-chars-backward " \t")
10143 (point)))
10144 (user-error "No link found"))
10145 ((eq type 'timestamp) (org-follow-timestamp-link))
10146 ((eq type 'link)
10147 (let ((type (org-element-property :type context))
10148 (path (org-link-unescape (org-element-property :path context))))
10149 ;; Switch back to REFERENCE-BUFFER needed when called in
10150 ;; a temporary buffer through `org-open-link-from-string'.
10151 (with-current-buffer (or reference-buffer (current-buffer))
10152 (cond
10153 ((equal type "file")
10154 (if (string-match "[*?{]" (file-name-nondirectory path))
10155 (dired path)
10156 ;; Look into `org-link-parameters' in order to find
10157 ;; a DEDICATED-FUNCTION to open file. The function
10158 ;; will be applied on raw link instead of parsed
10159 ;; link due to the limitation in `org-add-link-type'
10160 ;; ("open" function called with a single argument).
10161 ;; If no such function is found, fallback to
10162 ;; `org-open-file'.
10163 (let* ((option (org-element-property :search-option context))
10164 (app (org-element-property :application context))
10165 (dedicated-function
10166 (org-link-get-parameter
10167 (if app (concat type "+" app) type)
10168 :follow)))
10169 (if dedicated-function
10170 (funcall dedicated-function
10171 (concat path
10172 (and option (concat "::" option))))
10173 (apply #'org-open-file
10174 path
10175 (cond (arg)
10176 ((equal app "emacs") 'emacs)
10177 ((equal app "sys") 'system))
10178 (cond ((not option) nil)
10179 ((string-match-p "\\`[0-9]+\\'" option)
10180 (list (string-to-number option)))
10181 (t (list nil
10182 (org-link-unescape option)))))))))
10183 ((functionp (org-link-get-parameter type :follow))
10184 (funcall (org-link-get-parameter type :follow) path))
10185 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10186 (unless (run-hook-with-args-until-success
10187 'org-open-link-functions path)
10188 (if (not arg) (org-mark-ring-push)
10189 (switch-to-buffer-other-window
10190 (org-get-buffer-for-internal-link (current-buffer))))
10191 (let ((destination
10192 (org-with-wide-buffer
10193 (if (equal type "radio")
10194 (org-search-radio-target
10195 (org-element-property :path context))
10196 (org-link-search
10197 (if (member type '("custom-id" "coderef"))
10198 (org-element-property :raw-link context)
10199 path)
10200 ;; Prevent fuzzy links from matching
10201 ;; themselves.
10202 (and (equal type "fuzzy")
10203 (+ 2 (org-element-property :begin context)))))
10204 (point))))
10205 (unless (and (<= (point-min) destination)
10206 (>= (point-max) destination))
10207 (widen))
10208 (goto-char destination))))
10209 (t (browse-url-at-point))))))
10210 (t (user-error "No link found")))))
10211 (run-hook-with-args 'org-follow-link-hook)))
10213 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10214 "Offer links in the current entry and return the selected link.
10215 If there is only one link, return it.
10216 If NTH is an integer, return the NTH link found.
10217 If ZERO is a string, check also this string for a link, and if
10218 there is one, return it."
10219 (with-current-buffer buffer
10220 (org-with-wide-buffer
10221 (goto-char marker)
10222 (let ((cnt ?0)
10223 have-zero end links link c)
10224 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10225 (push (match-string 0 zero) links)
10226 (setq cnt (1- cnt) have-zero t))
10227 (save-excursion
10228 (org-back-to-heading t)
10229 (setq end (save-excursion (outline-next-heading) (point)))
10230 (while (re-search-forward org-any-link-re end t)
10231 (push (match-string 0) links))
10232 (setq links (org-uniquify (reverse links))))
10233 (cond
10234 ((null links)
10235 (message "No links"))
10236 ((equal (length links) 1)
10237 (setq link (car links)))
10238 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10239 (setq link (nth (if have-zero nth (1- nth)) links)))
10240 (t ; we have to select a link
10241 (save-excursion
10242 (save-window-excursion
10243 (delete-other-windows)
10244 (with-output-to-temp-buffer "*Select Link*"
10245 (dolist (l links)
10246 (cond
10247 ((not (string-match org-bracket-link-regexp l))
10248 (princ (format "[%c] %s\n" (cl-incf cnt)
10249 (org-unbracket-string "<" ">" l))))
10250 ((match-end 3)
10251 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10252 (match-string 3 l) (match-string 1 l))))
10253 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10254 (match-string 1 l)))))))
10255 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10256 (message "Select link to open, RET to open all:")
10257 (setq c (read-char-exclusive))
10258 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10259 (when (equal c ?q) (user-error "Abort"))
10260 (if (equal c ?\C-m)
10261 (setq link links)
10262 (setq nth (- c ?0))
10263 (when have-zero (setq nth (1+ nth)))
10264 (unless (and (integerp nth) (>= (length links) nth))
10265 (user-error "Invalid link selection"))
10266 (setq link (nth (1- nth) links)))))
10267 (cons link end)))))
10269 ;; TODO: These functions are deprecated since `org-open-at-point'
10270 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10271 (defun org-open-file-with-system (path)
10272 "Open file at PATH using the system way of opening it."
10273 (org-open-file path 'system))
10274 (defun org-open-file-with-emacs (path)
10275 "Open file at PATH in Emacs."
10276 (org-open-file path 'emacs))
10279 ;;; File search
10281 (defvar org-create-file-search-functions nil
10282 "List of functions to construct the right search string for a file link.
10283 These functions are called in turn with point at the location to
10284 which the link should point.
10286 A function in the hook should first test if it would like to
10287 handle this file type, for example by checking the `major-mode'
10288 or the file extension. If it decides not to handle this file, it
10289 should just return nil to give other functions a chance. If it
10290 does handle the file, it must return the search string to be used
10291 when following the link. The search string will be part of the
10292 file link, given after a double colon, and `org-open-at-point'
10293 will automatically search for it. If special measures must be
10294 taken to make the search successful, another function should be
10295 added to the companion hook `org-execute-file-search-functions',
10296 which see.
10298 A function in this hook may also use `setq' to set the variable
10299 `description' to provide a suggestion for the descriptive text to
10300 be used for this link when it gets inserted into an Org buffer
10301 with \\[org-insert-link].")
10303 (defvar org-execute-file-search-functions nil
10304 "List of functions to execute a file search triggered by a link.
10306 Functions added to this hook must accept a single argument, the
10307 search string that was part of the file link, the part after the
10308 double colon. The function must first check if it would like to
10309 handle this search, for example by checking the `major-mode' or
10310 the file extension. If it decides not to handle this search, it
10311 should just return nil to give other functions a chance. If it
10312 does handle the search, it must return a non-nil value to keep
10313 other functions from trying.
10315 Each function can access the current prefix argument through the
10316 variable `current-prefix-arg'. Note that a single prefix is used
10317 to force opening a link in Emacs, so it may be good to only use a
10318 numeric or double prefix to guide the search function.
10320 In case this is needed, a function in this hook can also restore
10321 the window configuration before `org-open-at-point' was called using:
10323 (set-window-configuration org-window-config-before-follow-link)")
10325 (defun org-search-radio-target (target)
10326 "Search a radio target matching TARGET in current buffer.
10327 White spaces are not significant."
10328 (let ((re (format "<<<%s>>>"
10329 (mapconcat #'regexp-quote
10330 (split-string target)
10331 "[ \t]+\\(?:\n[ \t]*\\)?")))
10332 (origin (point)))
10333 (goto-char (point-min))
10334 (catch :radio-match
10335 (while (re-search-forward re nil t)
10336 (backward-char)
10337 (let ((object (org-element-context)))
10338 (when (eq (org-element-type object) 'radio-target)
10339 (goto-char (org-element-property :begin object))
10340 (org-show-context 'link-search)
10341 (throw :radio-match nil))))
10342 (goto-char origin)
10343 (user-error "No match for radio target: %s" target))))
10345 (defun org-link-search (s &optional avoid-pos stealth)
10346 "Search for a search string S.
10348 If S starts with \"#\", it triggers a custom ID search.
10350 If S is enclosed within parenthesis, it initiates a coderef
10351 search.
10353 If S is surrounded by forward slashes, it is interpreted as
10354 a regular expression. In Org mode files, this will create an
10355 `org-occur' sparse tree. In ordinary files, `occur' will be used
10356 to list matches. If the current buffer is in `dired-mode', grep
10357 will be used to search in all files.
10359 When AVOID-POS is given, ignore matches near that position.
10361 When optional argument STEALTH is non-nil, do not modify
10362 visibility around point, thus ignoring `org-show-context-detail'
10363 variable.
10365 Search is case-insensitive and ignores white spaces. Return type
10366 of matched result, which is either `dedicated' or `fuzzy'."
10367 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10368 (let* ((case-fold-search t)
10369 (origin (point))
10370 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10371 (starred (eq (string-to-char normalized) ?*))
10372 (words (split-string (if starred (substring s 1) s)))
10373 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10374 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10375 type)
10376 (cond
10377 ;; Check if there are any special search functions.
10378 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10379 ((eq (string-to-char s) ?#)
10380 ;; Look for a custom ID S if S starts with "#".
10381 (let* ((id (substring normalized 1))
10382 (match (org-find-property "CUSTOM_ID" id)))
10383 (if match (progn (goto-char match) (setf type 'dedicated))
10384 (error "No match for custom ID: %s" id))))
10385 ((string-match "\\`(\\(.*\\))\\'" normalized)
10386 ;; Look for coderef targets if S is enclosed within parenthesis.
10387 (let ((coderef (match-string-no-properties 1 normalized))
10388 (re (substring s-single-re 1 -1)))
10389 (goto-char (point-min))
10390 (catch :coderef-match
10391 (while (re-search-forward re nil t)
10392 (let ((element (org-element-at-point)))
10393 (when (and (memq (org-element-type element)
10394 '(example-block src-block))
10395 ;; Build proper regexp according to current
10396 ;; block's label format.
10397 (let ((label-fmt
10398 (regexp-quote
10399 (or (org-element-property :label-fmt element)
10400 org-coderef-label-format))))
10401 (save-excursion
10402 (beginning-of-line)
10403 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10404 (format label-fmt coderef))))))
10405 (setq type 'dedicated)
10406 (goto-char (match-beginning 1))
10407 (throw :coderef-match nil))))
10408 (goto-char origin)
10409 (error "No match for coderef: %s" coderef))))
10410 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10411 ;; Look for a regular expression.
10412 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10413 (match-string 1 s)))
10414 ;; From here, we handle fuzzy links.
10416 ;; Look for targets, only if not in a headline search.
10417 ((and (not starred)
10418 (let ((target (format "<<%s>>" s-multi-re)))
10419 (catch :target-match
10420 (goto-char (point-min))
10421 (while (re-search-forward target nil t)
10422 (backward-char)
10423 (let ((context (org-element-context)))
10424 (when (eq (org-element-type context) 'target)
10425 (setq type 'dedicated)
10426 (goto-char (org-element-property :begin context))
10427 (throw :target-match t))))
10428 nil))))
10429 ;; Look for elements named after S, only if not in a headline
10430 ;; search.
10431 ((and (not starred)
10432 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10433 (catch :name-match
10434 (goto-char (point-min))
10435 (while (re-search-forward name nil t)
10436 (let ((element (org-element-at-point)))
10437 (when (equal words
10438 (split-string
10439 (org-element-property :name element)))
10440 (setq type 'dedicated)
10441 (beginning-of-line)
10442 (throw :name-match t))))
10443 nil))))
10444 ;; Regular text search. Prefer headlines in Org mode buffers.
10445 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10446 ;; statistics cookies and tags.
10447 ((and (derived-mode-p 'org-mode)
10448 (let ((title-re
10449 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10450 org-outline-regexp-bol
10451 org-comment-string
10452 (mapconcat #'regexp-quote words ".+")))
10453 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10454 (comment-re (eval-when-compile
10455 (format "\\`%s[ \t]+" org-comment-string))))
10456 (goto-char (point-min))
10457 (catch :found
10458 (while (re-search-forward title-re nil t)
10459 (when (equal words
10460 (split-string
10461 (replace-regexp-in-string
10462 cookie-re ""
10463 (replace-regexp-in-string
10464 comment-re "" (org-get-heading t t t)))))
10465 (throw :found t)))
10466 nil)))
10467 (beginning-of-line)
10468 (setq type 'dedicated))
10469 ;; Offer to create non-existent headline depending on
10470 ;; `org-link-search-must-match-exact-headline'.
10471 ((and (derived-mode-p 'org-mode)
10472 (not org-link-search-inhibit-query)
10473 (eq org-link-search-must-match-exact-headline 'query-to-create)
10474 (yes-or-no-p "No match - create this as a new heading? "))
10475 (goto-char (point-max))
10476 (unless (bolp) (newline))
10477 (org-insert-heading nil t t)
10478 (insert s "\n")
10479 (beginning-of-line 0))
10480 ;; Only headlines are looked after. No need to process
10481 ;; further: throw an error.
10482 ((and (derived-mode-p 'org-mode)
10483 (or starred org-link-search-must-match-exact-headline))
10484 (goto-char origin)
10485 (error "No match for fuzzy expression: %s" normalized))
10486 ;; Regular text search.
10487 ((catch :fuzzy-match
10488 (goto-char (point-min))
10489 (while (re-search-forward s-multi-re nil t)
10490 ;; Skip match if it contains AVOID-POS or it is included in
10491 ;; a link with a description but outside the description.
10492 (unless (or (and avoid-pos
10493 (<= (match-beginning 0) avoid-pos)
10494 (> (match-end 0) avoid-pos))
10495 (and (save-match-data
10496 (org-in-regexp org-bracket-link-regexp))
10497 (match-beginning 3)
10498 (or (> (match-beginning 3) (point))
10499 (<= (match-end 3) (point)))
10500 (org-element-lineage
10501 (save-match-data (org-element-context))
10502 '(link) t)))
10503 (goto-char (match-beginning 0))
10504 (setq type 'fuzzy)
10505 (throw :fuzzy-match t)))
10506 nil))
10507 ;; All failed. Throw an error.
10508 (t (goto-char origin)
10509 (error "No match for fuzzy expression: %s" normalized)))
10510 ;; Disclose surroundings of match, if appropriate.
10511 (when (and (derived-mode-p 'org-mode) (not stealth))
10512 (org-show-context 'link-search))
10513 type))
10515 (defun org-get-buffer-for-internal-link (buffer)
10516 "Return a buffer to be used for displaying the link target of internal links."
10517 (cond
10518 ((not org-display-internal-link-with-indirect-buffer)
10519 buffer)
10520 ((string-suffix-p "(Clone)" (buffer-name buffer))
10521 (message "Buffer is already a clone, not making another one")
10522 ;; we also do not modify visibility in this case
10523 buffer)
10524 (t ; make a new indirect buffer for displaying the link
10525 (let* ((bn (buffer-name buffer))
10526 (ibn (concat bn "(Clone)"))
10527 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10528 (with-current-buffer ib (org-overview))
10529 ib))))
10531 (defun org-do-occur (regexp &optional cleanup)
10532 "Call the Emacs command `occur'.
10533 If CLEANUP is non-nil, remove the printout of the regular expression
10534 in the *Occur* buffer. This is useful if the regex is long and not useful
10535 to read."
10536 (occur regexp)
10537 (when cleanup
10538 (let ((cwin (selected-window)) win beg end)
10539 (when (setq win (get-buffer-window "*Occur*"))
10540 (select-window win))
10541 (goto-char (point-min))
10542 (when (re-search-forward "match[a-z]+" nil t)
10543 (setq beg (match-end 0))
10544 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10545 (setq end (1- (match-beginning 0)))))
10546 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10547 (goto-char (point-min))
10548 (select-window cwin))))
10551 ;;; The Mark Ring
10553 (defvar org-mark-ring nil
10554 "Mark ring for positions before jumps in Org mode.")
10556 (defvar org-mark-ring-last-goto nil
10557 "Last position in the mark ring used to go back.")
10559 ;; Fill and close the ring
10560 (setq org-mark-ring nil)
10561 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10563 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10564 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10565 org-mark-ring)
10567 (defun org-mark-ring-push (&optional pos buffer)
10568 "Put the current position into the mark ring and rotate it.
10569 Also push position into the Emacs mark ring. If optional
10570 argument POS and BUFFER are not nil, mark this location instead."
10571 (interactive)
10572 (let ((pos (or pos (point)))
10573 (buffer (or buffer (current-buffer))))
10574 (with-current-buffer buffer
10575 (org-with-point-at pos (push-mark nil t)))
10576 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10577 (move-marker (car org-mark-ring) pos buffer))
10578 (message
10579 (substitute-command-keys
10580 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10582 (defun org-mark-ring-goto (&optional n)
10583 "Jump to the previous position in the mark ring.
10584 With prefix arg N, jump back that many stored positions. When
10585 called several times in succession, walk through the entire ring.
10586 Org mode commands jumping to a different position in the current file,
10587 or to another Org file, automatically push the old position onto the ring."
10588 (interactive "p")
10589 (let (p m)
10590 (if (eq last-command this-command)
10591 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10592 (setq p org-mark-ring))
10593 (setq org-mark-ring-last-goto p)
10594 (setq m (car p))
10595 (pop-to-buffer-same-window (marker-buffer m))
10596 (goto-char m)
10597 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10599 (defun org-add-angle-brackets (s)
10600 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10601 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10604 ;;; Following specific links
10606 (defvar org-agenda-buffer-tmp-name)
10607 (defvar org-agenda-start-on-weekday)
10608 (defun org-follow-timestamp-link ()
10609 "Open an agenda view for the time-stamp date/range at point."
10610 (cond
10611 ((org-at-date-range-p t)
10612 (let ((org-agenda-start-on-weekday)
10613 (t1 (match-string 1))
10614 (t2 (match-string 2)) tt1 tt2)
10615 (setq tt1 (time-to-days (org-time-string-to-time t1))
10616 tt2 (time-to-days (org-time-string-to-time t2)))
10617 (let ((org-agenda-buffer-tmp-name
10618 (format "*Org Agenda(a:%s)"
10619 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10620 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10621 ((org-at-timestamp-p 'lax)
10622 (let ((org-agenda-buffer-tmp-name
10623 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10624 (org-agenda-list nil (time-to-days (org-time-string-to-time
10625 (substring (match-string 1) 0 10)))
10626 1)))
10627 (t (error "This should not happen"))))
10630 ;;; Following file links
10631 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10632 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10633 (declare-function mailcap-mime-info
10634 "mailcap" (string &optional request no-decode))
10635 (defvar org-wait nil)
10636 (defun org-open-file (path &optional in-emacs line search)
10637 "Open the file at PATH.
10638 First, this expands any special file name abbreviations. Then the
10639 configuration variable `org-file-apps' is checked if it contains an
10640 entry for this file type, and if yes, the corresponding command is launched.
10642 If no application is found, Emacs simply visits the file.
10644 With optional prefix argument IN-EMACS, Emacs will visit the file.
10645 With a double \\[universal-argument] \\[universal-argument] \
10646 prefix arg, Org tries to avoid opening in Emacs
10647 and to use an external application to visit the file.
10649 Optional LINE specifies a line to go to, optional SEARCH a string
10650 to search for. If LINE or SEARCH is given, the file will be
10651 opened in Emacs, unless an entry from org-file-apps that makes
10652 use of groups in a regexp matches.
10654 If you want to change the way frames are used when following a
10655 link, please customize `org-link-frame-setup'.
10657 If the file does not exist, an error is thrown."
10658 (let* ((file (if (equal path "")
10659 buffer-file-name
10660 (substitute-in-file-name (expand-file-name path))))
10661 (file-apps (append org-file-apps (org-default-apps)))
10662 (apps (cl-remove-if
10663 'org-file-apps-entry-match-against-dlink-p file-apps))
10664 (apps-dlink (cl-remove-if-not
10665 'org-file-apps-entry-match-against-dlink-p file-apps))
10666 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10667 (dirp (unless remp (file-directory-p file)))
10668 (file (if (and dirp org-open-directory-means-index-dot-org)
10669 (concat (file-name-as-directory file) "index.org")
10670 file))
10671 (a-m-a-p (assq 'auto-mode apps))
10672 (dfile (downcase file))
10673 ;; Reconstruct the original link from the PATH, LINE and
10674 ;; SEARCH args.
10675 (link (cond (line (concat file "::" (number-to-string line)))
10676 (search (concat file "::" search))
10677 (t file)))
10678 (dlink (downcase link))
10679 (ext
10680 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10681 (match-string 1 dfile)))
10682 (save-position-maybe
10683 (let ((old-buffer (current-buffer))
10684 (old-pos (point))
10685 (old-mode major-mode))
10686 (lambda ()
10687 (and (derived-mode-p 'org-mode)
10688 (eq old-mode 'org-mode)
10689 (or (not (eq old-buffer (current-buffer)))
10690 (not (eq old-pos (point))))
10691 (org-mark-ring-push old-pos old-buffer)))))
10692 cmd link-match-data)
10693 (cond
10694 ((member in-emacs '((16) system))
10695 (setq cmd (cdr (assq 'system apps))))
10696 (in-emacs (setq cmd 'emacs))
10698 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10699 (and dirp (cdr (assq 'directory apps)))
10700 ;; First, try matching against apps-dlink if we
10701 ;; get a match here, store the match data for
10702 ;; later.
10703 (let ((match (assoc-default dlink apps-dlink
10704 'string-match)))
10705 (if match
10706 (progn (setq link-match-data (match-data))
10707 match)
10708 (progn (setq in-emacs (or in-emacs line search))
10709 nil))) ; if we have no match in apps-dlink,
10710 ; always open the file in emacs if line or search
10711 ; is given (for backwards compatibility)
10712 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10713 'string-match)
10714 (cdr (assoc ext apps))
10715 (cdr (assq t apps))))))
10716 (when (eq cmd 'system)
10717 (setq cmd (cdr (assq 'system apps))))
10718 (when (eq cmd 'default)
10719 (setq cmd (cdr (assoc t apps))))
10720 (when (eq cmd 'mailcap)
10721 (require 'mailcap)
10722 (mailcap-parse-mailcaps)
10723 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10724 (command (mailcap-mime-info mime-type)))
10725 (if (stringp command)
10726 (setq cmd command)
10727 (setq cmd 'emacs))))
10728 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10729 (not (file-exists-p file))
10730 (not org-open-non-existing-files))
10731 (user-error "No such file: %s" file))
10732 (cond
10733 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10734 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10735 (while (string-match "['\"]%s['\"]" cmd)
10736 (setq cmd (replace-match "%s" t t cmd)))
10737 (setq cmd (replace-regexp-in-string
10738 "%s"
10739 (shell-quote-argument (convert-standard-filename file))
10741 nil t))
10743 ;; Replace "%1", "%2" etc. in command with group matches from regex
10744 (save-match-data
10745 (let ((match-index 1)
10746 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10747 (set-match-data link-match-data)
10748 (while (<= match-index number-of-groups)
10749 (let ((regex (concat "%" (number-to-string match-index)))
10750 (replace-with (match-string match-index dlink)))
10751 (while (string-match regex cmd)
10752 (setq cmd (replace-match replace-with t t cmd))))
10753 (setq match-index (+ match-index 1)))))
10755 (save-window-excursion
10756 (message "Running %s...done" cmd)
10757 (start-process-shell-command cmd nil cmd)
10758 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10759 ((or (stringp cmd)
10760 (eq cmd 'emacs))
10761 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10762 (widen)
10763 (cond (line (org-goto-line line)
10764 (when (derived-mode-p 'org-mode) (org-reveal)))
10765 (search (condition-case err
10766 (org-link-search search)
10767 ;; Save position before error-ing out so user
10768 ;; can easily move back to the original buffer.
10769 (error (funcall save-position-maybe)
10770 (error (nth 1 err)))))))
10771 ((functionp cmd)
10772 (save-match-data
10773 (set-match-data link-match-data)
10774 (condition-case nil
10775 (funcall cmd file link)
10776 ;; FIXME: Remove this check when most default installations
10777 ;; of Emacs have at least Org 9.0.
10778 ((debug wrong-number-of-arguments wrong-type-argument
10779 invalid-function)
10780 (user-error "Please see Org News for version 9.0 about \
10781 `org-file-apps'--Lisp error: %S" cmd)))))
10782 ((consp cmd)
10783 ;; FIXME: Remove this check when most default installations of
10784 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10785 ;; fall back to `org-link-frame-setup' for an old usage of
10786 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10787 (user-error "Please see Org News for version 9.0 about \
10788 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10789 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10790 (funcall save-position-maybe)))
10792 (defun org-file-apps-entry-match-against-dlink-p (entry)
10793 "This function returns non-nil if `entry' uses a regular
10794 expression which should be matched against the whole link by
10795 org-open-file.
10797 It assumes that is the case when the entry uses a regular
10798 expression which has at least one grouping construct and the
10799 action is either a lisp form or a command string containing
10800 `%1', i.e. using at least one subexpression match as a
10801 parameter."
10802 (let ((selector (car entry))
10803 (action (cdr entry)))
10804 (if (stringp selector)
10805 (and (> (regexp-opt-depth selector) 0)
10806 (or (and (stringp action)
10807 (string-match "%[0-9]" action))
10808 (consp action)))
10809 nil)))
10811 (defun org-default-apps ()
10812 "Return the default applications for this operating system."
10813 (cond
10814 ((eq system-type 'darwin)
10815 org-file-apps-defaults-macosx)
10816 ((eq system-type 'windows-nt)
10817 org-file-apps-defaults-windowsnt)
10818 (t org-file-apps-defaults-gnu)))
10820 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10821 "Convert extensions to regular expressions in the cars of LIST.
10822 Also, weed out any non-string entries, because the return value is used
10823 only for regexp matching.
10824 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10825 point to the symbol `emacs', indicating that the file should
10826 be opened in Emacs."
10827 (append
10828 (delq nil
10829 (mapcar (lambda (x)
10830 (unless (not (stringp (car x)))
10831 (if (string-match "\\W" (car x))
10833 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10834 list))
10835 (when add-auto-mode
10836 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10838 (defvar ange-ftp-name-format)
10839 (defun org-file-remote-p (file)
10840 "Test whether FILE specifies a location on a remote system.
10841 Return non-nil if the location is indeed remote.
10843 For example, the filename \"/user@host:/foo\" specifies a location
10844 on the system \"/user@host:\"."
10845 (cond ((fboundp 'file-remote-p)
10846 (file-remote-p file))
10847 ((fboundp 'tramp-handle-file-remote-p)
10848 (tramp-handle-file-remote-p file))
10849 ((and (boundp 'ange-ftp-name-format)
10850 (string-match (car ange-ftp-name-format) file))
10851 t)))
10854 ;;;; Refiling
10856 (defun org-get-org-file ()
10857 "Read a filename, with default directory `org-directory'."
10858 (let ((default (or org-default-notes-file remember-data-file)))
10859 (read-file-name (format "File name [%s]: " default)
10860 (file-name-as-directory org-directory)
10861 default)))
10863 (defun org-notes-order-reversed-p ()
10864 "Check if the current file should receive notes in reversed order."
10865 (cond
10866 ((not org-reverse-note-order) nil)
10867 ((eq t org-reverse-note-order) t)
10868 ((not (listp org-reverse-note-order)) nil)
10869 (t (catch 'exit
10870 (dolist (entry org-reverse-note-order)
10871 (when (string-match (car entry) buffer-file-name)
10872 (throw 'exit (cdr entry))))))))
10874 (defvar org-refile-target-table nil
10875 "The list of refile targets, created by `org-refile'.")
10877 (defvar org-agenda-new-buffers nil
10878 "Buffers created to visit agenda files.")
10880 (defvar org-refile-cache nil
10881 "Cache for refile targets.")
10883 (defvar org-refile-markers nil
10884 "All the markers used for caching refile locations.")
10886 (defun org-refile-marker (pos)
10887 "Get a new refile marker, but only if caching is in use."
10888 (if (not org-refile-use-cache)
10890 (let ((m (make-marker)))
10891 (move-marker m pos)
10892 (push m org-refile-markers)
10893 m)))
10895 (defun org-refile-cache-clear ()
10896 "Clear the refile cache and disable all the markers."
10897 (dolist (m org-refile-markers) (move-marker m nil))
10898 (setq org-refile-markers nil)
10899 (setq org-refile-cache nil)
10900 (message "Refile cache has been cleared"))
10902 (defun org-refile-cache-check-set (set)
10903 "Check if all the markers in the cache still have live buffers."
10904 (let (marker)
10905 (catch 'exit
10906 (while (and set (setq marker (nth 3 (pop set))))
10907 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10908 (when (and marker (null (marker-buffer marker)))
10909 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10910 (sit-for 3)
10911 (throw 'exit nil)))
10912 t)))
10914 (defun org-refile-cache-put (set &rest identifiers)
10915 "Push the refile targets SET into the cache, under IDENTIFIERS."
10916 (let* ((key (sha1 (prin1-to-string identifiers)))
10917 (entry (assoc key org-refile-cache)))
10918 (if entry
10919 (setcdr entry set)
10920 (push (cons key set) org-refile-cache))))
10922 (defun org-refile-cache-get (&rest identifiers)
10923 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10924 (cond
10925 ((not org-refile-cache) nil)
10926 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10928 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10929 org-refile-cache))))
10930 (and set (org-refile-cache-check-set set) set)))))
10932 (defvar org-outline-path-cache nil
10933 "Alist between buffer positions and outline paths.
10934 It value is an alist (POSITION . PATH) where POSITION is the
10935 buffer position at the beginning of an entry and PATH is a list
10936 of strings describing the outline path for that entry, in reverse
10937 order.")
10939 (defun org-refile-get-targets (&optional default-buffer)
10940 "Produce a table with refile targets."
10941 (let ((case-fold-search nil)
10942 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10943 (entries (or org-refile-targets '((nil . (:level . 1)))))
10944 targets tgs files desc descre)
10945 (message "Getting targets...")
10946 (with-current-buffer (or default-buffer (current-buffer))
10947 (dolist (entry entries)
10948 (setq files (car entry) desc (cdr entry))
10949 (cond
10950 ((null files) (setq files (list (current-buffer))))
10951 ((eq files 'org-agenda-files)
10952 (setq files (org-agenda-files 'unrestricted)))
10953 ((and (symbolp files) (fboundp files))
10954 (setq files (funcall files)))
10955 ((and (symbolp files) (boundp files))
10956 (setq files (symbol-value files))))
10957 (when (stringp files) (setq files (list files)))
10958 (cond
10959 ((eq (car desc) :tag)
10960 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10961 ((eq (car desc) :todo)
10962 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10963 ((eq (car desc) :regexp)
10964 (setq descre (cdr desc)))
10965 ((eq (car desc) :level)
10966 (setq descre (concat "^\\*\\{" (number-to-string
10967 (if org-odd-levels-only
10968 (1- (* 2 (cdr desc)))
10969 (cdr desc)))
10970 "\\}[ \t]")))
10971 ((eq (car desc) :maxlevel)
10972 (setq descre (concat "^\\*\\{1," (number-to-string
10973 (if org-odd-levels-only
10974 (1- (* 2 (cdr desc)))
10975 (cdr desc)))
10976 "\\}[ \t]")))
10977 (t (error "Bad refiling target description %s" desc)))
10978 (dolist (f files)
10979 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10981 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10982 (progn
10983 (when (bufferp f)
10984 (setq f (buffer-file-name (buffer-base-buffer f))))
10985 (setq f (and f (expand-file-name f)))
10986 (when (eq org-refile-use-outline-path 'file)
10987 (push (list (file-name-nondirectory f) f nil nil) tgs))
10988 (when (eq org-refile-use-outline-path 'buffer-name)
10989 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10990 (when (eq org-refile-use-outline-path 'full-file-path)
10991 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10992 (org-with-wide-buffer
10993 (goto-char (point-min))
10994 (setq org-outline-path-cache nil)
10995 (while (re-search-forward descre nil t)
10996 (beginning-of-line)
10997 (let ((case-fold-search nil))
10998 (looking-at org-complex-heading-regexp))
10999 (let ((begin (point))
11000 (heading (match-string-no-properties 4)))
11001 (unless (or (and
11002 org-refile-target-verify-function
11003 (not
11004 (funcall org-refile-target-verify-function)))
11005 (not heading))
11006 (let ((re (format org-complex-heading-regexp-format
11007 (regexp-quote heading)))
11008 (target
11009 (if (not org-refile-use-outline-path) heading
11010 (mapconcat
11011 #'identity
11012 (append
11013 (pcase org-refile-use-outline-path
11014 (`file (list (file-name-nondirectory
11015 (buffer-file-name
11016 (buffer-base-buffer)))))
11017 (`full-file-path
11018 (list (buffer-file-name
11019 (buffer-base-buffer))))
11020 (`buffer-name
11021 (list (buffer-name
11022 (buffer-base-buffer))))
11023 (_ nil))
11024 (mapcar (lambda (s) (replace-regexp-in-string
11025 "/" "\\/" s nil t))
11026 (org-get-outline-path t t)))
11027 "/"))))
11028 (push (list target f re (org-refile-marker (point)))
11029 tgs)))
11030 (when (= (point) begin)
11031 ;; Verification function has not moved point.
11032 (end-of-line)))))))
11033 (when org-refile-use-cache
11034 (org-refile-cache-put tgs (buffer-file-name) descre))
11035 (setq targets (append tgs targets))))))
11036 (message "Getting targets...done")
11037 (delete-dups (nreverse targets))))
11039 (defun org--get-outline-path-1 (&optional use-cache)
11040 "Return outline path to current headline.
11042 Outline path is a list of strings, in reverse order. When
11043 optional argument USE-CACHE is non-nil, make use of a cache. See
11044 `org-get-outline-path' for details.
11046 Assume buffer is widened and point is on a headline."
11047 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11048 (let ((p (point))
11049 (heading (let ((case-fold-search nil))
11050 (looking-at org-complex-heading-regexp)
11051 (if (not (match-end 4)) ""
11052 ;; Remove statistics cookies.
11053 (org-trim
11054 (org-link-display-format
11055 (replace-regexp-in-string
11056 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11057 (match-string-no-properties 4))))))))
11058 (if (org-up-heading-safe)
11059 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11060 (when use-cache
11061 (push (cons p path) org-outline-path-cache))
11062 path)
11063 ;; This is a new root node. Since we assume we are moving
11064 ;; forward, we can drop previous cache so as to limit number
11065 ;; of associations there.
11066 (let ((path (list heading)))
11067 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11068 path)))))
11070 (defun org-get-outline-path (&optional with-self use-cache)
11071 "Return the outline path to the current entry.
11073 An outline path is a list of ancestors for current headline, as
11074 a list of strings. Statistics cookies are removed and links are
11075 replaced with their description, if any, or their path otherwise.
11077 When optional argument WITH-SELF is non-nil, the path also
11078 includes the current headline.
11080 When optional argument USE-CACHE is non-nil, cache outline paths
11081 between calls to this function so as to avoid backtracking. This
11082 argument is useful when planning to find more than one outline
11083 path in the same document. In that case, there are two
11084 conditions to satisfy:
11085 - `org-outline-path-cache' is set to nil before starting the
11086 process;
11087 - outline paths are computed by increasing buffer positions."
11088 (org-with-wide-buffer
11089 (and (or (and with-self (org-back-to-heading t))
11090 (org-up-heading-safe))
11091 (reverse (org--get-outline-path-1 use-cache)))))
11093 (defun org-format-outline-path (path &optional width prefix separator)
11094 "Format the outline path PATH for display.
11095 WIDTH is the maximum number of characters that is available.
11096 PREFIX is a prefix to be included in the returned string,
11097 such as the file name.
11098 SEPARATOR is inserted between the different parts of the path,
11099 the default is \"/\"."
11100 (setq width (or width 79))
11101 (setq path (delq nil path))
11102 (unless (> width 0)
11103 (user-error "Argument `width' must be positive"))
11104 (setq separator (or separator "/"))
11105 (let* ((org-odd-levels-only nil)
11106 (fpath (concat
11107 prefix (and prefix path separator)
11108 (mapconcat
11109 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11110 (cl-loop for head in path
11111 for n from 0
11112 collect (org-add-props
11113 head nil 'face
11114 (nth (% n org-n-level-faces) org-level-faces)))
11115 separator))))
11116 (when (> (length fpath) width)
11117 (if (< width 7)
11118 ;; It's unlikely that `width' will be this small, but don't
11119 ;; waste characters by adding ".." if it is.
11120 (setq fpath (substring fpath 0 width))
11121 (setf (substring fpath (- width 2)) "..")))
11122 fpath))
11124 (defun org-display-outline-path (&optional file current separator just-return-string)
11125 "Display the current outline path in the echo area.
11127 If FILE is non-nil, prepend the output with the file name.
11128 If CURRENT is non-nil, append the current heading to the output.
11129 SEPARATOR is passed through to `org-format-outline-path'. It separates
11130 the different parts of the path and defaults to \"/\".
11131 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11132 (interactive "P")
11133 (let* (case-fold-search
11134 (bfn (buffer-file-name (buffer-base-buffer)))
11135 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11136 res)
11137 (when current (setq path (append path
11138 (save-excursion
11139 (org-back-to-heading t)
11140 (when (looking-at org-complex-heading-regexp)
11141 (list (match-string 4)))))))
11142 (setq res
11143 (org-format-outline-path
11144 path
11145 (1- (frame-width))
11146 (and file bfn (concat (file-name-nondirectory bfn) separator))
11147 separator))
11148 (if just-return-string
11149 (org-no-properties res)
11150 (org-unlogged-message "%s" res))))
11152 (defvar org-refile-history nil
11153 "History for refiling operations.")
11155 (defvar org-after-refile-insert-hook nil
11156 "Hook run after `org-refile' has inserted its stuff at the new location.
11157 Note that this is still *before* the stuff will be removed from
11158 the *old* location.")
11160 (defvar org-capture-last-stored-marker)
11161 (defvar org-refile-keep nil
11162 "Non-nil means `org-refile' will copy instead of refile.")
11164 (defun org-copy ()
11165 "Like `org-refile', but copy."
11166 (interactive)
11167 (let ((org-refile-keep t))
11168 (funcall 'org-refile nil nil nil "Copy")))
11170 (defun org-refile (&optional arg default-buffer rfloc msg)
11171 "Move the entry or entries at point to another heading.
11173 The list of target headings is compiled using the information in
11174 `org-refile-targets', which see.
11176 At the target location, the entry is filed as a subitem of the
11177 target heading. Depending on `org-reverse-note-order', the new
11178 subitem will either be the first or the last subitem.
11180 If there is an active region, all entries in that region will be
11181 refiled. However, the region must fulfill the requirement that
11182 the first heading sets the top-level of the moved text.
11184 With a `\\[universal-argument]' ARG, the command will only visit the target \
11185 location
11186 and not actually move anything.
11188 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11189 location where the last
11190 refiling operation has put the subtree.
11192 With a numeric prefix argument of `2', refile to the running clock.
11194 With a numeric prefix argument of `3', emulate `org-refile-keep'
11195 being set to t and copy to the target location, don't move it.
11196 Beware that keeping refiled entries may result in duplicated ID
11197 properties.
11199 RFLOC can be a refile location obtained in a different way.
11201 MSG is a string to replace \"Refile\" in the default prompt with
11202 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11204 See also `org-refile-use-outline-path'.
11206 If you are using target caching (see `org-refile-use-cache'), you
11207 have to clear the target cache in order to find new targets.
11208 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11209 prefix argument (`C-u C-u C-u C-c C-w')."
11210 (interactive "P")
11211 (if (member arg '(0 (64)))
11212 (org-refile-cache-clear)
11213 (let* ((actionmsg (cond (msg msg)
11214 ((equal arg 3) "Refile (and keep)")
11215 (t "Refile")))
11216 (regionp (org-region-active-p))
11217 (region-start (and regionp (region-beginning)))
11218 (region-end (and regionp (region-end)))
11219 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11220 pos it nbuf file level reversed)
11221 (setq last-command nil)
11222 (when regionp
11223 (goto-char region-start)
11224 (or (bolp) (goto-char (point-at-bol)))
11225 (setq region-start (point))
11226 (unless (or (org-kill-is-subtree-p
11227 (buffer-substring region-start region-end))
11228 (prog1 org-refile-active-region-within-subtree
11229 (let ((s (point-at-eol)))
11230 (org-toggle-heading)
11231 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11232 (user-error "The region is not a (sequence of) subtree(s)")))
11233 (if (equal arg '(16))
11234 (org-refile-goto-last-stored)
11235 (when (or
11236 (and (equal arg 2)
11237 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11238 (prog1
11239 (setq it (list (or org-clock-heading "running clock")
11240 (buffer-file-name
11241 (marker-buffer org-clock-hd-marker))
11243 (marker-position org-clock-hd-marker)))
11244 (setq arg nil)))
11245 (setq it
11246 (or rfloc
11247 (let (heading-text)
11248 (save-excursion
11249 (unless (and arg (listp arg))
11250 (org-back-to-heading t)
11251 (setq heading-text
11252 (replace-regexp-in-string
11253 org-bracket-link-regexp
11254 "\\3"
11255 (or (nth 4 (org-heading-components))
11256 ""))))
11257 (org-refile-get-location
11258 (cond ((and arg (listp arg)) "Goto")
11259 (regionp (concat actionmsg " region to"))
11260 (t (concat actionmsg " subtree \""
11261 heading-text "\" to")))
11262 default-buffer
11263 (and (not (equal '(4) arg))
11264 org-refile-allow-creating-parent-nodes)))))))
11265 (setq file (nth 1 it)
11266 pos (nth 3 it))
11267 (when (and (not arg)
11269 (equal (buffer-file-name) file)
11270 (if regionp
11271 (and (>= pos region-start)
11272 (<= pos region-end))
11273 (and (>= pos (point))
11274 (< pos (save-excursion
11275 (org-end-of-subtree t t))))))
11276 (error "Cannot refile to position inside the tree or region"))
11277 (setq nbuf (or (find-buffer-visiting file)
11278 (find-file-noselect file)))
11279 (if (and arg (not (equal arg 3)))
11280 (progn
11281 (pop-to-buffer-same-window nbuf)
11282 (goto-char (cond (pos)
11283 ((org-notes-order-reversed-p) (point-min))
11284 (t (point-max))))
11285 (org-show-context 'org-goto))
11286 (if regionp
11287 (progn
11288 (org-kill-new (buffer-substring region-start region-end))
11289 (org-save-markers-in-region region-start region-end))
11290 (org-copy-subtree 1 nil t))
11291 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11292 (find-file-noselect file)))
11293 (setq reversed (org-notes-order-reversed-p))
11294 (org-with-wide-buffer
11295 (if pos
11296 (progn
11297 (goto-char pos)
11298 (setq level (org-get-valid-level (funcall outline-level) 1))
11299 (goto-char
11300 (if reversed
11301 (or (outline-next-heading) (point-max))
11302 (or (save-excursion (org-get-next-sibling))
11303 (org-end-of-subtree t t)
11304 (point-max)))))
11305 (setq level 1)
11306 (if (not reversed)
11307 (goto-char (point-max))
11308 (goto-char (point-min))
11309 (or (outline-next-heading) (goto-char (point-max)))))
11310 (unless (bolp) (newline))
11311 (org-paste-subtree level nil nil t)
11312 (when org-log-refile
11313 (org-add-log-setup 'refile nil nil org-log-refile)
11314 (unless (eq org-log-refile 'note)
11315 (save-excursion (org-add-log-note))))
11316 (and org-auto-align-tags
11317 (let ((org-loop-over-headlines-in-active-region nil))
11318 (org-set-tags nil t)))
11319 (let ((bookmark-name (plist-get org-bookmark-names-plist
11320 :last-refile)))
11321 (when bookmark-name
11322 (with-demoted-errors
11323 (bookmark-set bookmark-name))))
11324 ;; If we are refiling for capture, make sure that the
11325 ;; last-capture pointers point here
11326 (when (bound-and-true-p org-capture-is-refiling)
11327 (let ((bookmark-name (plist-get org-bookmark-names-plist
11328 :last-capture-marker)))
11329 (when bookmark-name
11330 (with-demoted-errors
11331 (bookmark-set bookmark-name))))
11332 (move-marker org-capture-last-stored-marker (point)))
11333 (when (fboundp 'deactivate-mark) (deactivate-mark))
11334 (run-hooks 'org-after-refile-insert-hook)))
11335 (unless org-refile-keep
11336 (if regionp
11337 (delete-region (point) (+ (point) (- region-end region-start)))
11338 (org-preserve-local-variables
11339 (delete-region
11340 (and (org-back-to-heading t) (point))
11341 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11342 (when (featurep 'org-inlinetask)
11343 (org-inlinetask-remove-END-maybe))
11344 (setq org-markers-to-move nil)
11345 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11347 (defun org-refile-goto-last-stored ()
11348 "Go to the location where the last refile was stored."
11349 (interactive)
11350 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11351 (message "This is the location of the last refile"))
11353 (defun org-refile--get-location (refloc tbl)
11354 "When user refile to REFLOC, find the associated target in TBL.
11355 Also check `org-refile-target-table'."
11356 (car (delq
11358 (mapcar
11359 (lambda (r) (or (assoc r tbl)
11360 (assoc r org-refile-target-table)))
11361 (list (replace-regexp-in-string "/$" "" refloc)
11362 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11364 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11365 "Prompt the user for a refile location, using PROMPT.
11366 PROMPT should not be suffixed with a colon and a space, because
11367 this function appends the default value from
11368 `org-refile-history' automatically, if that is not empty."
11369 (let ((org-refile-targets org-refile-targets)
11370 (org-refile-use-outline-path org-refile-use-outline-path))
11371 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11372 (unless org-refile-target-table
11373 (user-error "No refile targets"))
11374 (let* ((cbuf (current-buffer))
11375 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11376 (cfunc (if (and org-refile-use-outline-path
11377 org-outline-path-complete-in-steps)
11378 #'org-olpath-completing-read
11379 #'completing-read))
11380 (extra (if org-refile-use-outline-path "/" ""))
11381 (cbnex (concat (buffer-name) extra))
11382 (filename (and cfn (expand-file-name cfn)))
11383 (tbl (mapcar
11384 (lambda (x)
11385 (if (and (not (member org-refile-use-outline-path
11386 '(file full-file-path)))
11387 (not (equal filename (nth 1 x))))
11388 (cons (concat (car x) extra " ("
11389 (file-name-nondirectory (nth 1 x)) ")")
11390 (cdr x))
11391 (cons (concat (car x) extra) (cdr x))))
11392 org-refile-target-table))
11393 (completion-ignore-case t)
11394 cdef
11395 (prompt (concat prompt
11396 (or (and (car org-refile-history)
11397 (concat " (default " (car org-refile-history) ")"))
11398 (and (assoc cbnex tbl) (setq cdef cbnex)
11399 (concat " (default " cbnex ")"))) ": "))
11400 pa answ parent-target child parent old-hist)
11401 (setq old-hist org-refile-history)
11402 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11403 nil 'org-refile-history (or cdef (car org-refile-history))))
11404 (if (setq pa (org-refile--get-location answ tbl))
11405 (progn
11406 (org-refile-check-position pa)
11407 (when (or (not org-refile-history)
11408 (not (eq old-hist org-refile-history))
11409 (not (equal (car pa) (car org-refile-history))))
11410 (setq org-refile-history
11411 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11412 org-refile-history
11413 (cdr org-refile-history))))
11414 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11415 (pop org-refile-history)))
11417 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11418 (progn
11419 (setq parent (match-string 1 answ)
11420 child (match-string 2 answ))
11421 (setq parent-target (org-refile--get-location parent tbl))
11422 (when (and parent-target
11423 (or (eq new-nodes t)
11424 (and (eq new-nodes 'confirm)
11425 (y-or-n-p (format "Create new node \"%s\"? "
11426 child)))))
11427 (org-refile-new-child parent-target child)))
11428 (user-error "Invalid target location")))))
11430 (declare-function org-string-nw-p "org-macs" (s))
11431 (defun org-refile-check-position (refile-pointer)
11432 "Check if the refile pointer matches the headline to which it points."
11433 (let* ((file (nth 1 refile-pointer))
11434 (re (nth 2 refile-pointer))
11435 (pos (nth 3 refile-pointer))
11436 buffer)
11437 (if (and (not (markerp pos)) (not file))
11438 (user-error "Please indicate a target file in the refile path")
11439 (when (org-string-nw-p re)
11440 (setq buffer (if (markerp pos)
11441 (marker-buffer pos)
11442 (or (find-buffer-visiting file)
11443 (find-file-noselect file))))
11444 (with-current-buffer buffer
11445 (org-with-wide-buffer
11446 (goto-char pos)
11447 (beginning-of-line 1)
11448 (unless (looking-at-p re)
11449 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11451 (defun org-refile-new-child (parent-target child)
11452 "Use refile target PARENT-TARGET to add new CHILD below it."
11453 (unless parent-target
11454 (error "Cannot find parent for new node"))
11455 (let ((file (nth 1 parent-target))
11456 (pos (nth 3 parent-target))
11457 level)
11458 (with-current-buffer (or (find-buffer-visiting file)
11459 (find-file-noselect file))
11460 (org-with-wide-buffer
11461 (if pos
11462 (goto-char pos)
11463 (goto-char (point-max))
11464 (unless (bolp) (newline)))
11465 (when (looking-at org-outline-regexp)
11466 (setq level (funcall outline-level))
11467 (org-end-of-subtree t t))
11468 (org-back-over-empty-lines)
11469 (insert "\n" (make-string
11470 (if pos (org-get-valid-level level 1) 1) ?*)
11471 " " child "\n")
11472 (beginning-of-line 0)
11473 (list (concat (car parent-target) "/" child) file "" (point))))))
11475 (defun org-olpath-completing-read (prompt collection &rest args)
11476 "Read an outline path like a file name."
11477 (let ((thetable collection))
11478 (apply #'completing-read
11479 prompt
11480 (lambda (string predicate &optional flag)
11481 (cond
11482 ((eq flag nil) (try-completion string thetable))
11483 ((eq flag t)
11484 (let ((l (length string)))
11485 (mapcar (lambda (x)
11486 (let ((r (substring x l))
11487 (f (if (string-match " ([^)]*)$" x)
11488 (match-string 0 x)
11489 "")))
11490 (if (string-match "/" r)
11491 (concat string (substring r 0 (match-end 0)) f)
11492 x)))
11493 (all-completions string thetable predicate))))
11494 ;; Exact match?
11495 ((eq flag 'lambda) (assoc string thetable))))
11496 args)))
11498 ;;;; Dynamic blocks
11500 (defun org-find-dblock (name)
11501 "Find the first dynamic block with name NAME in the buffer.
11502 If not found, stay at current position and return nil."
11503 (let ((case-fold-search t) pos)
11504 (save-excursion
11505 (goto-char (point-min))
11506 (setq pos (and (re-search-forward
11507 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11508 (match-beginning 0))))
11509 (when pos (goto-char pos))
11510 pos))
11512 (defun org-create-dblock (plist)
11513 "Create a dynamic block section, with parameters taken from PLIST.
11514 PLIST must contain a :name entry which is used as the name of the block."
11515 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11516 (end-of-line 1)
11517 (newline))
11518 (let ((col (current-column))
11519 (name (plist-get plist :name)))
11520 (insert "#+BEGIN: " name)
11521 (while plist
11522 (if (eq (car plist) :name)
11523 (setq plist (cddr plist))
11524 (insert " " (prin1-to-string (pop plist)))))
11525 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11526 (beginning-of-line -2)))
11528 (defun org-prepare-dblock ()
11529 "Prepare dynamic block for refresh.
11530 This empties the block, puts the cursor at the insert position and returns
11531 the property list including an extra property :name with the block name."
11532 (unless (looking-at org-dblock-start-re)
11533 (user-error "Not at a dynamic block"))
11534 (let* ((begdel (1+ (match-end 0)))
11535 (name (org-no-properties (match-string 1)))
11536 (params (append (list :name name)
11537 (read (concat "(" (match-string 3) ")")))))
11538 (save-excursion
11539 (beginning-of-line 1)
11540 (skip-chars-forward " \t")
11541 (setq params (plist-put params :indentation-column (current-column))))
11542 (unless (re-search-forward org-dblock-end-re nil t)
11543 (error "Dynamic block not terminated"))
11544 (setq params
11545 (append params
11546 (list :content (buffer-substring
11547 begdel (match-beginning 0)))))
11548 (delete-region begdel (match-beginning 0))
11549 (goto-char begdel)
11550 (open-line 1)
11551 params))
11553 (defun org-map-dblocks (&optional command)
11554 "Apply COMMAND to all dynamic blocks in the current buffer.
11555 If COMMAND is not given, use `org-update-dblock'."
11556 (let ((cmd (or command 'org-update-dblock)))
11557 (save-excursion
11558 (goto-char (point-min))
11559 (while (re-search-forward org-dblock-start-re nil t)
11560 (goto-char (match-beginning 0))
11561 (save-excursion
11562 (condition-case nil
11563 (funcall cmd)
11564 (error (message "Error during update of dynamic block"))))
11565 (unless (re-search-forward org-dblock-end-re nil t)
11566 (error "Dynamic block not terminated"))))))
11568 (defun org-dblock-update (&optional arg)
11569 "User command for updating dynamic blocks.
11570 Update the dynamic block at point. With prefix ARG, update all dynamic
11571 blocks in the buffer."
11572 (interactive "P")
11573 (if arg
11574 (org-update-all-dblocks)
11575 (or (looking-at org-dblock-start-re)
11576 (org-beginning-of-dblock))
11577 (org-update-dblock)))
11579 (defun org-update-dblock ()
11580 "Update the dynamic block at point.
11581 This means to empty the block, parse for parameters and then call
11582 the correct writing function."
11583 (interactive)
11584 (save-excursion
11585 (let* ((win (selected-window))
11586 (pos (point))
11587 (line (org-current-line))
11588 (params (org-prepare-dblock))
11589 (name (plist-get params :name))
11590 (indent (plist-get params :indentation-column))
11591 (cmd (intern (concat "org-dblock-write:" name))))
11592 (message "Updating dynamic block `%s' at line %d..." name line)
11593 (funcall cmd params)
11594 (message "Updating dynamic block `%s' at line %d...done" name line)
11595 (goto-char pos)
11596 (when (and indent (> indent 0))
11597 (setq indent (make-string indent ?\ ))
11598 (save-excursion
11599 (select-window win)
11600 (org-beginning-of-dblock)
11601 (forward-line 1)
11602 (while (not (looking-at org-dblock-end-re))
11603 (insert indent)
11604 (beginning-of-line 2))
11605 (when (looking-at org-dblock-end-re)
11606 (and (looking-at "[ \t]+")
11607 (replace-match ""))
11608 (insert indent)))))))
11610 (defun org-beginning-of-dblock ()
11611 "Find the beginning of the dynamic block at point.
11612 Error if there is no such block at point."
11613 (let ((pos (point))
11614 beg)
11615 (end-of-line 1)
11616 (if (and (re-search-backward org-dblock-start-re nil t)
11617 (setq beg (match-beginning 0))
11618 (re-search-forward org-dblock-end-re nil t)
11619 (> (match-end 0) pos))
11620 (goto-char beg)
11621 (goto-char pos)
11622 (error "Not in a dynamic block"))))
11624 (defun org-update-all-dblocks ()
11625 "Update all dynamic blocks in the buffer.
11626 This function can be used in a hook."
11627 (interactive)
11628 (when (derived-mode-p 'org-mode)
11629 (org-map-dblocks 'org-update-dblock)))
11632 ;;;; Completion
11634 (declare-function org-export-backend-options "ox" (cl-x) t)
11635 (defun org-get-export-keywords ()
11636 "Return a list of all currently understood export keywords.
11637 Export keywords include options, block names, attributes and
11638 keywords relative to each registered export back-end."
11639 (let (keywords)
11640 (dolist (backend
11641 (bound-and-true-p org-export-registered-backends)
11642 (delq nil keywords))
11643 ;; Back-end name (for keywords, like #+LATEX:)
11644 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11645 (dolist (option-entry (org-export-backend-options backend))
11646 ;; Back-end options.
11647 (push (nth 1 option-entry) keywords)))))
11649 (defconst org-options-keywords
11650 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11651 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11652 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11653 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11654 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11656 (defcustom org-structure-template-alist
11657 '(("a" . "export ascii")
11658 ("c" . "center")
11659 ("C" . "comment")
11660 ("e" . "example")
11661 ("E" . "export")
11662 ("h" . "export html")
11663 ("l" . "export latex")
11664 ("q" . "quote")
11665 ("s" . "src")
11666 ("v" . "verse"))
11667 "Structure completion elements.
11668 This is an alist of keys and block types. With
11669 `org-insert-structure-template' a block can be inserted through a
11670 menu. The block type is inserted, with \"#+BEGIN_\" and
11671 \"#+END_\" added automatically. The menukeys are determined
11672 based on the key elements in the `org-structure-template-alist'.
11673 If two entries have the keys \"a\" and \"aa\" respectively, the
11674 former will be inserted by typing \"a TAB/RET/SPC\" and the
11675 latter will be inserted by typing \"aa\". If an entry with the
11676 key \"aab\" is later added it would be inserted by typing \"ab\".
11678 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11679 block can be inserted by pressing TAB after the string \"<KEY\".
11681 :group 'org-edit-structure
11682 :type '(repeat
11683 (cons (string :tag "Key")
11684 (string :tag "Template")))
11685 :package-version '(Org . "9.2"))
11687 (defun org--insert-structure-template-mks ()
11688 "Present `org-structure-template-alist' with `org-mks'.
11690 Menus are added if keys require more than one keystroke.
11691 Tabs are added to single key entires when needing more than one stroke.
11692 Keys longer than two characters are reduced to two characters."
11693 (let* (case-fold-search
11694 (templates (append org-structure-template-alist
11695 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11696 (keys (mapcar #'car templates))
11697 (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11698 ;; Sort each element of `org-structure-template-alist' into
11699 ;; sublists according to the first letter.
11700 (superlist (mapcar (lambda (letter)
11701 (list letter
11702 (cl-remove-if-not
11703 (apply-partially #'string-match-p (concat "^" letter))
11704 templates :key #'car)))
11705 start-letters)))
11706 (org-mks
11707 (apply #'append
11708 ;; Make an `org-mks' table. If only one element is
11709 ;; present in a sublist, make it part of the top-menu,
11710 ;; otherwise make a submenu according to the starting
11711 ;; letter and populate it.
11712 (mapcar (lambda (sublist)
11713 (if (eq 1 (length (cadr sublist)))
11714 (mapcar (lambda (elm)
11715 (list (substring (car elm) 0 1)
11716 (cdr elm) ""))
11717 (cadr sublist))
11718 ;; Create submenu.
11719 (let* ((topkey (car sublist))
11720 (elms (cadr sublist))
11721 (keys (mapcar #'car elms))
11722 (long (> (length elms) 3)))
11723 (append
11724 (list
11725 ;; Make a description of the submenu.
11726 (list topkey
11727 (concat
11728 (mapconcat #'cdr
11729 (cl-subseq elms 0 (if long 3 (length elms)))
11730 ", ")
11731 (when long ", ..."))))
11732 ;; List of entries in submenu.
11733 (cl-mapcar #'list
11734 (org--insert-structure-template-unique-keys keys)
11735 (mapcar #'cdr elms)
11736 (make-list (length elms) ""))))))
11737 superlist))
11738 "Select a key\n============"
11739 "Key: ")))
11741 (defun org--insert-structure-template-unique-keys (keys)
11742 "Make list of unique, two character long elements from KEYS.
11744 Elements of length one have a tab appended. Elements of length
11745 two are kept as is. Longer elements are truncated to length two.
11747 If an element cannot be made unique an error is raised."
11748 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11749 menu-keys)
11750 (dolist (key orderd-keys)
11751 (let ((potential-key
11752 (cl-case (length key)
11753 (1 (concat key "\t"))
11754 (2 key)
11755 (otherwise
11756 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11757 (mapcar (apply-partially #'concat (substring key 0 1))
11758 (split-string (substring key 1) "" t)))))))
11759 (if (or (not potential-key) (assoc potential-key menu-keys))
11760 (user-error "Could not make unique key for %s." key)
11761 (push (cons potential-key key) menu-keys))))
11762 (mapcar #'car
11763 (cl-sort menu-keys #'<
11764 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11766 (defun org-insert-structure-template (type)
11767 "Insert a block structure of the type #+begin_foo/#+end_foo.
11768 First choose a block based on `org-structure-template-alist'.
11769 Alternatively, type RET, TAB or SPC to write the block type.
11770 With an active region, wrap the region in the block. Otherwise,
11771 insert an empty block."
11772 (interactive
11773 (list (pcase (org--insert-structure-template-mks)
11774 (`("\t" . ,_) (read-string "Structure type: "))
11775 (`(,_ ,choice . ,_) choice))))
11776 (let* ((region? (use-region-p))
11777 (col (current-indentation))
11778 (indent (make-string col ?\s))
11779 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11780 (region-string (and region?
11781 (buffer-substring (region-beginning)
11782 (region-end))))
11783 (region-end-blank (and region?
11784 (save-excursion
11785 (goto-char (region-end))
11786 (when (looking-at "[ \t]*$")
11787 (replace-match "")
11788 t))))
11790 (when region? (delete-region (region-beginning) (region-end)))
11791 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11792 (insert "\n"))
11793 (beginning-of-line)
11794 (save-excursion
11795 (insert
11796 (with-temp-buffer
11797 (when region?
11798 (insert region-string "\n")
11799 (when (string-match-p
11800 (concat "\\`" (regexp-opt '("example" "export" "src")))
11801 type)
11802 (org-escape-code-in-region (point-min) (point-max))))
11803 (goto-char (point-min))
11804 ;; Delete trailing white-lines.
11805 (when region?
11806 (while (looking-at-p "^[ \t]*$")
11807 (delete-region (line-beginning-position)
11808 (line-beginning-position 2))))
11809 (save-excursion
11810 (while (not (eobp))
11811 (unless (looking-at-p indent)
11812 (insert indent))
11813 (forward-line)))
11814 (insert
11815 indent
11816 (format "#+begin_%s%s\n" type (if special? " " "")))
11817 (unless region? (indent-to col))
11818 (setq s (point))
11819 (goto-char (point-max))
11820 (skip-chars-backward "[ \t\n]" s)
11821 (delete-region (line-end-position) (point-max))
11822 (insert "\n" indent
11823 (format "#+end_%s" (car (split-string type)))
11824 (if region-end-blank "" "\n"))
11825 (buffer-substring (point-min) (point))))
11826 (when (and (eobp) (not (bolp))) (insert "\n")))
11827 (cond (special?
11828 (end-of-line))
11830 (forward-line)
11831 (skip-chars-forward "[ \t]*")))))
11834 ;;;; TODO, DEADLINE, Comments
11836 (defun org-toggle-comment ()
11837 "Change the COMMENT state of an entry."
11838 (interactive)
11839 (save-excursion
11840 (org-back-to-heading)
11841 (let ((case-fold-search nil))
11842 (looking-at org-complex-heading-regexp))
11843 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11844 (skip-chars-forward " \t")
11845 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11846 (if (org-in-commented-heading-p t)
11847 (delete-region (point)
11848 (progn (search-forward " " (line-end-position) 'move)
11849 (skip-chars-forward " \t")
11850 (point)))
11851 (insert org-comment-string)
11852 (unless (eolp) (insert " ")))))
11854 (defvar org-last-todo-state-is-todo nil
11855 "This is non-nil when the last TODO state change led to a TODO state.
11856 If the last change removed the TODO tag or switched to DONE, then
11857 this is nil.")
11859 (defvar org-setting-tags nil) ; dynamically scoped
11861 (defvar org-todo-setup-filter-hook nil
11862 "Hook for functions that pre-filter todo specs.
11863 Each function takes a todo spec and returns either nil or the spec
11864 transformed into canonical form." )
11866 (defvar org-todo-get-default-hook nil
11867 "Hook for functions that get a default item for todo.
11868 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11869 nil or a string to be used for the todo mark." )
11871 (defvar org-agenda-headline-snapshot-before-repeat)
11873 (defun org-current-effective-time ()
11874 "Return current time adjusted for `org-extend-today-until' variable."
11875 (let* ((ct (org-current-time))
11876 (dct (decode-time ct))
11877 (ct1
11878 (cond
11879 (org-use-last-clock-out-time-as-effective-time
11880 (or (org-clock-get-last-clock-out-time) ct))
11881 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11882 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11883 (t ct))))
11884 ct1))
11886 (defun org-todo-yesterday (&optional arg)
11887 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11888 (interactive "P")
11889 (if (eq major-mode 'org-agenda-mode)
11890 (apply 'org-agenda-todo-yesterday arg)
11891 (let* ((org-use-effective-time t)
11892 (hour (nth 2 (decode-time (org-current-time))))
11893 (org-extend-today-until (1+ hour)))
11894 (org-todo arg))))
11896 (defvar org-block-entry-blocking ""
11897 "First entry preventing the TODO state change.")
11899 (defun org-cancel-repeater ()
11900 "Cancel a repeater by setting its numeric value to zero."
11901 (interactive)
11902 (save-excursion
11903 (org-back-to-heading t)
11904 (let ((bound1 (point))
11905 (bound0 (save-excursion (outline-next-heading) (point))))
11906 (when (and (re-search-forward
11907 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11908 org-deadline-time-regexp "\\)\\|\\("
11909 org-ts-regexp "\\)")
11910 bound0 t)
11911 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11912 bound1 t))
11913 (replace-match "0" t nil nil 1)))))
11915 (defvar org-state)
11916 (defvar org-blocked-by-checkboxes)
11917 (defun org-todo (&optional arg)
11918 "Change the TODO state of an item.
11920 The state of an item is given by a keyword at the start of the heading,
11921 like
11922 *** TODO Write paper
11923 *** DONE Call mom
11925 The different keywords are specified in the variable `org-todo-keywords'.
11926 By default the available states are \"TODO\" and \"DONE\". So, for this
11927 example: when the item starts with TODO, it is changed to DONE.
11928 When it starts with DONE, the DONE is removed. And when neither TODO nor
11929 DONE are present, add TODO at the beginning of the heading.
11931 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11932 state.
11933 With numeric prefix ARG, switch to that state.
11934 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11935 next set of TODO \
11936 keywords (nextset).
11937 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11938 prefix, circumvent any state blocking.
11939 With a numeric prefix arg of 0, inhibit note taking for the change.
11940 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11942 When called through ELisp, arg is also interpreted in the following way:
11943 `none' -> empty state
11944 \"\" -> switch to empty state
11945 `done' -> switch to DONE
11946 `nextset' -> switch to the next set of keywords
11947 `previousset' -> switch to the previous set of keywords
11948 \"WAITING\" -> switch to the specified keyword, but only if it
11949 really is a member of `org-todo-keywords'."
11950 (interactive "P")
11951 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11952 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11953 'region-start-level 'region))
11954 org-loop-over-headlines-in-active-region)
11955 (org-map-entries
11956 `(org-todo ,arg)
11957 org-loop-over-headlines-in-active-region
11958 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11959 (when (equal arg '(16)) (setq arg 'nextset))
11960 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11961 (let ((org-blocker-hook org-blocker-hook)
11962 commentp
11963 case-fold-search)
11964 (when (equal arg '(64))
11965 (setq arg nil org-blocker-hook nil))
11966 (when (and org-blocker-hook
11967 (or org-inhibit-blocking
11968 (org-entry-get nil "NOBLOCKING")))
11969 (setq org-blocker-hook nil))
11970 (save-excursion
11971 (catch 'exit
11972 (org-back-to-heading t)
11973 (when (org-in-commented-heading-p t)
11974 (org-toggle-comment)
11975 (setq commentp t))
11976 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11977 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11978 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11979 (let* ((match-data (match-data))
11980 (startpos (copy-marker (line-beginning-position)))
11981 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11982 (org-log-done org-log-done)
11983 (org-log-repeat org-log-repeat)
11984 (org-todo-log-states org-todo-log-states)
11985 (org-inhibit-logging
11986 (if (equal arg 0)
11987 (progn (setq arg nil) 'note) org-inhibit-logging))
11988 (this (match-string 1))
11989 (hl-pos (match-beginning 0))
11990 (head (org-get-todo-sequence-head this))
11991 (ass (assoc head org-todo-kwd-alist))
11992 (interpret (nth 1 ass))
11993 (done-word (nth 3 ass))
11994 (final-done-word (nth 4 ass))
11995 (org-last-state (or this ""))
11996 (completion-ignore-case t)
11997 (member (member this org-todo-keywords-1))
11998 (tail (cdr member))
11999 (org-state (cond
12000 ((and org-todo-key-trigger
12001 (or (and (equal arg '(4))
12002 (eq org-use-fast-todo-selection 'prefix))
12003 (and (not arg) org-use-fast-todo-selection
12004 (not (eq org-use-fast-todo-selection
12005 'prefix)))))
12006 ;; Use fast selection.
12007 (org-fast-todo-selection))
12008 ((and (equal arg '(4))
12009 (or (not org-use-fast-todo-selection)
12010 (not org-todo-key-trigger)))
12011 ;; Read a state with completion.
12012 (completing-read
12013 "State: " (mapcar #'list org-todo-keywords-1)
12014 nil t))
12015 ((eq arg 'right)
12016 (if this
12017 (if tail (car tail) nil)
12018 (car org-todo-keywords-1)))
12019 ((eq arg 'left)
12020 (unless (equal member org-todo-keywords-1)
12021 (if this
12022 (nth (- (length org-todo-keywords-1)
12023 (length tail) 2)
12024 org-todo-keywords-1)
12025 (org-last org-todo-keywords-1))))
12026 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12027 (setq arg nil))) ;hack to fall back to cycling
12028 (arg
12029 ;; User or caller requests a specific state.
12030 (cond
12031 ((equal arg "") nil)
12032 ((eq arg 'none) nil)
12033 ((eq arg 'done) (or done-word (car org-done-keywords)))
12034 ((eq arg 'nextset)
12035 (or (car (cdr (member head org-todo-heads)))
12036 (car org-todo-heads)))
12037 ((eq arg 'previousset)
12038 (let ((org-todo-heads (reverse org-todo-heads)))
12039 (or (car (cdr (member head org-todo-heads)))
12040 (car org-todo-heads))))
12041 ((car (member arg org-todo-keywords-1)))
12042 ((stringp arg)
12043 (user-error "State `%s' not valid in this file" arg))
12044 ((nth (1- (prefix-numeric-value arg))
12045 org-todo-keywords-1))))
12046 ((null member) (or head (car org-todo-keywords-1)))
12047 ((equal this final-done-word) nil) ;-> make empty
12048 ((null tail) nil) ;-> first entry
12049 ((memq interpret '(type priority))
12050 (if (eq this-command last-command)
12051 (car tail)
12052 (if (> (length tail) 0)
12053 (or done-word (car org-done-keywords))
12054 nil)))
12056 (car tail))))
12057 (org-state (or
12058 (run-hook-with-args-until-success
12059 'org-todo-get-default-hook org-state org-last-state)
12060 org-state))
12061 (next (if org-state (concat " " org-state " ") " "))
12062 (change-plist (list :type 'todo-state-change :from this :to org-state
12063 :position startpos))
12064 dolog now-done-p)
12065 (when org-blocker-hook
12066 (let (org-blocked-by-checkboxes block-reason)
12067 (setq org-last-todo-state-is-todo
12068 (not (member this org-done-keywords)))
12069 (unless (save-excursion
12070 (save-match-data
12071 (org-with-wide-buffer
12072 (run-hook-with-args-until-failure
12073 'org-blocker-hook change-plist))))
12074 (setq block-reason (if org-blocked-by-checkboxes
12075 "contained checkboxes"
12076 (format "\"%s\"" org-block-entry-blocking)))
12077 (if (called-interactively-p 'interactive)
12078 (user-error "TODO state change from %s to %s blocked (by %s)"
12079 this org-state block-reason)
12080 ;; Fail silently.
12081 (message "TODO state change from %s to %s blocked (by %s)"
12082 this org-state block-reason)
12083 (throw 'exit nil)))))
12084 (store-match-data match-data)
12085 (replace-match next t t)
12086 (cond ((equal this org-state)
12087 (message "TODO state was already %s" (org-trim next)))
12088 ((not (pos-visible-in-window-p hl-pos))
12089 (message "TODO state changed to %s" (org-trim next))))
12090 (unless head
12091 (setq head (org-get-todo-sequence-head org-state)
12092 ass (assoc head org-todo-kwd-alist)
12093 interpret (nth 1 ass)
12094 done-word (nth 3 ass)
12095 final-done-word (nth 4 ass)))
12096 (when (memq arg '(nextset previousset))
12097 (message "Keyword-Set %d/%d: %s"
12098 (- (length org-todo-sets) -1
12099 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12100 (length org-todo-sets)
12101 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12102 (setq org-last-todo-state-is-todo
12103 (not (member org-state org-done-keywords)))
12104 (setq now-done-p (and (member org-state org-done-keywords)
12105 (not (member this org-done-keywords))))
12106 (and logging (org-local-logging logging))
12107 (when (and (or org-todo-log-states org-log-done)
12108 (not (eq org-inhibit-logging t))
12109 (not (memq arg '(nextset previousset))))
12110 ;; We need to look at recording a time and note.
12111 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12112 (nth 2 (assoc this org-todo-log-states))))
12113 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12114 (setq dolog 'time))
12115 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12116 (and org-state
12117 (member org-state org-not-done-keywords)
12118 (not (member this org-not-done-keywords))))
12119 ;; This is now a todo state and was not one before
12120 ;; If there was a CLOSED time stamp, get rid of it.
12121 (org-add-planning-info nil nil 'closed))
12122 (when (and now-done-p org-log-done)
12123 ;; It is now done, and it was not done before.
12124 (org-add-planning-info 'closed (org-current-effective-time))
12125 (when (and (not dolog) (eq 'note org-log-done))
12126 (org-add-log-setup 'done org-state this 'note)))
12127 (when (and org-state dolog)
12128 ;; This is a non-nil state, and we need to log it.
12129 (org-add-log-setup 'state org-state this dolog)))
12130 ;; Fixup tag positioning.
12131 (org-todo-trigger-tag-changes org-state)
12132 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12133 (when org-provide-todo-statistics
12134 (org-update-parent-todo-statistics))
12135 (run-hooks 'org-after-todo-state-change-hook)
12136 (when (and arg (not (member org-state org-done-keywords)))
12137 (setq head (org-get-todo-sequence-head org-state)))
12138 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12139 ;; Do we need to trigger a repeat?
12140 (when now-done-p
12141 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12142 ;; This is for the agenda, take a snapshot of the headline.
12143 (save-match-data
12144 (setq org-agenda-headline-snapshot-before-repeat
12145 (org-get-heading))))
12146 (org-auto-repeat-maybe org-state))
12147 ;; Fixup cursor location if close to the keyword.
12148 (when (and (outline-on-heading-p)
12149 (not (bolp))
12150 (save-excursion (beginning-of-line 1)
12151 (looking-at org-todo-line-regexp))
12152 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12153 (goto-char (or (match-end 2) (match-end 1)))
12154 (and (looking-at " ") (just-one-space)))
12155 (when org-trigger-hook
12156 (save-excursion
12157 (run-hook-with-args 'org-trigger-hook change-plist)))
12158 (when commentp (org-toggle-comment))))))))
12160 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12161 "Block turning an entry into a TODO, using the hierarchy.
12162 This checks whether the current task should be blocked from state
12163 changes. Such blocking occurs when:
12165 1. The task has children which are not all in a completed state.
12167 2. A task has a parent with the property :ORDERED:, and there
12168 are siblings prior to the current task with incomplete
12169 status.
12171 3. The parent of the task is blocked because it has siblings that should
12172 be done first, or is child of a block grandparent TODO entry."
12174 (if (not org-enforce-todo-dependencies)
12175 t ; if locally turned off don't block
12176 (catch 'dont-block
12177 ;; If this is not a todo state change, or if this entry is already DONE,
12178 ;; do not block
12179 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12180 (member (plist-get change-plist :from)
12181 (cons 'done org-done-keywords))
12182 (member (plist-get change-plist :to)
12183 (cons 'todo org-not-done-keywords))
12184 (not (plist-get change-plist :to)))
12185 (throw 'dont-block t))
12186 ;; If this task has children, and any are undone, it's blocked
12187 (save-excursion
12188 (org-back-to-heading t)
12189 (let ((this-level (funcall outline-level)))
12190 (outline-next-heading)
12191 (let ((child-level (funcall outline-level)))
12192 (while (and (not (eobp))
12193 (> child-level this-level))
12194 ;; this todo has children, check whether they are all
12195 ;; completed
12196 (when (and (not (org-entry-is-done-p))
12197 (org-entry-is-todo-p))
12198 (setq org-block-entry-blocking (org-get-heading))
12199 (throw 'dont-block nil))
12200 (outline-next-heading)
12201 (setq child-level (funcall outline-level))))))
12202 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12203 ;; any previous siblings are undone, it's blocked
12204 (save-excursion
12205 (org-back-to-heading t)
12206 (let* ((pos (point))
12207 (parent-pos (and (org-up-heading-safe) (point)))
12208 (case-fold-search nil))
12209 (unless parent-pos (throw 'dont-block t)) ; no parent
12210 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12211 (forward-line 1)
12212 (re-search-forward org-not-done-heading-regexp pos t))
12213 (setq org-block-entry-blocking (match-string 0))
12214 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12215 ;; Search further up the hierarchy, to see if an ancestor is blocked
12216 (while t
12217 (goto-char parent-pos)
12218 (unless (looking-at org-not-done-heading-regexp)
12219 (throw 'dont-block t)) ; do not block, parent is not a TODO
12220 (setq pos (point))
12221 (setq parent-pos (and (org-up-heading-safe) (point)))
12222 (unless parent-pos (throw 'dont-block t)) ; no parent
12223 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12224 (forward-line 1)
12225 (re-search-forward org-not-done-heading-regexp pos t)
12226 (setq org-block-entry-blocking (org-get-heading)))
12227 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12229 (defcustom org-track-ordered-property-with-tag nil
12230 "Should the ORDERED property also be shown as a tag?
12231 The ORDERED property decides if an entry should require subtasks to be
12232 completed in sequence. Since a property is not very visible, setting
12233 this option means that toggling the ORDERED property with the command
12234 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12235 not relevant for the behavior, but it makes things more visible.
12237 Note that toggling the tag with tags commands will not change the property
12238 and therefore not influence behavior!
12240 This can be t, meaning the tag ORDERED should be used, It can also be a
12241 string to select a different tag for this task."
12242 :group 'org-todo
12243 :type '(choice
12244 (const :tag "No tracking" nil)
12245 (const :tag "Track with ORDERED tag" t)
12246 (string :tag "Use other tag")))
12248 (defun org-toggle-ordered-property ()
12249 "Toggle the ORDERED property of the current entry.
12250 For better visibility, you can track the value of this property with a tag.
12251 See variable `org-track-ordered-property-with-tag'."
12252 (interactive)
12253 (let* ((t1 org-track-ordered-property-with-tag)
12254 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12255 (save-excursion
12256 (org-back-to-heading)
12257 (if (org-entry-get nil "ORDERED")
12258 (progn
12259 (org-delete-property "ORDERED")
12260 (and tag (org-toggle-tag tag 'off))
12261 (message "Subtasks can be completed in arbitrary order"))
12262 (org-entry-put nil "ORDERED" "t")
12263 (and tag (org-toggle-tag tag 'on))
12264 (message "Subtasks must be completed in sequence")))))
12266 (defun org-block-todo-from-checkboxes (change-plist)
12267 "Block turning an entry into a TODO, using checkboxes.
12268 This checks whether the current task should be blocked from state
12269 changes because there are unchecked boxes in this entry."
12270 (if (not org-enforce-todo-checkbox-dependencies)
12271 t ; if locally turned off don't block
12272 (catch 'dont-block
12273 ;; If this is not a todo state change, or if this entry is already DONE,
12274 ;; do not block
12275 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12276 (member (plist-get change-plist :from)
12277 (cons 'done org-done-keywords))
12278 (member (plist-get change-plist :to)
12279 (cons 'todo org-not-done-keywords))
12280 (not (plist-get change-plist :to)))
12281 (throw 'dont-block t))
12282 ;; If this task has checkboxes that are not checked, it's blocked
12283 (save-excursion
12284 (org-back-to-heading t)
12285 (let ((beg (point)) end)
12286 (outline-next-heading)
12287 (setq end (point))
12288 (goto-char beg)
12289 (when (org-list-search-forward
12290 (concat (org-item-beginning-re)
12291 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12292 "\\[[- ]\\]")
12293 end t)
12294 (when (boundp 'org-blocked-by-checkboxes)
12295 (setq org-blocked-by-checkboxes t))
12296 (throw 'dont-block nil))))
12297 t))) ; do not block
12299 (defun org-entry-blocked-p ()
12300 "Non-nil if entry at point is blocked."
12301 (and (not (org-entry-get nil "NOBLOCKING"))
12302 (member (org-entry-get nil "TODO") org-not-done-keywords)
12303 (not (run-hook-with-args-until-failure
12304 'org-blocker-hook
12305 (list :type 'todo-state-change
12306 :position (point)
12307 :from 'todo
12308 :to 'done)))))
12310 (defun org-update-statistics-cookies (all)
12311 "Update the statistics cookie, either from TODO or from checkboxes.
12312 This should be called with the cursor in a line with a statistics
12313 cookie. When called with a \\[universal-argument] prefix, update
12314 all statistics cookies in the buffer."
12315 (interactive "P")
12316 (if all
12317 (progn
12318 (org-update-checkbox-count 'all)
12319 (org-map-entries 'org-update-parent-todo-statistics))
12320 (if (not (org-at-heading-p))
12321 (org-update-checkbox-count)
12322 (let ((pos (point-marker))
12323 end l1 l2)
12324 (ignore-errors (org-back-to-heading t))
12325 (if (not (org-at-heading-p))
12326 (org-update-checkbox-count)
12327 (setq l1 (org-outline-level))
12328 (setq end (save-excursion
12329 (outline-next-heading)
12330 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12331 (point)))
12332 (if (and (save-excursion
12333 (re-search-forward
12334 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12335 (not (save-excursion (re-search-forward
12336 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12337 (org-update-checkbox-count)
12338 (if (and l2 (> l2 l1))
12339 (progn
12340 (goto-char end)
12341 (org-update-parent-todo-statistics))
12342 (goto-char pos)
12343 (beginning-of-line 1)
12344 (while (re-search-forward
12345 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12346 (point-at-eol) t)
12347 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12348 (goto-char pos)
12349 (move-marker pos nil)))))
12351 (defvar org-entry-property-inherited-from) ;; defined below
12352 (defun org-update-parent-todo-statistics ()
12353 "Update any statistics cookie in the parent of the current headline.
12354 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12355 the entire subtree and this will travel up the hierarchy and update
12356 statistics everywhere."
12357 (let* ((prop (save-excursion (org-up-heading-safe)
12358 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12359 (recursive (or (not org-hierarchical-todo-statistics)
12360 (and prop (string-match "\\<recursive\\>" prop))))
12361 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12363 (first t)
12364 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12365 level ltoggle l1 new ndel
12366 (cnt-all 0) (cnt-done 0) is-percent kwd
12367 checkbox-beg cookie-present)
12368 (catch 'exit
12369 (save-excursion
12370 (beginning-of-line 1)
12371 (setq ltoggle (funcall outline-level))
12372 ;; Three situations are to consider:
12374 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12375 ;; to the top-level ancestor on the headline;
12377 ;; 2. If parent has "recursive" property, repeat up to the
12378 ;; headline setting that property, taking inheritance into
12379 ;; account;
12381 ;; 3. Else, move up to direct parent and proceed only once.
12382 (while (and (setq level (org-up-heading-safe))
12383 (or recursive first)
12384 (>= (point) lim))
12385 (setq first nil cookie-present nil)
12386 (unless (and level
12387 (not (string-match
12388 "\\<checkbox\\>"
12389 (downcase (or (org-entry-get nil "COOKIE_DATA")
12390 "")))))
12391 (throw 'exit nil))
12392 (while (re-search-forward box-re (point-at-eol) t)
12393 (setq cnt-all 0 cnt-done 0 cookie-present t)
12394 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12395 (save-match-data
12396 (unless (outline-next-heading) (throw 'exit nil))
12397 (while (and (looking-at org-complex-heading-regexp)
12398 (> (setq l1 (length (match-string 1))) level))
12399 (setq kwd (and (or recursive (= l1 ltoggle))
12400 (match-string 2)))
12401 (if (or (eq org-provide-todo-statistics 'all-headlines)
12402 (and (eq org-provide-todo-statistics t)
12403 (or (member kwd org-done-keywords)))
12404 (and (listp org-provide-todo-statistics)
12405 (stringp (car org-provide-todo-statistics))
12406 (or (member kwd org-provide-todo-statistics)
12407 (member kwd org-done-keywords)))
12408 (and (listp org-provide-todo-statistics)
12409 (listp (car org-provide-todo-statistics))
12410 (or (member kwd (car org-provide-todo-statistics))
12411 (and (member kwd org-done-keywords)
12412 (member kwd (cadr org-provide-todo-statistics))))))
12413 (setq cnt-all (1+ cnt-all))
12414 (and (eq org-provide-todo-statistics t)
12416 (setq cnt-all (1+ cnt-all))))
12417 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12418 (member kwd org-done-keywords))
12419 (and (listp org-provide-todo-statistics)
12420 (listp (car org-provide-todo-statistics))
12421 (member kwd org-done-keywords)
12422 (member kwd (cadr org-provide-todo-statistics)))
12423 (and (listp org-provide-todo-statistics)
12424 (stringp (car org-provide-todo-statistics))
12425 (member kwd org-done-keywords)))
12426 (setq cnt-done (1+ cnt-done)))
12427 (outline-next-heading)))
12428 (setq new
12429 (if is-percent
12430 (format "[%d%%]" (floor (* 100.0 cnt-done)
12431 (max 1 cnt-all)))
12432 (format "[%d/%d]" cnt-done cnt-all))
12433 ndel (- (match-end 0) checkbox-beg))
12434 (goto-char checkbox-beg)
12435 (insert new)
12436 (delete-region (point) (+ (point) ndel))
12437 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12438 (when cookie-present
12439 (run-hook-with-args 'org-after-todo-statistics-hook
12440 cnt-done (- cnt-all cnt-done))))))
12441 (run-hooks 'org-todo-statistics-hook)))
12443 (defvar org-after-todo-statistics-hook nil
12444 "Hook that is called after a TODO statistics cookie has been updated.
12445 Each function is called with two arguments: the number of not-done entries
12446 and the number of done entries.
12448 For example, the following function, when added to this hook, will switch
12449 an entry to DONE when all children are done, and back to TODO when new
12450 entries are set to a TODO status. Note that this hook is only called
12451 when there is a statistics cookie in the headline!
12453 (defun org-summary-todo (n-done n-not-done)
12454 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12455 (let (org-log-done org-log-states) ; turn off logging
12456 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12459 (defvar org-todo-statistics-hook nil
12460 "Hook that is run whenever Org thinks TODO statistics should be updated.
12461 This hook runs even if there is no statistics cookie present, in which case
12462 `org-after-todo-statistics-hook' would not run.")
12464 (defun org-todo-trigger-tag-changes (state)
12465 "Apply the changes defined in `org-todo-state-tags-triggers'."
12466 (let ((l org-todo-state-tags-triggers)
12467 changes)
12468 (when (or (not state) (equal state ""))
12469 (setq changes (append changes (cdr (assoc "" l)))))
12470 (when (and (stringp state) (> (length state) 0))
12471 (setq changes (append changes (cdr (assoc state l)))))
12472 (when (member state org-not-done-keywords)
12473 (setq changes (append changes (cdr (assq 'todo l)))))
12474 (when (member state org-done-keywords)
12475 (setq changes (append changes (cdr (assq 'done l)))))
12476 (dolist (c changes)
12477 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12479 (defun org-local-logging (value)
12480 "Get logging settings from a property VALUE."
12481 ;; Directly set the variables, they are already local.
12482 (setq org-log-done nil
12483 org-log-repeat nil
12484 org-todo-log-states nil)
12485 (dolist (w (split-string value))
12486 (let (a)
12487 (cond
12488 ((setq a (assoc w org-startup-options))
12489 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12490 (set (nth 1 a) (nth 2 a))))
12491 ((setq a (org-extract-log-state-settings w))
12492 (and (member (car a) org-todo-keywords-1)
12493 (push a org-todo-log-states)))))))
12495 (defun org-get-todo-sequence-head (kwd)
12496 "Return the head of the TODO sequence to which KWD belongs.
12497 If KWD is not set, check if there is a text property remembering the
12498 right sequence."
12499 (let (p)
12500 (cond
12501 ((not kwd)
12502 (or (get-text-property (point-at-bol) 'org-todo-head)
12503 (progn
12504 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12505 nil (point-at-eol)))
12506 (get-text-property p 'org-todo-head))))
12507 ((not (member kwd org-todo-keywords-1))
12508 (car org-todo-keywords-1))
12509 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12511 (defun org-fast-todo-selection ()
12512 "Fast TODO keyword selection with single keys.
12513 Returns the new TODO keyword, or nil if no state change should occur."
12514 (let* ((fulltable org-todo-key-alist)
12515 (done-keywords org-done-keywords) ;; needed for the faces.
12516 (maxlen (apply 'max (mapcar
12517 (lambda (x)
12518 (if (stringp (car x)) (string-width (car x)) 0))
12519 fulltable)))
12520 (expert nil)
12521 (fwidth (+ maxlen 3 1 3))
12522 (ncol (/ (- (window-width) 4) fwidth))
12523 tg cnt e c tbl
12524 groups ingroup)
12525 (save-excursion
12526 (save-window-excursion
12527 (if expert
12528 (set-buffer (get-buffer-create " *Org todo*"))
12529 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12530 (erase-buffer)
12531 (setq-local org-done-keywords done-keywords)
12532 (setq tbl fulltable cnt 0)
12533 (while (setq e (pop tbl))
12534 (cond
12535 ((equal e '(:startgroup))
12536 (push '() groups) (setq ingroup t)
12537 (unless (= cnt 0)
12538 (setq cnt 0)
12539 (insert "\n"))
12540 (insert "{ "))
12541 ((equal e '(:endgroup))
12542 (setq ingroup nil cnt 0)
12543 (insert "}\n"))
12544 ((equal e '(:newline))
12545 (unless (= cnt 0)
12546 (setq cnt 0)
12547 (insert "\n")
12548 (setq e (car tbl))
12549 (while (equal (car tbl) '(:newline))
12550 (insert "\n")
12551 (setq tbl (cdr tbl)))))
12553 (setq tg (car e) c (cdr e))
12554 (when ingroup (push tg (car groups)))
12555 (setq tg (org-add-props tg nil 'face
12556 (org-get-todo-face tg)))
12557 (when (and (= cnt 0) (not ingroup)) (insert " "))
12558 (insert "[" c "] " tg (make-string
12559 (- fwidth 4 (length tg)) ?\ ))
12560 (when (= (setq cnt (1+ cnt)) ncol)
12561 (insert "\n")
12562 (when ingroup (insert " "))
12563 (setq cnt 0)))))
12564 (insert "\n")
12565 (goto-char (point-min))
12566 (unless expert (org-fit-window-to-buffer))
12567 (message "[a-z..]:Set [SPC]:clear")
12568 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12569 (cond
12570 ((or (= c ?\C-g)
12571 (and (= c ?q) (not (rassoc c fulltable))))
12572 (setq quit-flag t))
12573 ((= c ?\ ) nil)
12574 ((setq e (rassoc c fulltable) tg (car e))
12576 (t (setq quit-flag t)))))))
12578 (defun org-entry-is-todo-p ()
12579 (member (org-get-todo-state) org-not-done-keywords))
12581 (defun org-entry-is-done-p ()
12582 (member (org-get-todo-state) org-done-keywords))
12584 (defun org-get-todo-state ()
12585 "Return the TODO keyword of the current subtree."
12586 (save-excursion
12587 (org-back-to-heading t)
12588 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12589 (match-end 2)
12590 (match-string 2))))
12592 (defun org-at-date-range-p (&optional inactive-ok)
12593 "Non-nil if point is inside a date range.
12595 When optional argument INACTIVE-OK is non-nil, also consider
12596 inactive time ranges.
12598 When this function returns a non-nil value, match data is set
12599 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12600 on INACTIVE-OK."
12601 (interactive)
12602 (save-excursion
12603 (catch 'exit
12604 (let ((pos (point)))
12605 (skip-chars-backward "^[<\r\n")
12606 (skip-chars-backward "<[")
12607 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12608 (>= (match-end 0) pos)
12609 (throw 'exit t))
12610 (skip-chars-backward "^<[\r\n")
12611 (skip-chars-backward "<[")
12612 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12613 (>= (match-end 0) pos)
12614 (throw 'exit t)))
12615 nil)))
12617 (defun org-get-repeat (&optional timestamp)
12618 "Check if there is a time-stamp with repeater in this entry.
12620 Return the repeater, as a string, or nil. Also return nil when
12621 this function is called before first heading.
12623 When optional argument TIMESTAMP is a string, extract the
12624 repeater from there instead."
12625 (save-match-data
12626 (cond (timestamp
12627 (and (string-match org-repeat-re timestamp)
12628 (match-string-no-properties 1 timestamp)))
12629 ((org-before-first-heading-p) nil)
12631 (save-excursion
12632 (org-back-to-heading t)
12633 (let ((end (org-entry-end-position)))
12634 (catch :repeat
12635 (while (re-search-forward org-repeat-re end t)
12636 (when (save-match-data (org-at-timestamp-p 'agenda))
12637 (throw :repeat (match-string-no-properties 1)))))))))))
12639 (defvar org-last-changed-timestamp)
12640 (defvar org-last-inserted-timestamp)
12641 (defvar org-log-post-message)
12642 (defvar org-log-note-purpose)
12643 (defvar org-log-note-how nil)
12644 (defvar org-log-note-extra)
12645 (defun org-auto-repeat-maybe (done-word)
12646 "Check if the current headline contains a repeated time-stamp.
12648 If yes, set TODO state back to what it was and change the base date
12649 of repeating deadline/scheduled time stamps to new date.
12651 This function is run automatically after each state change to a DONE state."
12652 (let* ((repeat (org-get-repeat))
12653 (aa (assoc org-last-state org-todo-kwd-alist))
12654 (interpret (nth 1 aa))
12655 (head (nth 2 aa))
12656 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12657 (msg "Entry repeats: ")
12658 (org-log-done nil)
12659 (org-todo-log-states nil)
12660 (end (copy-marker (org-entry-end-position))))
12661 (unwind-protect
12662 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12663 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12664 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12665 (and (stringp org-todo-repeat-to-state)
12666 org-todo-repeat-to-state)
12667 (and org-todo-repeat-to-state org-last-state))))
12668 (org-todo (cond
12669 ((and to-state (member to-state org-todo-keywords-1))
12670 to-state)
12671 ((eq interpret 'type) org-last-state)
12672 (head)
12673 (t 'none))))
12674 (org-back-to-heading t)
12675 (org-add-planning-info nil nil 'closed)
12676 ;; When `org-log-repeat' is non-nil or entry contains
12677 ;; a clock, set LAST_REPEAT property.
12678 (when (or org-log-repeat
12679 (catch :clock
12680 (save-excursion
12681 (while (re-search-forward org-clock-line-re end t)
12682 (when (org-at-clock-log-p) (throw :clock t))))))
12683 (org-entry-put nil "LAST_REPEAT" (format-time-string
12684 (org-time-stamp-format t t)
12685 (current-time))))
12686 (when org-log-repeat
12687 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12688 (memq 'org-add-log-note post-command-hook))
12689 ;; We are already setup for some record.
12690 (when (eq org-log-repeat 'note)
12691 ;; Make sure we take a note, not only a time stamp.
12692 (setq org-log-note-how 'note))
12693 ;; Set up for taking a record.
12694 (org-add-log-setup 'state
12695 (or done-word (car org-done-keywords))
12696 org-last-state
12697 org-log-repeat)))
12698 (let ((planning-re (regexp-opt
12699 (list org-scheduled-string org-deadline-string))))
12700 (while (re-search-forward org-ts-regexp end t)
12701 (let* ((ts (match-string 0))
12702 (planning? (org-at-planning-p))
12703 (type (if (not planning?) "Plain:"
12704 (save-excursion
12705 (re-search-backward
12706 planning-re (line-beginning-position) t)
12707 (match-string 0)))))
12708 (cond
12709 ;; Ignore fake time-stamps (e.g., within comments).
12710 ((not (org-at-timestamp-p 'agenda)))
12711 ;; Time-stamps without a repeater are usually
12712 ;; skipped. However, a SCHEDULED time-stamp without
12713 ;; one is removed, as they are no longer relevant.
12714 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12715 ts))
12716 (when (equal type org-scheduled-string)
12717 (org-remove-timestamp-with-keyword type)))
12719 (let ((n (string-to-number (match-string 2 ts)))
12720 (what (match-string 3 ts)))
12721 (when (equal what "w") (setq n (* n 7) what "d"))
12722 (when (and (equal what "h")
12723 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12724 ts)))
12725 (user-error
12726 "Cannot repeat in Repeat in %d hour(s) because no hour \
12727 has been set"
12729 ;; Preparation, see if we need to modify the start
12730 ;; date for the change.
12731 (when (match-end 1)
12732 (let ((time (save-match-data
12733 (org-time-string-to-time ts))))
12734 (cond
12735 ((equal (match-string 1 ts) ".")
12736 ;; Shift starting date to today
12737 (org-timestamp-change
12738 (- (org-today) (time-to-days time))
12739 'day))
12740 ((equal (match-string 1 ts) "+")
12741 (let ((nshiftmax 10)
12742 (nshift 0))
12743 (while (or (= nshift 0)
12744 (not (time-less-p (current-time) time)))
12745 (when (= (cl-incf nshift) nshiftmax)
12746 (or (y-or-n-p
12747 (format "%d repeater intervals were not \
12748 enough to shift date past today. Continue? "
12749 nshift))
12750 (user-error "Abort")))
12751 (org-timestamp-change n (cdr (assoc what whata)))
12752 (org-in-regexp org-ts-regexp3)
12753 (setq ts (match-string 1))
12754 (setq time
12755 (save-match-data
12756 (org-time-string-to-time ts)))))
12757 (org-timestamp-change (- n) (cdr (assoc what whata)))
12758 ;; Rematch, so that we have everything in place
12759 ;; for the real shift.
12760 (org-in-regexp org-ts-regexp3)
12761 (setq ts (match-string 1))
12762 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12763 ts)))))
12764 (save-excursion
12765 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12766 (setq msg
12767 (concat
12768 msg type " " org-last-changed-timestamp " "))))))))
12769 (setq org-log-post-message msg)
12770 (message "%s" msg))
12771 (set-marker end nil))))
12773 (defun org-show-todo-tree (arg)
12774 "Make a compact tree which shows all headlines marked with TODO.
12775 The tree will show the lines where the regexp matches, and all higher
12776 headlines above the match.
12777 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12778 With a numeric prefix N, construct a sparse tree for the Nth element
12779 of `org-todo-keywords-1'."
12780 (interactive "P")
12781 (let ((case-fold-search nil)
12782 (kwd-re
12783 (cond ((null arg) org-not-done-regexp)
12784 ((equal arg '(4))
12785 (let ((kwd
12786 (completing-read "Keyword (or KWD1|KWD2|...): "
12787 (mapcar #'list org-todo-keywords-1))))
12788 (concat "\\("
12789 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12790 "\\)\\>")))
12791 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12792 (regexp-quote (nth (1- (prefix-numeric-value arg))
12793 org-todo-keywords-1)))
12794 (t (user-error "Invalid prefix argument: %s" arg)))))
12795 (message "%d TODO entries found"
12796 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12798 (defun org--deadline-or-schedule (arg type time)
12799 "Insert DEADLINE or SCHEDULE information in current entry.
12800 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12801 `org-schedule' for information about ARG and TIME arguments."
12802 (let* ((deadline? (eq type 'deadline))
12803 (keyword (if deadline? org-deadline-string org-scheduled-string))
12804 (log (if deadline? org-log-redeadline org-log-reschedule))
12805 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12806 (old-date-time (and old-date (org-time-string-to-time old-date)))
12807 ;; Save repeater cookie from either TIME or current scheduled
12808 ;; time stamp. We are going to insert it back at the end of
12809 ;; the process.
12810 (repeater (or (and (org-string-nw-p time)
12811 ;; We use `org-repeat-re' because we need
12812 ;; to tell the difference between a real
12813 ;; repeater and a time delta, e.g. "+2d".
12814 (string-match org-repeat-re time)
12815 (match-string 1 time))
12816 (and (org-string-nw-p old-date)
12817 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12818 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12819 old-date)
12820 (match-string 1 old-date)))))
12821 (pcase arg
12822 (`(4)
12823 (when (and old-date log)
12824 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12825 nil old-date log))
12826 (org-remove-timestamp-with-keyword keyword)
12827 (message (if deadline? "Item no longer has a deadline."
12828 "Item is no longer scheduled.")))
12829 (`(16)
12830 (save-excursion
12831 (org-back-to-heading t)
12832 (let ((regexp (if deadline? org-deadline-time-regexp
12833 org-scheduled-time-regexp)))
12834 (if (not (re-search-forward regexp (line-end-position 2) t))
12835 (user-error (if deadline? "No deadline information to update"
12836 "No scheduled information to update"))
12837 (let* ((rpl0 (match-string 1))
12838 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12839 (msg (if deadline? "Warn starting from" "Delay until")))
12840 (replace-match
12841 (concat keyword
12842 " <" rpl
12843 (format " -%dd"
12844 (abs (- (time-to-days
12845 (save-match-data
12846 (org-read-date
12847 nil t nil msg old-date-time)))
12848 (time-to-days old-date-time))))
12849 ">") t t))))))
12851 (org-add-planning-info type time 'closed)
12852 (when (and old-date
12854 (not (equal old-date org-last-inserted-timestamp)))
12855 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12856 org-last-inserted-timestamp
12857 old-date
12858 log))
12859 (when repeater
12860 (save-excursion
12861 (org-back-to-heading t)
12862 (when (re-search-forward
12863 (concat keyword " " org-last-inserted-timestamp)
12864 (line-end-position 2)
12866 (goto-char (1- (match-end 0)))
12867 (insert " " repeater)
12868 (setq org-last-inserted-timestamp
12869 (concat (substring org-last-inserted-timestamp 0 -1)
12870 " " repeater
12871 (substring org-last-inserted-timestamp -1))))))
12872 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12873 org-last-inserted-timestamp)))))
12875 (defun org-deadline (arg &optional time)
12876 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12877 With one universal prefix argument, remove any deadline from the item.
12878 With two universal prefix arguments, prompt for a warning delay.
12879 With argument TIME, set the deadline at the corresponding date. TIME
12880 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12881 (interactive "P")
12882 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12883 (org-map-entries
12884 (lambda () (org--deadline-or-schedule arg 'deadline time))
12886 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12887 'region-start-level
12888 'region)
12889 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12890 (org--deadline-or-schedule arg 'deadline time)))
12892 (defun org-schedule (arg &optional time)
12893 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12894 With one universal prefix argument, remove any scheduling date from the item.
12895 With two universal prefix arguments, prompt for a delay cookie.
12896 With argument TIME, scheduled at the corresponding date. TIME can
12897 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12898 (interactive "P")
12899 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12900 (org-map-entries
12901 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12903 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12904 'region-start-level
12905 'region)
12906 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12907 (org--deadline-or-schedule arg 'scheduled time)))
12909 (defun org-get-scheduled-time (pom &optional inherit)
12910 "Get the scheduled time as a time tuple, of a format suitable
12911 for calling org-schedule with, or if there is no scheduling,
12912 returns nil."
12913 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12914 (when time
12915 (apply 'encode-time (org-parse-time-string time)))))
12917 (defun org-get-deadline-time (pom &optional inherit)
12918 "Get the deadline as a time tuple, of a format suitable for
12919 calling org-deadline with, or if there is no scheduling, returns
12920 nil."
12921 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12922 (when time
12923 (apply 'encode-time (org-parse-time-string time)))))
12925 (defun org-remove-timestamp-with-keyword (keyword)
12926 "Remove all time stamps with KEYWORD in the current entry."
12927 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12928 beg)
12929 (save-excursion
12930 (org-back-to-heading t)
12931 (setq beg (point))
12932 (outline-next-heading)
12933 (while (re-search-backward re beg t)
12934 (replace-match "")
12935 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12936 (equal (char-before) ?\ ))
12937 (backward-delete-char 1)
12938 (when (string-match "^[ \t]*$" (buffer-substring
12939 (point-at-bol) (point-at-eol)))
12940 (delete-region (point-at-bol)
12941 (min (point-max) (1+ (point-at-eol))))))))))
12943 (defvar org-time-was-given) ; dynamically scoped parameter
12944 (defvar org-end-time-was-given) ; dynamically scoped parameter
12946 (defun org-at-planning-p ()
12947 "Non-nil when point is on a planning info line."
12948 ;; This is as accurate and faster than `org-element-at-point' since
12949 ;; planning info location is fixed in the section.
12950 (org-with-wide-buffer
12951 (beginning-of-line)
12952 (and (looking-at-p org-planning-line-re)
12953 (eq (point)
12954 (ignore-errors
12955 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12956 (org-back-to-heading t)
12957 (org-with-limited-levels (org-back-to-heading t)))
12958 (line-beginning-position 2))))))
12960 (defun org-add-planning-info (what &optional time &rest remove)
12961 "Insert new timestamp with keyword in the planning line.
12962 WHAT indicates what kind of time stamp to add. It is a symbol
12963 among `closed', `deadline', `scheduled' and nil. TIME indicates
12964 the time to use. If none is given, the user is prompted for
12965 a date. REMOVE indicates what kind of entries to remove. An old
12966 WHAT entry will also be removed."
12967 (let (org-time-was-given org-end-time-was-given default-time default-input)
12968 (catch 'exit
12969 (when (and (memq what '(scheduled deadline))
12970 (or (not time)
12971 (and (stringp time)
12972 (string-match "^[-+]+[0-9]" time))))
12973 ;; Try to get a default date/time from existing timestamp
12974 (save-excursion
12975 (org-back-to-heading t)
12976 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12977 (when (re-search-forward (if (eq what 'scheduled)
12978 org-scheduled-time-regexp
12979 org-deadline-time-regexp)
12980 end t)
12981 (setq ts (match-string 1)
12982 default-time (apply 'encode-time (org-parse-time-string ts))
12983 default-input (and ts (org-get-compact-tod ts)))))))
12984 (when what
12985 (setq time
12986 (if (stringp time)
12987 ;; This is a string (relative or absolute), set
12988 ;; proper date.
12989 (apply #'encode-time
12990 (org-read-date-analyze
12991 time default-time (decode-time default-time)))
12992 ;; If necessary, get the time from the user
12993 (or time (org-read-date nil 'to-time nil nil
12994 default-time default-input)))))
12996 (org-with-wide-buffer
12997 (org-back-to-heading t)
12998 (forward-line)
12999 (unless (bolp) (insert "\n"))
13000 (cond ((looking-at-p org-planning-line-re)
13001 ;; Move to current indentation.
13002 (skip-chars-forward " \t")
13003 ;; Check if we have to remove something.
13004 (dolist (type (if what (cons what remove) remove))
13005 (save-excursion
13006 (when (re-search-forward
13007 (cl-case type
13008 (closed org-closed-time-regexp)
13009 (deadline org-deadline-time-regexp)
13010 (scheduled org-scheduled-time-regexp)
13011 (otherwise
13012 (error "Invalid planning type: %s" type)))
13013 (line-end-position) t)
13014 ;; Delete until next keyword or end of line.
13015 (delete-region
13016 (match-beginning 0)
13017 (if (re-search-forward org-keyword-time-not-clock-regexp
13018 (line-end-position)
13020 (match-beginning 0)
13021 (line-end-position))))))
13022 ;; If there is nothing more to add and no more keyword
13023 ;; is left, remove the line completely.
13024 (if (and (looking-at-p "[ \t]*$") (not what))
13025 (delete-region (line-beginning-position)
13026 (line-beginning-position 2))
13027 ;; If we removed last keyword, do not leave trailing
13028 ;; white space at the end of line.
13029 (let ((p (point)))
13030 (save-excursion
13031 (end-of-line)
13032 (unless (= (skip-chars-backward " \t" p) 0)
13033 (delete-region (point) (line-end-position)))))))
13034 ((not what) (throw 'exit nil)) ; Nothing to do.
13035 (t (insert-before-markers "\n")
13036 (backward-char 1)
13037 (when org-adapt-indentation
13038 (indent-to-column (1+ (org-outline-level))))))
13039 (when what
13040 ;; Insert planning keyword.
13041 (insert (cl-case what
13042 (closed org-closed-string)
13043 (deadline org-deadline-string)
13044 (scheduled org-scheduled-string)
13045 (otherwise (error "Invalid planning type: %s" what)))
13046 " ")
13047 ;; Insert associated timestamp.
13048 (let ((ts (org-insert-time-stamp
13049 time
13050 (or org-time-was-given
13051 (and (eq what 'closed) org-log-done-with-time))
13052 (eq what 'closed)
13053 nil nil (list org-end-time-was-given))))
13054 (unless (eolp) (insert " "))
13055 ts))))))
13057 (defvar org-log-note-marker (make-marker)
13058 "Marker pointing at the entry where the note is to be inserted.")
13059 (defvar org-log-note-purpose nil)
13060 (defvar org-log-note-state nil)
13061 (defvar org-log-note-previous-state nil)
13062 (defvar org-log-note-extra nil)
13063 (defvar org-log-note-window-configuration nil)
13064 (defvar org-log-note-return-to (make-marker))
13065 (defvar org-log-note-effective-time nil
13066 "Remembered current time so that dynamically scoped
13067 `org-extend-today-until' affects timestamps in state change log")
13069 (defvar org-log-post-message nil
13070 "Message to be displayed after a log note has been stored.
13071 The auto-repeater uses this.")
13073 (defun org-add-note ()
13074 "Add a note to the current entry.
13075 This is done in the same way as adding a state change note."
13076 (interactive)
13077 (org-add-log-setup 'note))
13079 (defun org-log-beginning (&optional create)
13080 "Return expected start of log notes in current entry.
13081 When optional argument CREATE is non-nil, the function creates
13082 a drawer to store notes, if necessary. Returned position ignores
13083 narrowing."
13084 (org-with-wide-buffer
13085 (let ((drawer (org-log-into-drawer)))
13086 (cond
13087 (drawer
13088 (org-end-of-meta-data)
13089 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13090 (end (if (org-at-heading-p) (point)
13091 (save-excursion (outline-next-heading) (point))))
13092 (case-fold-search t))
13093 (catch 'exit
13094 ;; Try to find existing drawer.
13095 (while (re-search-forward regexp end t)
13096 (let ((element (org-element-at-point)))
13097 (when (eq (org-element-type element) 'drawer)
13098 (let ((cend (org-element-property :contents-end element)))
13099 (when (and (not org-log-states-order-reversed) cend)
13100 (goto-char cend)))
13101 (throw 'exit nil))))
13102 ;; No drawer found. Create one, if permitted.
13103 (when create
13104 (unless (bolp) (insert "\n"))
13105 (let ((beg (point)))
13106 (insert ":" drawer ":\n:END:\n")
13107 (org-indent-region beg (point))
13108 (org-flag-region
13109 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13110 (end-of-line -1)))))
13112 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13113 (skip-chars-forward " \t\n")
13114 (beginning-of-line)
13115 (unless org-log-states-order-reversed
13116 (org-skip-over-state-notes)
13117 (skip-chars-backward " \t\n")
13118 (forward-line)))))
13119 (if (bolp) (point) (line-beginning-position 2))))
13121 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13122 "Set up the post command hook to take a note.
13123 If this is about to TODO state change, the new state is expected in STATE.
13124 HOW is an indicator what kind of note should be created.
13125 EXTRA is additional text that will be inserted into the notes buffer."
13126 (move-marker org-log-note-marker (point))
13127 (setq org-log-note-purpose purpose
13128 org-log-note-state state
13129 org-log-note-previous-state prev-state
13130 org-log-note-how how
13131 org-log-note-extra extra
13132 org-log-note-effective-time (org-current-effective-time))
13133 (add-hook 'post-command-hook 'org-add-log-note 'append))
13135 (defun org-skip-over-state-notes ()
13136 "Skip past the list of State notes in an entry."
13137 (when (ignore-errors (goto-char (org-in-item-p)))
13138 (let* ((struct (org-list-struct))
13139 (prevs (org-list-prevs-alist struct))
13140 (regexp
13141 (concat "[ \t]*- +"
13142 (replace-regexp-in-string
13143 " +" " +"
13144 (org-replace-escapes
13145 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13146 `(("%d" . ,org-ts-regexp-inactive)
13147 ("%D" . ,org-ts-regexp)
13148 ("%s" . "\"\\S-+\"")
13149 ("%S" . "\"\\S-+\"")
13150 ("%t" . ,org-ts-regexp-inactive)
13151 ("%T" . ,org-ts-regexp)
13152 ("%u" . ".*?")
13153 ("%U" . ".*?")))))))
13154 (while (looking-at-p regexp)
13155 (goto-char (or (org-list-get-next-item (point) struct prevs)
13156 (org-list-get-item-end (point) struct)))))))
13158 (defun org-add-log-note (&optional _purpose)
13159 "Pop up a window for taking a note, and add this note later."
13160 (remove-hook 'post-command-hook 'org-add-log-note)
13161 (setq org-log-note-window-configuration (current-window-configuration))
13162 (delete-other-windows)
13163 (move-marker org-log-note-return-to (point))
13164 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13165 (goto-char org-log-note-marker)
13166 (org-switch-to-buffer-other-window "*Org Note*")
13167 (erase-buffer)
13168 (if (memq org-log-note-how '(time state))
13169 (org-store-log-note)
13170 (let ((org-inhibit-startup t)) (org-mode))
13171 (insert (format "# Insert note for %s.
13172 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13173 (cond
13174 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13175 ((eq org-log-note-purpose 'done) "closed todo item")
13176 ((eq org-log-note-purpose 'state)
13177 (format "state change from \"%s\" to \"%s\""
13178 (or org-log-note-previous-state "")
13179 (or org-log-note-state "")))
13180 ((eq org-log-note-purpose 'reschedule)
13181 "rescheduling")
13182 ((eq org-log-note-purpose 'delschedule)
13183 "no longer scheduled")
13184 ((eq org-log-note-purpose 'redeadline)
13185 "changing deadline")
13186 ((eq org-log-note-purpose 'deldeadline)
13187 "removing deadline")
13188 ((eq org-log-note-purpose 'refile)
13189 "refiling")
13190 ((eq org-log-note-purpose 'note)
13191 "this entry")
13192 (t (error "This should not happen")))))
13193 (when org-log-note-extra (insert org-log-note-extra))
13194 (setq-local org-finish-function 'org-store-log-note)
13195 (run-hooks 'org-log-buffer-setup-hook)))
13197 (defvar org-note-abort nil) ; dynamically scoped
13198 (defun org-store-log-note ()
13199 "Finish taking a log note, and insert it to where it belongs."
13200 (let ((txt (prog1 (buffer-string)
13201 (kill-buffer)))
13202 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13203 lines)
13204 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13205 (setq txt (replace-match "" t t txt)))
13206 (when (string-match "\\s-+\\'" txt)
13207 (setq txt (replace-match "" t t txt)))
13208 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13209 (when (org-string-nw-p note)
13210 (setq note
13211 (org-replace-escapes
13212 note
13213 (list (cons "%u" (user-login-name))
13214 (cons "%U" user-full-name)
13215 (cons "%t" (format-time-string
13216 (org-time-stamp-format 'long 'inactive)
13217 org-log-note-effective-time))
13218 (cons "%T" (format-time-string
13219 (org-time-stamp-format 'long nil)
13220 org-log-note-effective-time))
13221 (cons "%d" (format-time-string
13222 (org-time-stamp-format nil 'inactive)
13223 org-log-note-effective-time))
13224 (cons "%D" (format-time-string
13225 (org-time-stamp-format nil nil)
13226 org-log-note-effective-time))
13227 (cons "%s" (cond
13228 ((not org-log-note-state) "")
13229 ((string-match-p org-ts-regexp
13230 org-log-note-state)
13231 (format "\"[%s]\""
13232 (substring org-log-note-state 1 -1)))
13233 (t (format "\"%s\"" org-log-note-state))))
13234 (cons "%S"
13235 (cond
13236 ((not org-log-note-previous-state) "")
13237 ((string-match-p org-ts-regexp
13238 org-log-note-previous-state)
13239 (format "\"[%s]\""
13240 (substring
13241 org-log-note-previous-state 1 -1)))
13242 (t (format "\"%s\""
13243 org-log-note-previous-state)))))))
13244 (when lines (setq note (concat note " \\\\")))
13245 (push note lines))
13246 (when (and lines (not org-note-abort))
13247 (with-current-buffer (marker-buffer org-log-note-marker)
13248 (org-with-wide-buffer
13249 ;; Find location for the new note.
13250 (goto-char org-log-note-marker)
13251 (set-marker org-log-note-marker nil)
13252 ;; Note associated to a clock is to be located right after
13253 ;; the clock. Do not move point.
13254 (unless (eq org-log-note-purpose 'clock-out)
13255 (goto-char (org-log-beginning t)))
13256 ;; Make sure point is at the beginning of an empty line.
13257 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13258 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13259 ;; In an existing list, add a new item at the top level.
13260 ;; Otherwise, indent line like a regular one.
13261 (let ((itemp (org-in-item-p)))
13262 (if itemp
13263 (indent-line-to
13264 (let ((struct (save-excursion
13265 (goto-char itemp) (org-list-struct))))
13266 (org-list-get-ind (org-list-get-top-point struct) struct)))
13267 (org-indent-line)))
13268 (insert (org-list-bullet-string "-") (pop lines))
13269 (let ((ind (org-list-item-body-column (line-beginning-position))))
13270 (dolist (line lines)
13271 (insert "\n")
13272 (indent-line-to ind)
13273 (insert line)))
13274 (message "Note stored")
13275 (org-back-to-heading t))
13276 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13277 ;; from within `org-add-log-note' because `buffer-undo-list'
13278 ;; is then modified outside of `org-with-remote-undo'.
13279 (when (eq this-command 'org-agenda-todo)
13280 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13281 ;; Don't add undo information when called from `org-agenda-todo'.
13282 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13283 (set-window-configuration org-log-note-window-configuration)
13284 (with-current-buffer (marker-buffer org-log-note-return-to)
13285 (goto-char org-log-note-return-to))
13286 (move-marker org-log-note-return-to nil)
13287 (when org-log-post-message (message "%s" org-log-post-message))))
13289 (defun org-remove-empty-drawer-at (pos)
13290 "Remove an empty drawer at position POS.
13291 POS may also be a marker."
13292 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13293 (org-with-wide-buffer
13294 (goto-char pos)
13295 (let ((drawer (org-element-at-point)))
13296 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13297 (not (org-element-property :contents-begin drawer)))
13298 (delete-region (org-element-property :begin drawer)
13299 (progn (goto-char (org-element-property :end drawer))
13300 (skip-chars-backward " \r\t\n")
13301 (forward-line)
13302 (point))))))))
13304 (defvar org-ts-type nil)
13305 (defun org-sparse-tree (&optional arg type)
13306 "Create a sparse tree, prompt for the details.
13307 This command can create sparse trees. You first need to select the type
13308 of match used to create the tree:
13310 t Show all TODO entries.
13311 T Show entries with a specific TODO keyword.
13312 m Show entries selected by a tags/property match.
13313 p Enter a property name and its value (both with completion on existing
13314 names/values) and show entries with that property.
13315 r Show entries matching a regular expression (`/' can be used as well).
13316 b Show deadlines and scheduled items before a date.
13317 a Show deadlines and scheduled items after a date.
13318 d Show deadlines due within `org-deadline-warning-days'.
13319 D Show deadlines and scheduled items between a date range."
13320 (interactive "P")
13321 (setq type (or type org-sparse-tree-default-date-type))
13322 (setq org-ts-type type)
13323 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13324 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13325 \[c]ycle through date types: %s"
13326 (cl-case type
13327 (all "all timestamps")
13328 (scheduled "only scheduled")
13329 (deadline "only deadline")
13330 (active "only active timestamps")
13331 (inactive "only inactive timestamps")
13332 (closed "with a closed time-stamp")
13333 (otherwise "scheduled/deadline")))
13334 (let ((answer (read-char-exclusive)))
13335 (cl-case answer
13337 (org-sparse-tree
13339 (cadr
13340 (memq type '(nil all scheduled deadline active inactive closed)))))
13341 (?d (call-interactively 'org-check-deadlines))
13342 (?b (call-interactively 'org-check-before-date))
13343 (?a (call-interactively 'org-check-after-date))
13344 (?D (call-interactively 'org-check-dates-range))
13345 (?t (call-interactively 'org-show-todo-tree))
13346 (?T (org-show-todo-tree '(4)))
13347 (?m (call-interactively 'org-match-sparse-tree))
13348 ((?p ?P)
13349 (let* ((kwd (completing-read
13350 "Property: " (mapcar #'list (org-buffer-property-keys))))
13351 (value (completing-read
13352 "Value: " (mapcar #'list (org-property-values kwd)))))
13353 (unless (string-match "\\`{.*}\\'" value)
13354 (setq value (concat "\"" value "\"")))
13355 (org-match-sparse-tree arg (concat kwd "=" value))))
13356 ((?r ?R ?/) (call-interactively 'org-occur))
13357 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13359 (defvar-local org-occur-highlights nil
13360 "List of overlays used for occur matches.")
13361 (defvar-local org-occur-parameters nil
13362 "Parameters of the active org-occur calls.
13363 This is a list, each call to org-occur pushes as cons cell,
13364 containing the regular expression and the callback, onto the list.
13365 The list can contain several entries if `org-occur' has been called
13366 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13367 will only contain one set of parameters. When the highlights are
13368 removed (for example with `C-c C-c', or with the next edit (depending
13369 on `org-remove-highlights-with-change'), this variable is emptied
13370 as well.")
13372 (defun org-occur (regexp &optional keep-previous callback)
13373 "Make a compact tree which shows all matches of REGEXP.
13375 The tree will show the lines where the regexp matches, and any other context
13376 defined in `org-show-context-detail', which see.
13378 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13379 done by a previous call to `org-occur' will be kept, to allow stacking of
13380 calls to this command.
13382 Optional argument CALLBACK can be a function of no argument. In this case,
13383 it is called with point at the end of the match, match data being set
13384 accordingly. Current match is shown only if the return value is non-nil.
13385 The function must neither move point nor alter narrowing."
13386 (interactive "sRegexp: \nP")
13387 (when (equal regexp "")
13388 (user-error "Regexp cannot be empty"))
13389 (unless keep-previous
13390 (org-remove-occur-highlights nil nil t))
13391 (push (cons regexp callback) org-occur-parameters)
13392 (let ((cnt 0))
13393 (save-excursion
13394 (goto-char (point-min))
13395 (when (or (not keep-previous) ; do not want to keep
13396 (not org-occur-highlights)) ; no previous matches
13397 ;; hide everything
13398 (org-overview))
13399 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13400 (isearch-no-upper-case-p regexp t)
13401 org-occur-case-fold-search)))
13402 (while (re-search-forward regexp nil t)
13403 (when (or (not callback)
13404 (save-match-data (funcall callback)))
13405 (setq cnt (1+ cnt))
13406 (when org-highlight-sparse-tree-matches
13407 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13408 (org-show-context 'occur-tree)))))
13409 (when org-remove-highlights-with-change
13410 (add-hook 'before-change-functions 'org-remove-occur-highlights
13411 nil 'local))
13412 (unless org-sparse-tree-open-archived-trees
13413 (org-hide-archived-subtrees (point-min) (point-max)))
13414 (run-hooks 'org-occur-hook)
13415 (when (called-interactively-p 'interactive)
13416 (message "%d match(es) for regexp %s" cnt regexp))
13417 cnt))
13419 (defun org-occur-next-match (&optional n _reset)
13420 "Function for `next-error-function' to find sparse tree matches.
13421 N is the number of matches to move, when negative move backwards.
13422 This function always goes back to the starting point when no
13423 match is found."
13424 (let* ((limit (if (< n 0) (point-min) (point-max)))
13425 (search-func (if (< n 0)
13426 'previous-single-char-property-change
13427 'next-single-char-property-change))
13428 (n (abs n))
13429 (pos (point))
13431 (catch 'exit
13432 (while (setq p1 (funcall search-func (point) 'org-type))
13433 (when (equal p1 limit)
13434 (goto-char pos)
13435 (user-error "No more matches"))
13436 (when (equal (get-char-property p1 'org-type) 'org-occur)
13437 (setq n (1- n))
13438 (when (= n 0)
13439 (goto-char p1)
13440 (throw 'exit (point))))
13441 (goto-char p1))
13442 (goto-char p1)
13443 (user-error "No more matches"))))
13445 (defun org-highlight-new-match (beg end)
13446 "Highlight from BEG to END and mark the highlight is an occur headline."
13447 (let ((ov (make-overlay beg end)))
13448 (overlay-put ov 'face 'secondary-selection)
13449 (overlay-put ov 'org-type 'org-occur)
13450 (push ov org-occur-highlights)))
13452 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13453 "Remove the occur highlights from the buffer.
13454 BEG and END are ignored. If NOREMOVE is nil, remove this function
13455 from the `before-change-functions' in the current buffer."
13456 (interactive)
13457 (unless org-inhibit-highlight-removal
13458 (mapc #'delete-overlay org-occur-highlights)
13459 (setq org-occur-highlights nil)
13460 (setq org-occur-parameters nil)
13461 (unless noremove
13462 (remove-hook 'before-change-functions
13463 'org-remove-occur-highlights 'local))))
13465 ;;;; Priorities
13467 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13468 "Regular expression matching the priority indicator.")
13470 (defvar org-remove-priority-next-time nil)
13472 (defun org-priority-up ()
13473 "Increase the priority of the current item."
13474 (interactive)
13475 (org-priority 'up))
13477 (defun org-priority-down ()
13478 "Decrease the priority of the current item."
13479 (interactive)
13480 (org-priority 'down))
13482 (defun org-priority (&optional action _show)
13483 "Change the priority of an item.
13484 ACTION can be `set', `up', `down', or a character."
13485 (interactive "P")
13486 (if (equal action '(4))
13487 (org-show-priority)
13488 (unless org-enable-priority-commands
13489 (user-error "Priority commands are disabled"))
13490 (setq action (or action 'set))
13491 (let (current new news have remove)
13492 (save-excursion
13493 (org-back-to-heading t)
13494 (when (looking-at org-priority-regexp)
13495 (setq current (string-to-char (match-string 2))
13496 have t))
13497 (cond
13498 ((eq action 'remove)
13499 (setq remove t new ?\ ))
13500 ((or (eq action 'set)
13501 (integerp action))
13502 (if (not (eq action 'set))
13503 (setq new action)
13504 (message "Priority %c-%c, SPC to remove: "
13505 org-highest-priority org-lowest-priority)
13506 (save-match-data
13507 (setq new (read-char-exclusive))))
13508 (when (and (= (upcase org-highest-priority) org-highest-priority)
13509 (= (upcase org-lowest-priority) org-lowest-priority))
13510 (setq new (upcase new)))
13511 (cond ((equal new ?\ ) (setq remove t))
13512 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13513 (user-error "Priority must be between `%c' and `%c'"
13514 org-highest-priority org-lowest-priority))))
13515 ((eq action 'up)
13516 (setq new (if have
13517 (1- current) ; normal cycling
13518 ;; last priority was empty
13519 (if (eq last-command this-command)
13520 org-lowest-priority ; wrap around empty to lowest
13521 ;; default
13522 (if org-priority-start-cycle-with-default
13523 org-default-priority
13524 (1- org-default-priority))))))
13525 ((eq action 'down)
13526 (setq new (if have
13527 (1+ current) ; normal cycling
13528 ;; last priority was empty
13529 (if (eq last-command this-command)
13530 org-highest-priority ; wrap around empty to highest
13531 ;; default
13532 (if org-priority-start-cycle-with-default
13533 org-default-priority
13534 (1+ org-default-priority))))))
13535 (t (user-error "Invalid action")))
13536 (when (or (< (upcase new) org-highest-priority)
13537 (> (upcase new) org-lowest-priority))
13538 (if (and (memq action '(up down))
13539 (not have) (not (eq last-command this-command)))
13540 ;; `new' is from default priority
13541 (error
13542 "The default can not be set, see `org-default-priority' why")
13543 ;; normal cycling: `new' is beyond highest/lowest priority
13544 ;; and is wrapped around to the empty priority
13545 (setq remove t)))
13546 (setq news (format "%c" new))
13547 (if have
13548 (if remove
13549 (replace-match "" t t nil 1)
13550 (replace-match news t t nil 2))
13551 (if remove
13552 (user-error "No priority cookie found in line")
13553 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13554 (if (match-end 2)
13555 (progn
13556 (goto-char (match-end 2))
13557 (insert " [#" news "]"))
13558 (goto-char (match-beginning 3))
13559 (insert "[#" news "] "))))
13560 (org-set-tags nil 'align))
13561 (if remove
13562 (message "Priority removed")
13563 (message "Priority of current item set to %s" news)))))
13565 (defun org-show-priority ()
13566 "Show the priority of the current item.
13567 This priority is composed of the main priority given with the [#A] cookies,
13568 and by additional input from the age of a schedules or deadline entry."
13569 (interactive)
13570 (let ((pri (if (eq major-mode 'org-agenda-mode)
13571 (org-get-at-bol 'priority)
13572 (save-excursion
13573 (save-match-data
13574 (beginning-of-line)
13575 (and (looking-at org-heading-regexp)
13576 (org-get-priority (match-string 0))))))))
13577 (message "Priority is %d" (if pri pri -1000))))
13579 (defun org-get-priority (s)
13580 "Find priority cookie and return priority."
13581 (save-match-data
13582 (if (functionp org-get-priority-function)
13583 (funcall org-get-priority-function)
13584 (if (not (string-match org-priority-regexp s))
13585 (* 1000 (- org-lowest-priority org-default-priority))
13586 (* 1000 (- org-lowest-priority
13587 (string-to-char (match-string 2 s))))))))
13589 ;;;; Tags
13591 (defvar org-agenda-archives-mode)
13592 (defvar org-map-continue-from nil
13593 "Position from where mapping should continue.
13594 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13596 (defvar org-scanner-tags nil
13597 "The current tag list while the tags scanner is running.")
13599 (defvar org-trust-scanner-tags nil
13600 "Should `org-get-tags' use the tags for the scanner.
13601 This is for internal dynamical scoping only.
13602 When this is non-nil, the function `org-get-tags' will return the value
13603 of `org-scanner-tags' instead of building the list by itself. This
13604 can lead to large speed-ups when the tags scanner is used in a file with
13605 many entries, and when the list of tags is retrieved, for example to
13606 obtain a list of properties. Building the tags list for each entry in such
13607 a file becomes an N^2 operation - but with this variable set, it scales
13608 as N.")
13610 (defvar org--matcher-tags-todo-only nil)
13612 (defun org-scan-tags (action matcher todo-only &optional start-level)
13613 "Scan headline tags with inheritance and produce output ACTION.
13615 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13616 or `agenda' to produce an entry list for an agenda view. It can also be
13617 a Lisp form or a function that should be called at each matched headline, in
13618 this case the return value is a list of all return values from these calls.
13620 MATCHER is a function accepting three arguments, returning
13621 a non-nil value whenever a given set of tags qualifies a headline
13622 for inclusion. See `org-make-tags-matcher' for more information.
13623 As a special case, it can also be set to t (respectively nil) in
13624 order to match all (respectively none) headline.
13626 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13627 included in the output.
13629 START-LEVEL can be a string with asterisks, reducing the scope to
13630 headlines matching this string."
13631 (require 'org-agenda)
13632 (let* ((re (concat "^"
13633 (if start-level
13634 ;; Get the correct level to match
13635 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13636 org-outline-regexp)
13637 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13638 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13639 (props (list 'face 'default
13640 'done-face 'org-agenda-done
13641 'undone-face 'default
13642 'mouse-face 'highlight
13643 'org-not-done-regexp org-not-done-regexp
13644 'org-todo-regexp org-todo-regexp
13645 'org-complex-heading-regexp org-complex-heading-regexp
13646 'help-echo
13647 (format "mouse-2 or RET jump to Org file %S"
13648 (abbreviate-file-name
13649 (or (buffer-file-name (buffer-base-buffer))
13650 (buffer-name (buffer-base-buffer)))))))
13651 (org-map-continue-from nil)
13652 lspos tags tags-list
13653 (tags-alist (list (cons 0 org-file-tags)))
13654 (llast 0) rtn rtn1 level category i txt
13655 todo marker entry priority
13656 ts-date ts-date-type ts-date-pair)
13657 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13658 (setq action (list 'lambda nil action)))
13659 (save-excursion
13660 (goto-char (point-min))
13661 (when (eq action 'sparse-tree)
13662 (org-overview)
13663 (org-remove-occur-highlights))
13664 (while (let (case-fold-search)
13665 (re-search-forward re nil t))
13666 (setq org-map-continue-from nil)
13667 (catch :skip
13668 ;; Ignore closing parts of inline tasks.
13669 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13670 (throw :skip t))
13671 (setq todo
13672 ;; TODO: is the 1-2 difference a bug?
13673 (when (match-end 1) (match-string-no-properties 2))
13674 tags (when (match-end 4) (match-string-no-properties 4)))
13675 (goto-char (setq lspos (match-beginning 0)))
13676 (setq level (org-reduced-level (org-outline-level))
13677 category (org-get-category))
13678 (when (eq action 'agenda)
13679 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13680 ts-date (car ts-date-pair)
13681 ts-date-type (cdr ts-date-pair)))
13682 (setq i llast llast level)
13683 ;; remove tag lists from same and sublevels
13684 (while (>= i level)
13685 (when (setq entry (assoc i tags-alist))
13686 (setq tags-alist (delete entry tags-alist)))
13687 (setq i (1- i)))
13688 ;; add the next tags
13689 (when tags
13690 (setq tags (org-split-string tags ":")
13691 tags-alist
13692 (cons (cons level tags) tags-alist)))
13693 ;; compile tags for current headline
13694 (setq tags-list
13695 (if org-use-tag-inheritance
13696 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13697 tags)
13698 org-scanner-tags tags-list)
13699 (when org-use-tag-inheritance
13700 (setcdr (car tags-alist)
13701 (mapcar (lambda (x)
13702 (setq x (copy-sequence x))
13703 (org-add-prop-inherited x))
13704 (cdar tags-alist))))
13705 (when (and tags org-use-tag-inheritance
13706 (or (not (eq t org-use-tag-inheritance))
13707 org-tags-exclude-from-inheritance))
13708 ;; Selective inheritance, remove uninherited ones.
13709 (setcdr (car tags-alist)
13710 (org-remove-uninherited-tags (cdar tags-alist))))
13711 (when (and
13713 ;; eval matcher only when the todo condition is OK
13714 (and (or (not todo-only) (member todo org-todo-keywords-1))
13715 (if (functionp matcher)
13716 (let ((case-fold-search t) (org-trust-scanner-tags t))
13717 (funcall matcher todo tags-list level))
13718 matcher))
13720 ;; Call the skipper, but return t if it does not
13721 ;; skip, so that the `and' form continues evaluating.
13722 (progn
13723 (unless (eq action 'sparse-tree) (org-agenda-skip))
13726 ;; Check if timestamps are deselecting this entry
13727 (or (not todo-only)
13728 (and (member todo org-todo-keywords-1)
13729 (or (not org-agenda-tags-todo-honor-ignore-options)
13730 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13732 ;; select this headline
13733 (cond
13734 ((eq action 'sparse-tree)
13735 (and org-highlight-sparse-tree-matches
13736 (org-get-heading) (match-end 0)
13737 (org-highlight-new-match
13738 (match-beginning 1) (match-end 1)))
13739 (org-show-context 'tags-tree))
13740 ((eq action 'agenda)
13741 (setq txt (org-agenda-format-item
13743 (concat
13744 (if (eq org-tags-match-list-sublevels 'indented)
13745 (make-string (1- level) ?.) "")
13746 (org-get-heading))
13747 (make-string level ?\s)
13748 category
13749 tags-list)
13750 priority (org-get-priority txt))
13751 (goto-char lspos)
13752 (setq marker (org-agenda-new-marker))
13753 (org-add-props txt props
13754 'org-marker marker 'org-hd-marker marker 'org-category category
13755 'todo-state todo
13756 'ts-date ts-date
13757 'priority priority
13758 'type (concat "tagsmatch" ts-date-type))
13759 (push txt rtn))
13760 ((functionp action)
13761 (setq org-map-continue-from nil)
13762 (save-excursion
13763 (setq rtn1 (funcall action))
13764 (push rtn1 rtn)))
13765 (t (user-error "Invalid action")))
13767 ;; if we are to skip sublevels, jump to end of subtree
13768 (unless org-tags-match-list-sublevels
13769 (org-end-of-subtree t)
13770 (backward-char 1))))
13771 ;; Get the correct position from where to continue
13772 (if org-map-continue-from
13773 (goto-char org-map-continue-from)
13774 (and (= (point) lspos) (end-of-line 1)))))
13775 (when (and (eq action 'sparse-tree)
13776 (not org-sparse-tree-open-archived-trees))
13777 (org-hide-archived-subtrees (point-min) (point-max)))
13778 (nreverse rtn)))
13780 (defun org-remove-uninherited-tags (tags)
13781 "Remove all tags that are not inherited from the list TAGS."
13782 (cond
13783 ((eq org-use-tag-inheritance t)
13784 (if org-tags-exclude-from-inheritance
13785 (org-delete-all org-tags-exclude-from-inheritance tags)
13786 tags))
13787 ((not org-use-tag-inheritance) nil)
13788 ((stringp org-use-tag-inheritance)
13789 (delq nil (mapcar
13790 (lambda (x)
13791 (if (and (string-match org-use-tag-inheritance x)
13792 (not (member x org-tags-exclude-from-inheritance)))
13793 x nil))
13794 tags)))
13795 ((listp org-use-tag-inheritance)
13796 (delq nil (mapcar
13797 (lambda (x)
13798 (if (member x org-use-tag-inheritance) x nil))
13799 tags)))))
13801 (defun org-match-sparse-tree (&optional todo-only match)
13802 "Create a sparse tree according to tags string MATCH.
13804 MATCH is a string with match syntax. It can contain a selection
13805 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13806 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13807 those. See the manual for details.
13809 If optional argument TODO-ONLY is non-nil, only select lines that
13810 are also TODO tasks."
13811 (interactive "P")
13812 (org-agenda-prepare-buffers (list (current-buffer)))
13813 (let ((org--matcher-tags-todo-only todo-only))
13814 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13815 org--matcher-tags-todo-only)))
13817 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13819 (defvar org-cached-props nil)
13820 (defun org-cached-entry-get (pom property)
13821 (if (or (eq t org-use-property-inheritance)
13822 (and (stringp org-use-property-inheritance)
13823 (let ((case-fold-search t))
13824 (string-match-p org-use-property-inheritance property)))
13825 (and (listp org-use-property-inheritance)
13826 (member-ignore-case property org-use-property-inheritance)))
13827 ;; Caching is not possible, check it directly.
13828 (org-entry-get pom property 'inherit)
13829 ;; Get all properties, so we can do complicated checks easily.
13830 (cdr (assoc-string property
13831 (or org-cached-props
13832 (setq org-cached-props (org-entry-properties pom)))
13833 t))))
13835 (defun org-global-tags-completion-table (&optional files)
13836 "Return the list of all tags in all agenda buffer/files.
13837 Optional FILES argument is a list of files which can be used
13838 instead of the agenda files."
13839 (save-excursion
13840 (org-uniquify
13841 (delq nil
13842 (apply #'append
13843 (mapcar
13844 (lambda (file)
13845 (set-buffer (find-file-noselect file))
13846 (org-tag-add-to-alist
13847 (org-get-buffer-tags)
13848 (mapcar (lambda (x)
13849 (and (stringp (car-safe x))
13850 (list (car-safe x))))
13851 org-current-tag-alist)))
13852 (if (car-safe files) files
13853 (org-agenda-files))))))))
13855 (defun org-make-tags-matcher (match)
13856 "Create the TAGS/TODO matcher form for the selection string MATCH.
13858 Returns a cons of the selection string MATCH and a function
13859 implementing the matcher.
13861 The matcher is to be called at an Org entry, with point on the
13862 headline, and returns non-nil if the entry matches the selection
13863 string MATCH. It must be called with three arguments: the TODO
13864 keyword at the entry (or nil if none), the list of all tags at
13865 the entry including inherited ones and the reduced level of the
13866 headline. Additionally, the category of the entry, if any, must
13867 be specified as the text property `org-category' on the headline.
13869 This function sets the variable `org--matcher-tags-todo-only' to
13870 a non-nil value if the matcher restricts matching to TODO
13871 entries, otherwise it is not touched.
13873 See also `org-scan-tags'."
13874 (unless match
13875 ;; Get a new match request, with completion against the global
13876 ;; tags table and the local tags in current buffer.
13877 (let ((org-last-tags-completion-table
13878 (org-tag-add-to-alist
13879 (org-get-buffer-tags)
13880 (org-global-tags-completion-table))))
13881 (setq match
13882 (completing-read
13883 "Match: "
13884 'org-tags-completion-function nil nil nil 'org-tags-history))))
13886 (let ((match0 match)
13887 (re (concat
13888 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13889 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13890 "\\([<>=]\\{1,2\\}\\)"
13891 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13892 "\\|" org-tag-re "\\)"))
13893 (start 0)
13894 tagsmatch todomatch tagsmatcher todomatcher)
13896 ;; Expand group tags.
13897 (setq match (org-tags-expand match))
13899 ;; Check if there is a TODO part of this match, which would be the
13900 ;; part after a "/". To make sure that this slash is not part of
13901 ;; a property value to be matched against, we also check that
13902 ;; there is no / after that slash. First, find the last slash.
13903 (let ((s 0))
13904 (while (string-match "/+" match s)
13905 (setq start (match-beginning 0))
13906 (setq s (match-end 0))))
13907 (if (and (string-match "/+" match start)
13908 (not (string-match-p "\"" match start)))
13909 ;; Match contains also a TODO-matching request.
13910 (progn
13911 (setq tagsmatch (substring match 0 (match-beginning 0)))
13912 (setq todomatch (substring match (match-end 0)))
13913 (when (string-prefix-p "!" todomatch)
13914 (setq org--matcher-tags-todo-only t)
13915 (setq todomatch (substring todomatch 1)))
13916 (when (string-match "\\`\\s-*\\'" todomatch)
13917 (setq todomatch nil)))
13918 ;; Only matching tags.
13919 (setq tagsmatch match)
13920 (setq todomatch nil))
13922 ;; Make the tags matcher.
13923 (when (org-string-nw-p tagsmatch)
13924 (let ((orlist nil)
13925 (orterms (org-split-string tagsmatch "|"))
13926 term)
13927 (while (setq term (pop orterms))
13928 (while (and (equal (substring term -1) "\\") orterms)
13929 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13930 (while (string-match re term)
13931 (let* ((rest (substring term (match-end 0)))
13932 (minus (and (match-end 1)
13933 (equal (match-string 1 term) "-")))
13934 (tag (save-match-data
13935 (replace-regexp-in-string
13936 "\\\\-" "-" (match-string 2 term))))
13937 (regexp (eq (string-to-char tag) ?{))
13938 (levelp (match-end 4))
13939 (propp (match-end 5))
13941 (cond
13942 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13943 (levelp
13944 `(,(org-op-to-function (match-string 3 term))
13945 level
13946 ,(string-to-number (match-string 4 term))))
13947 (propp
13948 (let* ((gv (pcase (upcase (match-string 5 term))
13949 ("CATEGORY"
13950 '(get-text-property (point) 'org-category))
13951 ("TODO" 'todo)
13952 (p `(org-cached-entry-get nil ,p))))
13953 (pv (match-string 7 term))
13954 (regexp (eq (string-to-char pv) ?{))
13955 (strp (eq (string-to-char pv) ?\"))
13956 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13957 (po (org-op-to-function (match-string 6 term)
13958 (if timep 'time strp))))
13959 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13960 (when timep (setq pv (org-matcher-time pv)))
13961 (cond ((and regexp (eq po '/=))
13962 `(not (string-match ,pv (or ,gv ""))))
13963 (regexp `(string-match ,pv (or ,gv "")))
13964 (strp `(,po (or ,gv "") ,pv))
13966 `(,po
13967 (string-to-number (or ,gv ""))
13968 ,(string-to-number pv))))))
13969 (t `(member ,tag tags-list)))))
13970 (push (if minus `(not ,mm) mm) tagsmatcher)
13971 (setq term rest)))
13972 (push `(and ,@tagsmatcher) orlist)
13973 (setq tagsmatcher nil))
13974 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13976 ;; Make the TODO matcher.
13977 (when (org-string-nw-p todomatch)
13978 (let ((orlist nil))
13979 (dolist (term (org-split-string todomatch "|"))
13980 (while (string-match re term)
13981 (let* ((minus (and (match-end 1)
13982 (equal (match-string 1 term) "-")))
13983 (kwd (match-string 2 term))
13984 (regexp (eq (string-to-char kwd) ?{))
13985 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13986 `(equal todo ,kwd))))
13987 (push (if minus `(not ,mm) mm) todomatcher))
13988 (setq term (substring term (match-end 0))))
13989 (push (if (> (length todomatcher) 1)
13990 (cons 'and todomatcher)
13991 (car todomatcher))
13992 orlist)
13993 (setq todomatcher nil))
13994 (setq todomatcher (cons 'or orlist))))
13996 ;; Return the string and function of the matcher. If no
13997 ;; tags-specific or todo-specific matcher exists, match
13998 ;; everything.
13999 (let ((matcher (if (and tagsmatcher todomatcher)
14000 `(and ,tagsmatcher ,todomatcher)
14001 (or tagsmatcher todomatcher t))))
14002 (when org--matcher-tags-todo-only
14003 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14004 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14006 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14007 "Expand group tags in MATCH.
14009 This replaces every group tag in MATCH with a regexp tag search.
14010 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14011 will be replaced like this:
14013 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14014 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14015 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14017 Replacing by a regexp preserves the structure of the match.
14018 E.g., this expansion
14020 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14022 will match anything tagged with \"Lab\" and \"Home\", or tagged
14023 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14025 A group tag in MATCH can contain regular expressions of its own.
14026 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14027 will be replaced like this:
14029 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14031 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14032 assumed to be a single group tag, and the function will return
14033 the list of tags in this group.
14035 When DOWNCASE is non-nil, expand downcased TAGS."
14036 (if org-group-tags
14037 (let* ((case-fold-search t)
14038 (stable org-mode-syntax-table)
14039 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14040 (taggroups (if downcased
14041 (mapcar (lambda (tg) (mapcar #'downcase tg))
14042 taggroups)
14043 taggroups))
14044 (taggroups-keys (mapcar #'car taggroups))
14045 (return-match (if downcased (downcase match) match))
14046 (count 0)
14047 (work-already-expanded tags-already-expanded)
14048 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14049 ;; @ and _ are allowed as word-components in tags.
14050 (modify-syntax-entry ?@ "w" stable)
14051 (modify-syntax-entry ?_ "w" stable)
14052 ;; Temporarily replace regexp-expressions in the match-expression.
14053 (while (string-match "{.+?}" return-match)
14054 (cl-incf count)
14055 (push (match-string 0 return-match) regexps-in-match)
14056 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14057 (while (and taggroups-keys
14058 (with-syntax-table stable
14059 (string-match
14060 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14061 (regexp-opt taggroups-keys) "\\>\\)")
14062 return-match)))
14063 (let* ((dir (match-string 1 return-match))
14064 (tag (match-string 2 return-match))
14065 (tag (if downcased (downcase tag) tag)))
14066 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14067 (member tag tags-already-expanded))
14068 (setq tags-in-group (assoc tag taggroups))
14069 (push tag work-already-expanded)
14070 ;; Recursively expand each tag in the group, if the tag hasn't
14071 ;; already been expanded. Restore the match-data after all recursive calls.
14072 (save-match-data
14073 (let (tags-expanded)
14074 (dolist (x (cdr tags-in-group))
14075 (if (and (member x taggroups-keys)
14076 (not (member x work-already-expanded)))
14077 (setq tags-expanded
14078 (delete-dups
14079 (append
14080 (org-tags-expand x t downcased
14081 work-already-expanded)
14082 tags-expanded)))
14083 (setq tags-expanded
14084 (append (list x) tags-expanded)))
14085 (setq work-already-expanded
14086 (delete-dups
14087 (append tags-expanded
14088 work-already-expanded))))
14089 (setq tags-in-group
14090 (delete-dups (cons (car tags-in-group)
14091 tags-expanded)))))
14092 ;; Filter tag-regexps from tags.
14093 (setq regexp-in-group-escaped
14094 (delq nil (mapcar (lambda (x)
14095 (if (stringp x)
14096 (and (equal "{" (substring x 0 1))
14097 (equal "}" (substring x -1))
14100 tags-in-group))
14101 regexp-in-group
14102 (mapcar (lambda (x)
14103 (substring x 1 -1))
14104 regexp-in-group-escaped)
14105 tags-in-group
14106 (delq nil (mapcar (lambda (x)
14107 (if (stringp x)
14108 (and (not (equal "{" (substring x 0 1)))
14109 (not (equal "}" (substring x -1)))
14112 tags-in-group)))
14113 ;; If single-as-list, do no more in the while-loop.
14114 (if (not single-as-list)
14115 (progn
14116 (when regexp-in-group
14117 (setq regexp-in-group
14118 (concat "\\|"
14119 (mapconcat 'identity regexp-in-group
14120 "\\|"))))
14121 (setq tags-in-group
14122 (concat dir
14123 "{\\<"
14124 (regexp-opt tags-in-group)
14125 "\\>"
14126 regexp-in-group
14127 "}"))
14128 (when (stringp tags-in-group)
14129 (org-add-props tags-in-group '(grouptag t)))
14130 (setq return-match
14131 (replace-match tags-in-group t t return-match)))
14132 (setq tags-in-group
14133 (append regexp-in-group-escaped tags-in-group))))
14134 (setq taggroups-keys (delete tag taggroups-keys))))
14135 ;; Add the regular expressions back into the match-expression again.
14136 (while regexps-in-match
14137 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14138 (pop regexps-in-match)
14139 return-match t t))
14140 (cl-decf count))
14141 (if single-as-list
14142 (if tags-in-group tags-in-group (list return-match))
14143 return-match))
14144 (if single-as-list
14145 (list (if downcased (downcase match) match))
14146 match)))
14148 (defun org-op-to-function (op &optional stringp)
14149 "Turn an operator into the appropriate function."
14150 (setq op
14151 (cond
14152 ((equal op "<" ) '(< org-string< org-time<))
14153 ((equal op ">" ) '(> org-string> org-time>))
14154 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14155 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14156 ((member op '("=" "==")) '(= string= org-time=))
14157 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14158 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14160 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14161 (defvar org-tags-overlay (make-overlay 1 1))
14162 (delete-overlay org-tags-overlay)
14164 (defun org-add-prop-inherited (s)
14165 (add-text-properties 0 (length s) '(inherited t) s)
14168 (defun org-toggle-tag (tag &optional onoff)
14169 "Toggle the tag TAG for the current line.
14170 If ONOFF is `on' or `off', don't toggle but set to this state."
14171 (save-excursion
14172 (org-back-to-heading t)
14173 (let ((current
14174 ;; Reverse the tags list so any new tag is appended to the
14175 ;; current list of tags.
14176 (nreverse (org-get-tags)))
14177 res)
14178 (pcase onoff
14179 (`off (setq current (delete tag current)))
14180 ((or `on (guard (not (member tag current))))
14181 (setq res t)
14182 (cl-pushnew tag current :test #'equal))
14183 (_ (setq current (delete tag current))))
14184 (org-set-tags-to (nreverse current))
14185 (run-hooks 'org-after-tags-change-hook)
14186 res)))
14188 (defun org--align-tags-here (to-col)
14189 "Align tags on the current headline to TO-COL.
14190 Assume point is on a headline."
14191 (when (and (org-match-line org-tag-line-re)
14192 (< (point) (match-beginning 1)))
14193 (let ((pos (point))
14194 (shift (if (>= to-col 0) to-col
14195 (- (abs to-col) (string-width (match-string 1))))))
14196 ;; Delete all blanks before tags.
14197 (goto-char (match-beginning 1))
14198 (skip-chars-backward " \t")
14199 (delete-region (point) (match-beginning 1))
14200 ;; Insert new blanks.
14201 (insert (make-string (max 1 (- shift (current-column))) ?\s))
14202 ;; Preserve initial position, if possible. In any case, stop
14203 ;; before tags.
14204 (when (< pos (point)) (goto-char pos)))))
14206 (defun org-set-tags-command (&optional arg just-align)
14207 "Call the set-tags command for the current entry."
14208 (interactive "P")
14209 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14210 (org-set-tags arg just-align)
14211 (save-excursion
14212 (unless (and (org-region-active-p)
14213 org-loop-over-headlines-in-active-region)
14214 (org-back-to-heading t))
14215 (org-set-tags arg just-align))))
14217 (defun org-set-tags-to (data)
14218 "Set the tags of the current entry to DATA, replacing current tags.
14219 DATA may be a tags string like \":aa:bb:cc:\", or a list of tags.
14220 If DATA is nil or the empty string, all tags are removed."
14221 (interactive "sTags: ")
14222 (let ((data
14223 (pcase (if (stringp data) (org-trim data) data)
14224 ((or `nil "") nil)
14225 ((pred listp) (org-make-tag-string data))
14226 ((pred stringp)
14227 (org-make-tag-string (org-split-string data ":+")))
14228 (_ (error "Invalid tag specification: %S" data)))))
14229 (org-with-wide-buffer
14230 (org-back-to-heading t)
14231 (let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
14232 (when (or (match-end 5) data)
14233 (goto-char (or (match-beginning 5) (line-end-position)))
14234 (skip-chars-backward " \t")
14235 (delete-region (point) (line-end-position))
14236 (when data
14237 (insert " " data)
14238 (org-set-tags nil 'align))))))
14240 (defun org-align-all-tags ()
14241 "Align the tags in all headings."
14242 (interactive)
14243 (save-excursion
14244 (or (ignore-errors (org-back-to-heading t))
14245 (outline-next-heading))
14246 (if (org-at-heading-p)
14247 (org-set-tags t)
14248 (message "No headings"))))
14250 (defvar org-indent-indentation-per-level)
14251 (defun org-set-tags (&optional arg just-align)
14252 "Set the tags for the current headline.
14253 With prefix ARG, realign all tags in headings in the current buffer.
14254 When JUST-ALIGN is non-nil, only align tags."
14255 (interactive "P")
14256 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14257 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14258 'region-start-level
14259 'region))
14260 org-loop-over-headlines-in-active-region)
14261 (org-map-entries
14262 ;; We don't use ARG and JUST-ALIGN here because these args
14263 ;; are not useful when looping over headlines.
14264 #'org-set-tags
14265 org-loop-over-headlines-in-active-region
14267 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14268 (let ((org-setting-tags t))
14269 (if arg
14270 (save-excursion
14271 (goto-char (point-min))
14272 (while (re-search-forward org-outline-regexp-bol nil t)
14273 (org-set-tags nil t)
14274 (end-of-line))
14275 (message "All tags realigned to column %d" org-tags-column))
14276 (let* ((current (org-make-tag-string (org-get-tags nil t)))
14277 (tags
14278 (if just-align current
14279 ;; Get a new set of tags from the user.
14280 (save-excursion
14281 (let* ((table
14282 (setq
14283 org-last-tags-completion-table
14284 (org-tag-add-to-alist
14285 (and
14286 org-complete-tags-always-offer-all-agenda-tags
14287 (org-global-tags-completion-table
14288 (org-agenda-files)))
14289 (or org-current-tag-alist
14290 (org-get-buffer-tags)))))
14291 (current-tags (org-split-string current ":"))
14292 (inherited-tags
14293 (nreverse (nthcdr (length current-tags)
14294 (nreverse (org-get-tags))))))
14295 (replace-regexp-in-string
14296 "\\([-+&]+\\|,\\)"
14298 (if (or (eq t org-use-fast-tag-selection)
14299 (and org-use-fast-tag-selection
14300 (delq nil (mapcar #'cdr table))))
14301 (org-fast-tag-selection
14302 current-tags inherited-tags table
14303 (and org-fast-tag-selection-include-todo
14304 org-todo-key-alist))
14305 (let ((org-add-colon-after-tag-completion
14306 (< 1 (length table))))
14307 (org-trim
14308 (completing-read
14309 "Tags: "
14310 #'org-tags-completion-function
14311 nil nil current 'org-tags-history))))))))))
14313 (when org-tags-sort-function
14314 (setq tags
14315 (mapconcat
14316 #'identity
14317 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14318 org-tags-sort-function)
14319 ":")))
14321 (if (or (string= ":" tags)
14322 (string= "::" tags))
14323 (setq tags ""))
14324 (if (not (org-string-nw-p tags)) (setq tags "")
14325 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14326 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14328 ;; Insert new tags at the correct column.
14329 (unless (equal current tags)
14330 (save-excursion
14331 (beginning-of-line)
14332 (let ((case-fold-search nil))
14333 (looking-at org-complex-heading-regexp))
14334 ;; Remove current tags, if any.
14335 (when (match-end 5) (replace-match "" nil nil nil 5))
14336 ;; Insert new tags, if any. Otherwise, remove trailing
14337 ;; white spaces.
14338 (end-of-line)
14339 (if (not (equal tags ""))
14340 ;; When text is being inserted on an invisible
14341 ;; region boundary, it can be inadvertently sucked
14342 ;; into invisibility.
14343 (org-flag-region (point) (progn (insert " " tags) (point))
14345 'outline)
14346 (skip-chars-backward " \t")
14347 (delete-region (point) (line-end-position)))))
14348 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14349 ;; is on.
14350 (unless (equal tags "")
14351 (let* ((level (save-excursion
14352 (beginning-of-line)
14353 (skip-chars-forward "\\*")))
14354 (offset (if (bound-and-true-p org-indent-mode)
14355 (* (1- org-indent-indentation-per-level)
14356 (1- level))
14358 (tags-column
14359 (+ org-tags-column
14360 (if (> org-tags-column 0) (- offset) offset))))
14361 (org--align-tags-here tags-column))))
14362 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14364 (defun org-change-tag-in-region (beg end tag off)
14365 "Add or remove TAG for each entry in the region.
14366 This works in the agenda, and also in an Org buffer."
14367 (interactive
14368 (list (region-beginning) (region-end)
14369 (let ((org-last-tags-completion-table
14370 (if (derived-mode-p 'org-mode)
14371 (org-tag-add-to-alist
14372 (org-get-buffer-tags)
14373 (org-global-tags-completion-table))
14374 (org-global-tags-completion-table))))
14375 (completing-read
14376 "Tag: " 'org-tags-completion-function nil nil nil
14377 'org-tags-history))
14378 (progn
14379 (message "[s]et or [r]emove? ")
14380 (equal (read-char-exclusive) ?r))))
14381 (when (fboundp 'deactivate-mark) (deactivate-mark))
14382 (let ((agendap (equal major-mode 'org-agenda-mode))
14383 l1 l2 m buf pos newhead (cnt 0))
14384 (goto-char end)
14385 (setq l2 (1- (org-current-line)))
14386 (goto-char beg)
14387 (setq l1 (org-current-line))
14388 (cl-loop for l from l1 to l2 do
14389 (org-goto-line l)
14390 (setq m (get-text-property (point) 'org-hd-marker))
14391 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14392 (and agendap m))
14393 (setq buf (if agendap (marker-buffer m) (current-buffer))
14394 pos (if agendap m (point)))
14395 (with-current-buffer buf
14396 (save-excursion
14397 (save-restriction
14398 (goto-char pos)
14399 (setq cnt (1+ cnt))
14400 (org-toggle-tag tag (if off 'off 'on))
14401 (setq newhead (org-get-heading)))))
14402 (and agendap (org-agenda-change-all-lines newhead m))))
14403 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14405 (defun org-tags-completion-function (string _predicate &optional flag)
14406 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14407 (confirm (lambda (x) (stringp (car x)))))
14408 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14409 (setq s1 (match-string 1 string)
14410 s2 (match-string 2 string))
14411 (setq s1 "" s2 string))
14412 (cond
14413 ((eq flag nil)
14414 ;; try completion
14415 (setq rtn (try-completion s2 ctable confirm))
14416 (when (stringp rtn)
14417 (setq rtn
14418 (concat s1 s2 (substring rtn (length s2))
14419 (if (and org-add-colon-after-tag-completion
14420 (assoc rtn ctable))
14421 ":" ""))))
14422 rtn)
14423 ((eq flag t)
14424 ;; all-completions
14425 (all-completions s2 ctable confirm))
14426 ((eq flag 'lambda)
14427 ;; exact match?
14428 (assoc s2 ctable)))))
14430 (defun org-fast-tag-insert (kwd tags face &optional end)
14431 "Insert KDW, and the TAGS, the latter with face FACE.
14432 Also insert END."
14433 (insert (format "%-12s" (concat kwd ":"))
14434 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14435 (or end "")))
14437 (defun org-fast-tag-show-exit (flag)
14438 (save-excursion
14439 (org-goto-line 3)
14440 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14441 (replace-match ""))
14442 (when flag
14443 (end-of-line 1)
14444 (org-move-to-column (- (window-width) 19) t)
14445 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14447 (defun org-set-current-tags-overlay (current prefix)
14448 "Add an overlay to CURRENT tag with PREFIX."
14449 (let ((s (org-make-tag-string current)))
14450 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14451 (org-overlay-display org-tags-overlay (concat prefix s))))
14453 (defvar org-last-tag-selection-key nil)
14454 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14455 "Fast tag selection with single keys.
14456 CURRENT is the current list of tags in the headline, INHERITED is the
14457 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14458 possibly with grouping information. TODO-TABLE is a similar table with
14459 TODO keywords, should these have keys assigned to them.
14460 If the keys are nil, a-z are automatically assigned.
14461 Returns the new tags string, or nil to not change the current settings."
14462 (let* ((fulltable (append table todo-table))
14463 (maxlen (apply 'max (mapcar
14464 (lambda (x)
14465 (if (stringp (car x)) (string-width (car x)) 0))
14466 fulltable)))
14467 (buf (current-buffer))
14468 (expert (eq org-fast-tag-selection-single-key 'expert))
14469 (buffer-tags nil)
14470 (fwidth (+ maxlen 3 1 3))
14471 (ncol (/ (- (window-width) 4) fwidth))
14472 (i-face 'org-done)
14473 (c-face 'org-todo)
14474 tg cnt e c char c1 c2 ntable tbl rtn
14475 ov-start ov-end ov-prefix
14476 (exit-after-next org-fast-tag-selection-single-key)
14477 (done-keywords org-done-keywords)
14478 groups ingroup intaggroup)
14479 (save-excursion
14480 (beginning-of-line)
14481 (if (looking-at org-tag-line-re)
14482 (setq ov-start (match-beginning 1)
14483 ov-end (match-end 1)
14484 ov-prefix "")
14485 (setq ov-start (1- (point-at-eol))
14486 ov-end (1+ ov-start))
14487 (skip-chars-forward "^\n\r")
14488 (setq ov-prefix
14489 (concat
14490 (buffer-substring (1- (point)) (point))
14491 (if (> (current-column) org-tags-column)
14493 (make-string (- org-tags-column (current-column)) ?\ ))))))
14494 (move-overlay org-tags-overlay ov-start ov-end)
14495 (save-window-excursion
14496 (if expert
14497 (set-buffer (get-buffer-create " *Org tags*"))
14498 (delete-other-windows)
14499 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14500 (org-switch-to-buffer-other-window " *Org tags*"))
14501 (erase-buffer)
14502 (setq-local org-done-keywords done-keywords)
14503 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14504 (org-fast-tag-insert "Current" current c-face "\n\n")
14505 (org-fast-tag-show-exit exit-after-next)
14506 (org-set-current-tags-overlay current ov-prefix)
14507 (setq tbl fulltable char ?a cnt 0)
14508 (while (setq e (pop tbl))
14509 (cond
14510 ((eq (car e) :startgroup)
14511 (push '() groups) (setq ingroup t)
14512 (unless (zerop cnt)
14513 (setq cnt 0)
14514 (insert "\n"))
14515 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14516 ((eq (car e) :endgroup)
14517 (setq ingroup nil cnt 0)
14518 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14519 ((eq (car e) :startgrouptag)
14520 (setq intaggroup t)
14521 (unless (zerop cnt)
14522 (setq cnt 0)
14523 (insert "\n"))
14524 (insert "[ "))
14525 ((eq (car e) :endgrouptag)
14526 (setq intaggroup nil cnt 0)
14527 (insert "]\n"))
14528 ((equal e '(:newline))
14529 (unless (zerop cnt)
14530 (setq cnt 0)
14531 (insert "\n")
14532 (setq e (car tbl))
14533 (while (equal (car tbl) '(:newline))
14534 (insert "\n")
14535 (setq tbl (cdr tbl)))))
14536 ((equal e '(:grouptags)) (insert " : "))
14538 (setq tg (copy-sequence (car e)) c2 nil)
14539 (if (cdr e)
14540 (setq c (cdr e))
14541 ;; automatically assign a character.
14542 (setq c1 (string-to-char
14543 (downcase (substring
14544 tg (if (= (string-to-char tg) ?@) 1 0)))))
14545 (if (or (rassoc c1 ntable) (rassoc c1 table))
14546 (while (or (rassoc char ntable) (rassoc char table))
14547 (setq char (1+ char)))
14548 (setq c2 c1))
14549 (setq c (or c2 char)))
14550 (when ingroup (push tg (car groups)))
14551 (setq tg (org-add-props tg nil 'face
14552 (cond
14553 ((not (assoc tg table))
14554 (org-get-todo-face tg))
14555 ((member tg current) c-face)
14556 ((member tg inherited) i-face))))
14557 (when (equal (caar tbl) :grouptags)
14558 (org-add-props tg nil 'face 'org-tag-group))
14559 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14560 (insert "[" c "] " tg (make-string
14561 (- fwidth 4 (length tg)) ?\ ))
14562 (push (cons tg c) ntable)
14563 (when (= (cl-incf cnt) ncol)
14564 (insert "\n")
14565 (when (or ingroup intaggroup) (insert " "))
14566 (setq cnt 0)))))
14567 (setq ntable (nreverse ntable))
14568 (insert "\n")
14569 (goto-char (point-min))
14570 (unless expert (org-fit-window-to-buffer))
14571 (setq rtn
14572 (catch 'exit
14573 (while t
14574 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14575 (if (not groups) "no " "")
14576 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14577 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14578 (setq org-last-tag-selection-key c)
14579 (cond
14580 ((= c ?\r) (throw 'exit t))
14581 ((= c ?!)
14582 (setq groups (not groups))
14583 (goto-char (point-min))
14584 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14585 ((= c ?\C-c)
14586 (if (not expert)
14587 (org-fast-tag-show-exit
14588 (setq exit-after-next (not exit-after-next)))
14589 (setq expert nil)
14590 (delete-other-windows)
14591 (set-window-buffer (split-window-vertically) " *Org tags*")
14592 (org-switch-to-buffer-other-window " *Org tags*")
14593 (org-fit-window-to-buffer)))
14594 ((or (= c ?\C-g)
14595 (and (= c ?q) (not (rassoc c ntable))))
14596 (delete-overlay org-tags-overlay)
14597 (setq quit-flag t))
14598 ((= c ?\ )
14599 (setq current nil)
14600 (when exit-after-next (setq exit-after-next 'now)))
14601 ((= c ?\t)
14602 (condition-case nil
14603 (setq tg (completing-read
14604 "Tag: "
14605 (or buffer-tags
14606 (with-current-buffer buf
14607 (setq buffer-tags
14608 (org-get-buffer-tags))))))
14609 (quit (setq tg "")))
14610 (when (string-match "\\S-" tg)
14611 (cl-pushnew (list tg) buffer-tags :test #'equal)
14612 (if (member tg current)
14613 (setq current (delete tg current))
14614 (push tg current)))
14615 (when exit-after-next (setq exit-after-next 'now)))
14616 ((setq e (rassoc c todo-table) tg (car e))
14617 (with-current-buffer buf
14618 (save-excursion (org-todo tg)))
14619 (when exit-after-next (setq exit-after-next 'now)))
14620 ((setq e (rassoc c ntable) tg (car e))
14621 (if (member tg current)
14622 (setq current (delete tg current))
14623 (cl-loop for g in groups do
14624 (when (member tg g)
14625 (dolist (x g) (setq current (delete x current)))))
14626 (push tg current))
14627 (when exit-after-next (setq exit-after-next 'now))))
14629 ;; Create a sorted list
14630 (setq current
14631 (sort current
14632 (lambda (a b)
14633 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14634 (when (eq exit-after-next 'now) (throw 'exit t))
14635 (goto-char (point-min))
14636 (beginning-of-line 2)
14637 (delete-region (point) (point-at-eol))
14638 (org-fast-tag-insert "Current" current c-face)
14639 (org-set-current-tags-overlay current ov-prefix)
14640 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14641 (while (re-search-forward tag-re nil t)
14642 (let ((tag (match-string 1)))
14643 (add-text-properties
14644 (match-beginning 1) (match-end 1)
14645 (list 'face
14646 (cond
14647 ((member tag current) c-face)
14648 ((member tag inherited) i-face)
14649 (t (get-text-property (match-beginning 1) '
14650 face))))))))
14651 (goto-char (point-min)))))
14652 (delete-overlay org-tags-overlay)
14653 (if rtn
14654 (mapconcat 'identity current ":")
14655 nil))))
14657 (defun org-make-tag-string (tags)
14658 "Return string associated to TAGS.
14659 TAGS is a list of strings."
14660 (if (null tags) ""
14661 (format ":%s:" (mapconcat #'identity tags ":"))))
14663 (defun org--get-local-tags ()
14664 "Return list of tags for the current headline.
14665 Assume point is at the beginning of the headline."
14666 (and (looking-at org-tag-line-re)
14667 (split-string (match-string-no-properties 2) ":" t)))
14669 (defun org-get-tags (&optional pos local)
14670 "Get the list of tags specified in the current headline.
14672 When argument POS is non-nil, retrieve tags for headline at POS.
14674 Accoring to `org-use-tags-inheritance', tags may be inherited
14675 from parent headlines, and from the whole document, through
14676 `org-file-tags'. However, when optional argument LOCAL is
14677 non-nil, only return tags really specified in the considered
14678 headline.
14680 Inherited tags have the `inherited' text property."
14681 (if (and org-trust-scanner-tags
14682 (or (not pos) (eq pos (point)))
14683 (not local))
14684 org-scanner-tags
14685 (org-with-point-at (or pos (point))
14686 (unless (org-before-first-heading-p)
14687 (org-back-to-heading t)
14688 (let ((tags (org--get-local-tags)))
14689 (if (or local (not org-use-tag-inheritance)) tags
14690 (while (org-up-heading-safe)
14691 (setq tags (append (mapcar #'org-add-prop-inherited
14692 (org--get-local-tags))
14693 tags)))
14694 (org-remove-uninherited-tags
14695 (delete-dups (append org-file-tags tags)))))))))
14697 (defun org-get-buffer-tags ()
14698 "Get a table of all tags used in the buffer, for completion."
14699 (org-with-point-at 1
14700 (let (tags)
14701 (while (re-search-forward org-tag-line-re nil t)
14702 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14703 tags)))
14704 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14706 ;;;; The mapping API
14708 (defvar org-agenda-skip-comment-trees)
14709 (defvar org-agenda-skip-function)
14710 (defun org-map-entries (func &optional match scope &rest skip)
14711 "Call FUNC at each headline selected by MATCH in SCOPE.
14713 FUNC is a function or a lisp form. The function will be called without
14714 arguments, with the cursor positioned at the beginning of the headline.
14715 The return values of all calls to the function will be collected and
14716 returned as a list.
14718 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14719 does not need to preserve point. After evaluation, the cursor will be
14720 moved to the end of the line (presumably of the headline of the
14721 processed entry) and search continues from there. Under some
14722 circumstances, this may not produce the wanted results. For example,
14723 if you have removed (e.g. archived) the current (sub)tree it could
14724 mean that the next entry will be skipped entirely. In such cases, you
14725 can specify the position from where search should continue by making
14726 FUNC set the variable `org-map-continue-from' to the desired buffer
14727 position.
14729 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14730 Only headlines that are matched by this query will be considered during
14731 the iteration. When MATCH is nil or t, all headlines will be
14732 visited by the iteration.
14734 SCOPE determines the scope of this command. It can be any of:
14736 nil The current buffer, respecting the restriction if any
14737 tree The subtree started with the entry at point
14738 region The entries within the active region, if any
14739 region-start-level
14740 The entries within the active region, but only those at
14741 the same level than the first one.
14742 file The current buffer, without restriction
14743 file-with-archives
14744 The current buffer, and any archives associated with it
14745 agenda All agenda files
14746 agenda-with-archives
14747 All agenda files with any archive files associated with them
14748 \(file1 file2 ...)
14749 If this is a list, all files in the list will be scanned
14751 The remaining args are treated as settings for the skipping facilities of
14752 the scanner. The following items can be given here:
14754 archive skip trees with the archive tag
14755 comment skip trees with the COMMENT keyword
14756 function or Emacs Lisp form:
14757 will be used as value for `org-agenda-skip-function', so
14758 whenever the function returns a position, FUNC will not be
14759 called for that entry and search will continue from the
14760 position returned
14762 If your function needs to retrieve the tags including inherited tags
14763 at the *current* entry, you can use the value of the variable
14764 `org-scanner-tags' which will be much faster than getting the value
14765 with `org-get-tags'. If your function gets properties with
14766 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14767 to t around the call to `org-entry-properties' to get the same speedup.
14768 Note that if your function moves around to retrieve tags and properties at
14769 a *different* entry, you cannot use these techniques."
14770 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14771 (not (org-region-active-p)))
14772 (let* ((org-agenda-archives-mode nil) ; just to make sure
14773 (org-agenda-skip-archived-trees (memq 'archive skip))
14774 (org-agenda-skip-comment-trees (memq 'comment skip))
14775 (org-agenda-skip-function
14776 (car (org-delete-all '(comment archive) skip)))
14777 (org-tags-match-list-sublevels t)
14778 (start-level (eq scope 'region-start-level))
14779 matcher res
14780 org-todo-keywords-for-agenda
14781 org-done-keywords-for-agenda
14782 org-todo-keyword-alist-for-agenda
14783 org-tag-alist-for-agenda
14784 org--matcher-tags-todo-only)
14786 (cond
14787 ((eq match t) (setq matcher t))
14788 ((eq match nil) (setq matcher t))
14789 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14791 (save-excursion
14792 (save-restriction
14793 (cond ((eq scope 'tree)
14794 (org-back-to-heading t)
14795 (org-narrow-to-subtree)
14796 (setq scope nil))
14797 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14798 (org-region-active-p))
14799 ;; If needed, set start-level to a string like "2"
14800 (when start-level
14801 (save-excursion
14802 (goto-char (region-beginning))
14803 (unless (org-at-heading-p) (outline-next-heading))
14804 (setq start-level (org-current-level))))
14805 (narrow-to-region (region-beginning)
14806 (save-excursion
14807 (goto-char (region-end))
14808 (unless (and (bolp) (org-at-heading-p))
14809 (outline-next-heading))
14810 (point)))
14811 (setq scope nil)))
14813 (if (not scope)
14814 (progn
14815 (org-agenda-prepare-buffers
14816 (and buffer-file-name (list buffer-file-name)))
14817 (setq res
14818 (org-scan-tags
14819 func matcher org--matcher-tags-todo-only start-level)))
14820 ;; Get the right scope
14821 (cond
14822 ((and scope (listp scope) (symbolp (car scope)))
14823 (setq scope (eval scope)))
14824 ((eq scope 'agenda)
14825 (setq scope (org-agenda-files t)))
14826 ((eq scope 'agenda-with-archives)
14827 (setq scope (org-agenda-files t))
14828 (setq scope (org-add-archive-files scope)))
14829 ((eq scope 'file)
14830 (setq scope (and buffer-file-name (list buffer-file-name))))
14831 ((eq scope 'file-with-archives)
14832 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14833 (org-agenda-prepare-buffers scope)
14834 (dolist (file scope)
14835 (with-current-buffer (org-find-base-buffer-visiting file)
14836 (org-with-wide-buffer
14837 (goto-char (point-min))
14838 (setq res
14839 (append
14841 (org-scan-tags
14842 func matcher org--matcher-tags-todo-only)))))))))
14843 res)))
14845 ;;; Properties API
14847 (defconst org-special-properties
14848 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14849 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14850 "The special properties valid in Org mode.
14851 These are properties that are not defined in the property drawer,
14852 but in some other way.")
14854 (defconst org-default-properties
14855 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14856 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14857 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14858 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14859 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14860 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14861 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14862 "Some properties that are used by Org mode for various purposes.
14863 Being in this list makes sure that they are offered for completion.")
14865 (defun org--valid-property-p (property)
14866 "Non nil when string PROPERTY is a valid property name."
14867 (not
14868 (or (equal property "")
14869 (string-match-p "\\s-" property))))
14871 (defun org--update-property-plist (key val props)
14872 "Associate KEY to VAL in alist PROPS.
14873 Modifications are made by side-effect. Return new alist."
14874 (let* ((appending (string= (substring key -1) "+"))
14875 (key (if appending (substring key 0 -1) key))
14876 (old (assoc-string key props t)))
14877 (if (not old) (cons (cons key val) props)
14878 (setcdr old (if appending (concat (cdr old) " " val) val))
14879 props)))
14881 (defun org-get-property-block (&optional beg force)
14882 "Return the (beg . end) range of the body of the property drawer.
14883 BEG is the beginning of the current subtree, or of the part
14884 before the first headline. If it is not given, it will be found.
14885 If the drawer does not exist, create it if FORCE is non-nil, or
14886 return nil."
14887 (org-with-wide-buffer
14888 (when beg (goto-char beg))
14889 (unless (org-before-first-heading-p)
14890 (let ((beg (cond (beg)
14891 ((or (not (featurep 'org-inlinetask))
14892 (org-inlinetask-in-task-p))
14893 (org-back-to-heading t))
14894 (t (org-with-limited-levels (org-back-to-heading t))))))
14895 (forward-line)
14896 (when (looking-at-p org-planning-line-re) (forward-line))
14897 (cond ((looking-at org-property-drawer-re)
14898 (forward-line)
14899 (cons (point) (progn (goto-char (match-end 0))
14900 (line-beginning-position))))
14901 (force
14902 (goto-char beg)
14903 (org-insert-property-drawer)
14904 (let ((pos (save-excursion (search-forward ":END:")
14905 (line-beginning-position))))
14906 (cons pos pos))))))))
14908 (defun org-at-property-p ()
14909 "Non-nil when point is inside a property drawer.
14910 See `org-property-re' for match data, if applicable."
14911 (save-excursion
14912 (beginning-of-line)
14913 (and (looking-at org-property-re)
14914 (let ((property-drawer (save-match-data (org-get-property-block))))
14915 (and property-drawer
14916 (>= (point) (car property-drawer))
14917 (< (point) (cdr property-drawer)))))))
14919 (defun org-property-action ()
14920 "Do an action on properties."
14921 (interactive)
14922 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14923 (let ((c (read-char-exclusive)))
14924 (cl-case c
14925 (?s (call-interactively #'org-set-property))
14926 (?d (call-interactively #'org-delete-property))
14927 (?D (call-interactively #'org-delete-property-globally))
14928 (?c (call-interactively #'org-compute-property-at-point))
14929 (otherwise (user-error "No such property action %c" c)))))
14931 (defun org-inc-effort ()
14932 "Increment the value of the effort property in the current entry."
14933 (interactive)
14934 (org-set-effort t))
14936 (defvar org-clock-effort) ; Defined in org-clock.el.
14937 (defvar org-clock-current-task) ; Defined in org-clock.el.
14938 (defun org-set-effort (&optional increment value)
14939 "Set the effort property of the current entry.
14940 If INCREMENT is non-nil, set the property to the next allowed
14941 value. Otherwise, if optional argument VALUE is provided, use
14942 it. Eventually, prompt for the new value if none of the previous
14943 variables is set."
14944 (interactive "P")
14945 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14946 (current (org-entry-get nil org-effort-property))
14947 (value
14948 (cond
14949 (increment
14950 (unless allowed (user-error "Allowed effort values are not set"))
14951 (or (cl-caadr (member (list current) allowed))
14952 (user-error "Unknown value %S among allowed values" current)))
14953 (value
14954 (if (stringp value) value
14955 (error "Invalid effort value: %S" value)))
14957 (let ((must-match
14958 (and allowed
14959 (not (get-text-property 0 'org-unrestricted
14960 (caar allowed))))))
14961 (completing-read "Effort: " allowed nil must-match))))))
14962 (unless (equal current value)
14963 (org-entry-put nil org-effort-property value))
14964 (org-refresh-property '((effort . identity)
14965 (effort-minutes . org-duration-to-minutes))
14966 value)
14967 (when (equal (org-get-heading t t t t)
14968 (bound-and-true-p org-clock-current-task))
14969 (setq org-clock-effort (org-get-at-bol 'effort))
14970 (org-clock-update-mode-line))
14971 (message "%s is now %s" org-effort-property value)))
14973 (defun org-entry-properties (&optional pom which)
14974 "Get all properties of the current entry.
14976 When POM is a buffer position, get all properties from the entry
14977 there instead.
14979 This includes the TODO keyword, the tags, time strings for
14980 deadline, scheduled, and clocking, and any additional properties
14981 defined in the entry.
14983 If WHICH is nil or `all', get all properties. If WHICH is
14984 `special' or `standard', only get that subclass. If WHICH is
14985 a string, only get that property.
14987 Return value is an alist. Keys are properties, as upcased
14988 strings."
14989 (org-with-point-at pom
14990 (when (and (derived-mode-p 'org-mode)
14991 (ignore-errors (org-back-to-heading t)))
14992 (catch 'exit
14993 (let* ((beg (point))
14994 (specific (and (stringp which) (upcase which)))
14995 (which (cond ((not specific) which)
14996 ((member specific org-special-properties) 'special)
14997 (t 'standard)))
14998 props)
14999 ;; Get the special properties, like TODO and TAGS.
15000 (when (memq which '(nil all special))
15001 (when (or (not specific) (string= specific "CLOCKSUM"))
15002 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15003 (when clocksum
15004 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15005 props)))
15006 (when specific (throw 'exit props)))
15007 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15008 (let ((clocksumt (get-text-property (point)
15009 :org-clock-minutes-today)))
15010 (when clocksumt
15011 (push (cons "CLOCKSUM_T"
15012 (org-duration-from-minutes clocksumt))
15013 props)))
15014 (when specific (throw 'exit props)))
15015 (when (or (not specific) (string= specific "ITEM"))
15016 (let ((case-fold-search nil))
15017 (when (looking-at org-complex-heading-regexp)
15018 (push (cons "ITEM"
15019 (let ((title (match-string-no-properties 4)))
15020 (if (org-string-nw-p title)
15021 (org-remove-tabs title)
15022 "")))
15023 props)))
15024 (when specific (throw 'exit props)))
15025 (when (or (not specific) (string= specific "TODO"))
15026 (let ((case-fold-search nil))
15027 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15028 (push (cons "TODO" (match-string-no-properties 2)) props)))
15029 (when specific (throw 'exit props)))
15030 (when (or (not specific) (string= specific "PRIORITY"))
15031 (push (cons "PRIORITY"
15032 (if (looking-at org-priority-regexp)
15033 (match-string-no-properties 2)
15034 (char-to-string org-default-priority)))
15035 props)
15036 (when specific (throw 'exit props)))
15037 (when (or (not specific) (string= specific "FILE"))
15038 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15039 props)
15040 (when specific (throw 'exit props)))
15041 (when (or (not specific) (string= specific "TAGS"))
15042 (let ((tags (org-get-tags nil t)))
15043 (when tags
15044 (push (cons "TAGS" (org-make-tag-string tags))
15045 props)))
15046 (when specific (throw 'exit props)))
15047 (when (or (not specific) (string= specific "ALLTAGS"))
15048 (let ((tags (org-get-tags)))
15049 (when tags
15050 (push (cons "ALLTAGS" (org-make-tag-string tags))
15051 props)))
15052 (when specific (throw 'exit props)))
15053 (when (or (not specific) (string= specific "BLOCKED"))
15054 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15055 (when specific (throw 'exit props)))
15056 (when (or (not specific)
15057 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15058 (forward-line)
15059 (when (looking-at-p org-planning-line-re)
15060 (end-of-line)
15061 (let ((bol (line-beginning-position))
15062 ;; Backward compatibility: time keywords used to
15063 ;; be configurable (before 8.3). Make sure we
15064 ;; get the correct keyword.
15065 (key-assoc `(("CLOSED" . ,org-closed-string)
15066 ("DEADLINE" . ,org-deadline-string)
15067 ("SCHEDULED" . ,org-scheduled-string))))
15068 (dolist (pair (if specific (list (assoc specific key-assoc))
15069 key-assoc))
15070 (save-excursion
15071 (when (search-backward (cdr pair) bol t)
15072 (goto-char (match-end 0))
15073 (skip-chars-forward " \t")
15074 (and (looking-at org-ts-regexp-both)
15075 (push (cons (car pair)
15076 (match-string-no-properties 0))
15077 props)))))))
15078 (when specific (throw 'exit props)))
15079 (when (or (not specific)
15080 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15081 (let ((find-ts
15082 (lambda (end ts)
15083 ;; Fix next time-stamp before END. TS is the
15084 ;; list of time-stamps found so far.
15085 (let ((ts ts)
15086 (regexp (cond
15087 ((string= specific "TIMESTAMP")
15088 org-ts-regexp)
15089 ((string= specific "TIMESTAMP_IA")
15090 org-ts-regexp-inactive)
15091 ((assoc "TIMESTAMP_IA" ts)
15092 org-ts-regexp)
15093 ((assoc "TIMESTAMP" ts)
15094 org-ts-regexp-inactive)
15095 (t org-ts-regexp-both))))
15096 (catch 'next
15097 (while (re-search-forward regexp end t)
15098 (backward-char)
15099 (let ((object (org-element-context)))
15100 ;; Accept to match timestamps in node
15101 ;; properties, too.
15102 (when (memq (org-element-type object)
15103 '(node-property timestamp))
15104 (let ((type
15105 (org-element-property :type object)))
15106 (cond
15107 ((and (memq type '(active active-range))
15108 (not (equal specific "TIMESTAMP_IA")))
15109 (unless (assoc "TIMESTAMP" ts)
15110 (push (cons "TIMESTAMP"
15111 (org-element-property
15112 :raw-value object))
15114 (when specific (throw 'exit ts))))
15115 ((and (memq type '(inactive inactive-range))
15116 (not (string= specific "TIMESTAMP")))
15117 (unless (assoc "TIMESTAMP_IA" ts)
15118 (push (cons "TIMESTAMP_IA"
15119 (org-element-property
15120 :raw-value object))
15122 (when specific (throw 'exit ts))))))
15123 ;; Both timestamp types are found,
15124 ;; move to next part.
15125 (when (= (length ts) 2) (throw 'next ts)))))
15126 ts)))))
15127 (goto-char beg)
15128 ;; First look for timestamps within headline.
15129 (let ((ts (funcall find-ts (line-end-position) nil)))
15130 (if (= (length ts) 2) (setq props (nconc ts props))
15131 ;; Then find timestamps in the section, skipping
15132 ;; planning line.
15133 (let ((end (save-excursion (outline-next-heading))))
15134 (forward-line)
15135 (when (looking-at-p org-planning-line-re) (forward-line))
15136 (setq props (nconc (funcall find-ts end ts) props))))))))
15137 ;; Get the standard properties, like :PROP:.
15138 (when (memq which '(nil all standard))
15139 ;; If we are looking after a specific property, delegate
15140 ;; to `org-entry-get', which is faster. However, make an
15141 ;; exception for "CATEGORY", since it can be also set
15142 ;; through keywords (i.e. #+CATEGORY).
15143 (if (and specific (not (equal specific "CATEGORY")))
15144 (let ((value (org-entry-get beg specific nil t)))
15145 (throw 'exit (and value (list (cons specific value)))))
15146 (let ((range (org-get-property-block beg)))
15147 (when range
15148 (let ((end (cdr range)) seen-base)
15149 (goto-char (car range))
15150 ;; Unlike to `org--update-property-plist', we
15151 ;; handle the case where base values is found
15152 ;; after its extension. We also forbid standard
15153 ;; properties to be named as special properties.
15154 (while (re-search-forward org-property-re end t)
15155 (let* ((key (upcase (match-string-no-properties 2)))
15156 (extendp (string-match-p "\\+\\'" key))
15157 (key-base (if extendp (substring key 0 -1) key))
15158 (value (match-string-no-properties 3)))
15159 (cond
15160 ((member-ignore-case key-base org-special-properties))
15161 (extendp
15162 (setq props
15163 (org--update-property-plist key value props)))
15164 ((member key seen-base))
15165 (t (push key seen-base)
15166 (let ((p (assoc-string key props t)))
15167 (if p (setcdr p (concat value " " (cdr p)))
15168 (push (cons key value) props))))))))))))
15169 (unless (assoc "CATEGORY" props)
15170 (push (cons "CATEGORY" (org-get-category beg)) props)
15171 (when (string= specific "CATEGORY") (throw 'exit props)))
15172 ;; Return value.
15173 props)))))
15175 (defun org--property-local-values (property literal-nil)
15176 "Return value for PROPERTY in current entry.
15177 Value is a list whose car is the base value for PROPERTY and cdr
15178 a list of accumulated values. Return nil if neither is found in
15179 the entry. Also return nil when PROPERTY is set to \"nil\",
15180 unless LITERAL-NIL is non-nil."
15181 (let ((range (org-get-property-block)))
15182 (when range
15183 (goto-char (car range))
15184 (let* ((case-fold-search t)
15185 (end (cdr range))
15186 (value
15187 ;; Base value.
15188 (save-excursion
15189 (let ((v (and (re-search-forward
15190 (org-re-property property nil t) end t)
15191 (match-string-no-properties 3))))
15192 (list (if literal-nil v (org-not-nil v)))))))
15193 ;; Find additional values.
15194 (let* ((property+ (org-re-property (concat property "+") nil t)))
15195 (while (re-search-forward property+ end t)
15196 (push (match-string-no-properties 3) value)))
15197 ;; Return final values.
15198 (and (not (equal value '(nil))) (nreverse value))))))
15200 (defun org--property-global-value (property literal-nil)
15201 "Return value for PROPERTY in current buffer.
15202 Return value is a string. Return nil if property is not set
15203 globally. Also return nil when PROPERTY is set to \"nil\",
15204 unless LITERAL-NIL is non-nil."
15205 (let ((global
15206 (cdr (or (assoc-string property org-file-properties t)
15207 (assoc-string property org-global-properties t)
15208 (assoc-string property org-global-properties-fixed t)))))
15209 (if literal-nil global (org-not-nil global))))
15211 (defun org-entry-get (pom property &optional inherit literal-nil)
15212 "Get value of PROPERTY for entry or content at point-or-marker POM.
15214 If INHERIT is non-nil and the entry does not have the property,
15215 then also check higher levels of the hierarchy. If INHERIT is
15216 the symbol `selective', use inheritance only if the setting in
15217 `org-use-property-inheritance' selects PROPERTY for inheritance.
15219 If the property is present but empty, the return value is the
15220 empty string. If the property is not present at all, nil is
15221 returned. In any other case, return the value as a string.
15222 Search is case-insensitive.
15224 If LITERAL-NIL is set, return the string value \"nil\" as
15225 a string, do not interpret it as the list atom nil. This is used
15226 for inheritance when a \"nil\" value can supersede a non-nil
15227 value higher up the hierarchy."
15228 (org-with-point-at pom
15229 (cond
15230 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15231 ;; We need a special property. Use `org-entry-properties' to
15232 ;; retrieve it, but specify the wanted property.
15233 (cdr (assoc-string property (org-entry-properties nil property))))
15234 ((and inherit
15235 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15236 (org-entry-get-with-inheritance property literal-nil))
15238 (let* ((local (org--property-local-values property literal-nil))
15239 (value (and local (mapconcat #'identity (delq nil local) " "))))
15240 (if literal-nil value (org-not-nil value)))))))
15242 (defun org-property-or-variable-value (var &optional inherit)
15243 "Check if there is a property fixing the value of VAR.
15244 If yes, return this value. If not, return the current value of the variable."
15245 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15246 (if (and prop (stringp prop) (string-match "\\S-" prop))
15247 (read prop)
15248 (symbol-value var))))
15250 (defun org-entry-delete (pom property)
15251 "Delete PROPERTY from entry at point-or-marker POM.
15252 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15253 non-nil when a property was removed."
15254 (org-with-point-at pom
15255 (pcase (org-get-property-block)
15256 (`(,begin . ,origin)
15257 (let* ((end (copy-marker origin))
15258 (re (org-re-property
15259 (concat (regexp-quote property) "\\+?") t t)))
15260 (goto-char begin)
15261 (while (re-search-forward re end t)
15262 (delete-region (match-beginning 0) (line-beginning-position 2)))
15263 ;; If drawer is empty, remove it altogether.
15264 (when (= begin end)
15265 (delete-region (line-beginning-position 0)
15266 (line-beginning-position 2)))
15267 ;; Return non-nil if some property was removed.
15268 (prog1 (/= end origin) (set-marker end nil))))
15269 (_ nil))))
15271 ;; Multi-values properties are properties that contain multiple values
15272 ;; These values are assumed to be single words, separated by whitespace.
15273 (defun org-entry-add-to-multivalued-property (pom property value)
15274 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15275 (let* ((old (org-entry-get pom property))
15276 (values (and old (split-string old))))
15277 (setq value (org-entry-protect-space value))
15278 (unless (member value values)
15279 (setq values (append values (list value)))
15280 (org-entry-put pom property (mapconcat #'identity values " ")))))
15282 (defun org-entry-remove-from-multivalued-property (pom property value)
15283 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15284 (let* ((old (org-entry-get pom property))
15285 (values (and old (split-string old))))
15286 (setq value (org-entry-protect-space value))
15287 (when (member value values)
15288 (setq values (delete value values))
15289 (org-entry-put pom property (mapconcat #'identity values " ")))))
15291 (defun org-entry-member-in-multivalued-property (pom property value)
15292 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15293 (let* ((old (org-entry-get pom property))
15294 (values (and old (split-string old))))
15295 (setq value (org-entry-protect-space value))
15296 (member value values)))
15298 (defun org-entry-get-multivalued-property (pom property)
15299 "Return a list of values in a multivalued property."
15300 (let* ((value (org-entry-get pom property))
15301 (values (and value (split-string value))))
15302 (mapcar #'org-entry-restore-space values)))
15304 (defun org-entry-put-multivalued-property (pom property &rest values)
15305 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15306 VALUES should be a list of strings. Spaces will be protected."
15307 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15308 (let* ((value (org-entry-get pom property))
15309 (values (and value (split-string value))))
15310 (mapcar #'org-entry-restore-space values)))
15312 (defun org-entry-protect-space (s)
15313 "Protect spaces and newline in string S."
15314 (while (string-match " " s)
15315 (setq s (replace-match "%20" t t s)))
15316 (while (string-match "\n" s)
15317 (setq s (replace-match "%0A" t t s)))
15320 (defun org-entry-restore-space (s)
15321 "Restore spaces and newline in string S."
15322 (while (string-match "%20" s)
15323 (setq s (replace-match " " t t s)))
15324 (while (string-match "%0A" s)
15325 (setq s (replace-match "\n" t t s)))
15328 (defvar org-entry-property-inherited-from (make-marker)
15329 "Marker pointing to the entry from where a property was inherited.
15330 Each call to `org-entry-get-with-inheritance' will set this marker to the
15331 location of the entry where the inheritance search matched. If there was
15332 no match, the marker will point nowhere.
15333 Note that also `org-entry-get' calls this function, if the INHERIT flag
15334 is set.")
15336 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15337 "Get PROPERTY of entry or content at point, search higher levels if needed.
15338 The search will stop at the first ancestor which has the property defined.
15339 If the value found is \"nil\", return nil to show that the property
15340 should be considered as undefined (this is the meaning of nil here).
15341 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15342 (move-marker org-entry-property-inherited-from nil)
15343 (org-with-wide-buffer
15344 (let (value)
15345 (catch 'exit
15346 (while t
15347 (let ((v (org--property-local-values property literal-nil)))
15348 (when v
15349 (setq value
15350 (concat (mapconcat #'identity (delq nil v) " ")
15351 (and value " ")
15352 value)))
15353 (cond
15354 ((car v)
15355 (org-back-to-heading t)
15356 (move-marker org-entry-property-inherited-from (point))
15357 (throw 'exit nil))
15358 ((org-up-heading-safe))
15360 (let ((global (org--property-global-value property literal-nil)))
15361 (cond ((not global))
15362 (value (setq value (concat global " " value)))
15363 (t (setq value global))))
15364 (throw 'exit nil))))))
15365 (if literal-nil value (org-not-nil value)))))
15367 (defvar org-property-changed-functions nil
15368 "Hook called when the value of a property has changed.
15369 Each hook function should accept two arguments, the name of the property
15370 and the new value.")
15372 (defun org-entry-put (pom property value)
15373 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15375 If the value is nil, it is converted to the empty string. If it
15376 is not a string, an error is raised. Also raise an error on
15377 invalid property names.
15379 PROPERTY can be any regular property (see
15380 `org-special-properties'). It can also be \"TODO\",
15381 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15383 For the last two properties, VALUE may have any of the special
15384 values \"earlier\" and \"later\". The function then increases or
15385 decreases scheduled or deadline date by one day."
15386 (cond ((null value) (setq value ""))
15387 ((not (stringp value)) (error "Properties values should be strings"))
15388 ((not (org--valid-property-p property))
15389 (user-error "Invalid property name: \"%s\"" property)))
15390 (org-with-point-at pom
15391 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15392 (org-back-to-heading t)
15393 (org-with-limited-levels (org-back-to-heading t)))
15394 (let ((beg (point)))
15395 (cond
15396 ((equal property "TODO")
15397 (cond ((not (org-string-nw-p value)) (setq value 'none))
15398 ((not (member value org-todo-keywords-1))
15399 (user-error "\"%s\" is not a valid TODO state" value)))
15400 (org-todo value)
15401 (org-set-tags nil 'align))
15402 ((equal property "PRIORITY")
15403 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15404 (org-set-tags nil 'align))
15405 ((equal property "SCHEDULED")
15406 (forward-line)
15407 (if (and (looking-at-p org-planning-line-re)
15408 (re-search-forward
15409 org-scheduled-time-regexp (line-end-position) t))
15410 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15411 ((string= value "later") (org-timestamp-change 1 'day))
15412 ((string= value "") (org-schedule '(4)))
15413 (t (org-schedule nil value)))
15414 (if (member value '("earlier" "later" ""))
15415 (call-interactively #'org-schedule)
15416 (org-schedule nil value))))
15417 ((equal property "DEADLINE")
15418 (forward-line)
15419 (if (and (looking-at-p org-planning-line-re)
15420 (re-search-forward
15421 org-deadline-time-regexp (line-end-position) t))
15422 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15423 ((string= value "later") (org-timestamp-change 1 'day))
15424 ((string= value "") (org-deadline '(4)))
15425 (t (org-deadline nil value)))
15426 (if (member value '("earlier" "later" ""))
15427 (call-interactively #'org-deadline)
15428 (org-deadline nil value))))
15429 ((member property org-special-properties)
15430 (error "The %s property cannot be set with `org-entry-put'" property))
15432 (let* ((range (org-get-property-block beg 'force))
15433 (end (cdr range))
15434 (case-fold-search t))
15435 (goto-char (car range))
15436 (if (re-search-forward (org-re-property property nil t) end t)
15437 (progn (delete-region (match-beginning 0) (match-end 0))
15438 (goto-char (match-beginning 0)))
15439 (goto-char end)
15440 (insert "\n")
15441 (backward-char))
15442 (insert ":" property ":")
15443 (when value (insert " " value))
15444 (org-indent-line)))))
15445 (run-hook-with-args 'org-property-changed-functions property value)))
15447 (defun org-buffer-property-keys (&optional specials defaults columns)
15448 "Get all property keys in the current buffer.
15450 When SPECIALS is non-nil, also list the special properties that
15451 reflect things like tags and TODO state.
15453 When DEFAULTS is non-nil, also include properties that has
15454 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15455 DESCRIPTION, LOCATION, and LOGGING and others.
15457 When COLUMNS in non-nil, also include property names given in
15458 COLUMN formats in the current buffer."
15459 (let ((case-fold-search t)
15460 (props (append
15461 (and specials org-special-properties)
15462 (and defaults (cons org-effort-property org-default-properties))
15463 nil)))
15464 (org-with-wide-buffer
15465 (goto-char (point-min))
15466 (while (re-search-forward org-property-start-re nil t)
15467 (catch :skip
15468 (let ((range (org-get-property-block)))
15469 (unless range (throw :skip nil))
15470 (goto-char (car range))
15471 (let ((begin (car range))
15472 (end (cdr range)))
15473 ;; Make sure that found property block is not located
15474 ;; before current point, as it would generate an infloop.
15475 ;; It can happen, for example, in the following
15476 ;; situation:
15478 ;; * Headline
15479 ;; :PROPERTIES:
15480 ;; ...
15481 ;; :END:
15482 ;; *************** Inlinetask
15483 ;; #+BEGIN_EXAMPLE
15484 ;; :PROPERTIES:
15485 ;; #+END_EXAMPLE
15487 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15488 (while (< (point) end)
15489 (let ((p (progn (looking-at org-property-re)
15490 (match-string-no-properties 2))))
15491 ;; Only add true property name, not extension symbol.
15492 (push (if (not (string-match-p "\\+\\'" p)) p
15493 (substring p 0 -1))
15494 props))
15495 (forward-line))))
15496 (outline-next-heading)))
15497 (when columns
15498 (goto-char (point-min))
15499 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15500 (let ((element (org-element-at-point)))
15501 (when (memq (org-element-type element) '(keyword node-property))
15502 (let ((value (org-element-property :value element))
15503 (start 0))
15504 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15505 \\(?:{[^}]+}\\)?"
15506 value start)
15507 (setq start (match-end 0))
15508 (let ((p (match-string-no-properties 1 value)))
15509 (unless (member-ignore-case p org-special-properties)
15510 (push p props))))))))))
15511 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15513 (defun org-property-values (key)
15514 "List all non-nil values of property KEY in current buffer."
15515 (org-with-wide-buffer
15516 (goto-char (point-min))
15517 (let ((case-fold-search t)
15518 (re (org-re-property key))
15519 values)
15520 (while (re-search-forward re nil t)
15521 (push (org-entry-get (point) key) values))
15522 (delete-dups values))))
15524 (defun org-insert-property-drawer ()
15525 "Insert a property drawer into the current entry."
15526 (org-with-wide-buffer
15527 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15528 (org-back-to-heading t)
15529 (org-with-limited-levels (org-back-to-heading t)))
15530 (forward-line)
15531 (when (looking-at-p org-planning-line-re) (forward-line))
15532 (unless (looking-at-p org-property-drawer-re)
15533 ;; Make sure we start editing a line from current entry, not from
15534 ;; next one. It prevents extending text properties or overlays
15535 ;; belonging to the latter.
15536 (when (bolp) (backward-char))
15537 (let ((begin (1+ (point)))
15538 (inhibit-read-only t))
15539 (insert "\n:PROPERTIES:\n:END:")
15540 (when (eobp) (insert "\n"))
15541 (org-indent-region begin (point))))))
15543 (defun org-insert-drawer (&optional arg drawer)
15544 "Insert a drawer at point.
15546 When optional argument ARG is non-nil, insert a property drawer.
15548 Optional argument DRAWER, when non-nil, is a string representing
15549 drawer's name. Otherwise, the user is prompted for a name.
15551 If a region is active, insert the drawer around that region
15552 instead.
15554 Point is left between drawer's boundaries."
15555 (interactive "P")
15556 (let* ((drawer (if arg "PROPERTIES"
15557 (or drawer (read-from-minibuffer "Drawer: ")))))
15558 (cond
15559 ;; With C-u, fall back on `org-insert-property-drawer'
15560 (arg (org-insert-property-drawer))
15561 ;; Check validity of suggested drawer's name.
15562 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15563 (user-error "Invalid drawer name"))
15564 ;; With an active region, insert a drawer at point.
15565 ((not (org-region-active-p))
15566 (progn
15567 (unless (bolp) (insert "\n"))
15568 (insert (format ":%s:\n\n:END:\n" drawer))
15569 (forward-line -2)))
15570 ;; Otherwise, insert the drawer at point
15572 (let ((rbeg (region-beginning))
15573 (rend (copy-marker (region-end))))
15574 (unwind-protect
15575 (progn
15576 (goto-char rbeg)
15577 (beginning-of-line)
15578 (when (save-excursion
15579 (re-search-forward org-outline-regexp-bol rend t))
15580 (user-error "Drawers cannot contain headlines"))
15581 ;; Position point at the beginning of the first
15582 ;; non-blank line in region. Insert drawer's opening
15583 ;; there, then indent it.
15584 (org-skip-whitespace)
15585 (beginning-of-line)
15586 (insert ":" drawer ":\n")
15587 (forward-line -1)
15588 (indent-for-tab-command)
15589 ;; Move point to the beginning of the first blank line
15590 ;; after the last non-blank line in region. Insert
15591 ;; drawer's closing, then indent it.
15592 (goto-char rend)
15593 (skip-chars-backward " \r\t\n")
15594 (insert "\n:END:")
15595 (deactivate-mark t)
15596 (indent-for-tab-command)
15597 (unless (eolp) (insert "\n")))
15598 ;; Clear marker, whatever the outcome of insertion is.
15599 (set-marker rend nil)))))))
15601 (defvar org-property-set-functions-alist nil
15602 "Property set function alist.
15603 Each entry should have the following format:
15605 (PROPERTY . READ-FUNCTION)
15607 The read function will be called with the same argument as
15608 `org-completing-read'.")
15610 (defun org-set-property-function (property)
15611 "Get the function that should be used to set PROPERTY.
15612 This is computed according to `org-property-set-functions-alist'."
15613 (or (cdr (assoc property org-property-set-functions-alist))
15614 'org-completing-read))
15616 (defun org-read-property-value (property)
15617 "Read PROPERTY value from user."
15618 (let* ((completion-ignore-case t)
15619 (allowed (org-property-get-allowed-values nil property 'table))
15620 (cur (org-entry-get nil property))
15621 (prompt (concat property " value"
15622 (if (and cur (string-match "\\S-" cur))
15623 (concat " [" cur "]") "") ": "))
15624 (set-function (org-set-property-function property))
15625 (val (if allowed
15626 (funcall set-function prompt allowed nil
15627 (not (get-text-property 0 'org-unrestricted
15628 (caar allowed))))
15629 (funcall set-function prompt
15630 (mapcar 'list (org-property-values property))
15631 nil nil "" nil cur))))
15632 (org-trim val)))
15634 (defvar org-last-set-property nil)
15635 (defvar org-last-set-property-value nil)
15636 (defun org-read-property-name ()
15637 "Read a property name."
15638 (let ((completion-ignore-case t)
15639 (default-prop (or (and (org-at-property-p)
15640 (match-string-no-properties 2))
15641 org-last-set-property)))
15642 (org-completing-read
15643 (concat "Property"
15644 (if default-prop (concat " [" default-prop "]") "")
15645 ": ")
15646 (mapcar #'list (org-buffer-property-keys nil t t))
15647 nil nil nil nil default-prop)))
15649 (defun org-set-property-and-value (use-last)
15650 "Allow to set [PROPERTY]: [value] direction from prompt.
15651 When use-default, don't even ask, just use the last
15652 \"[PROPERTY]: [value]\" string from the history."
15653 (interactive "P")
15654 (let* ((completion-ignore-case t)
15655 (pv (or (and use-last org-last-set-property-value)
15656 (org-completing-read
15657 "Enter a \"[Property]: [value]\" pair: "
15658 nil nil nil nil nil
15659 org-last-set-property-value)))
15660 prop val)
15661 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15662 (setq prop (match-string 1 pv)
15663 val (match-string 2 pv))
15664 (org-set-property prop val))))
15666 (defun org-set-property (property value)
15667 "In the current entry, set PROPERTY to VALUE.
15669 When called interactively, this will prompt for a property name, offering
15670 completion on existing and default properties. And then it will prompt
15671 for a value, offering completion either on allowed values (via an inherited
15672 xxx_ALL property) or on existing values in other instances of this property
15673 in the current file.
15675 Throw an error when trying to set a property with an invalid name."
15676 (interactive (list nil nil))
15677 (let ((property (or property (org-read-property-name))))
15678 ;; `org-entry-put' also makes the following check, but this one
15679 ;; avoids polluting `org-last-set-property' and
15680 ;; `org-last-set-property-value' needlessly.
15681 (unless (org--valid-property-p property)
15682 (user-error "Invalid property name: \"%s\"" property))
15683 (let ((value (or value (org-read-property-value property)))
15684 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15685 (setq org-last-set-property property)
15686 (setq org-last-set-property-value (concat property ": " value))
15687 ;; Possibly postprocess the inserted value:
15688 (when fn (setq value (funcall fn value)))
15689 (unless (equal (org-entry-get nil property) value)
15690 (org-entry-put nil property value)))))
15692 (defun org-find-property (property &optional value)
15693 "Find first entry in buffer that sets PROPERTY.
15695 When optional argument VALUE is non-nil, only consider an entry
15696 if it contains PROPERTY set to this value. If PROPERTY should be
15697 explicitly set to nil, use string \"nil\" for VALUE.
15699 Return position where the entry begins, or nil if there is no
15700 such entry. If narrowing is in effect, only search the visible
15701 part of the buffer."
15702 (save-excursion
15703 (goto-char (point-min))
15704 (let ((case-fold-search t)
15705 (re (org-re-property property nil (not value) value)))
15706 (catch 'exit
15707 (while (re-search-forward re nil t)
15708 (when (if value (org-at-property-p)
15709 (org-entry-get (point) property nil t))
15710 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15712 (defun org-delete-property (property)
15713 "In the current entry, delete PROPERTY."
15714 (interactive
15715 (let* ((completion-ignore-case t)
15716 (cat (org-entry-get (point) "CATEGORY"))
15717 (props0 (org-entry-properties nil 'standard))
15718 (props (if cat props0
15719 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15720 (prop (if (< 1 (length props))
15721 (completing-read "Property: " props nil t)
15722 (caar props))))
15723 (list prop)))
15724 (if (not property)
15725 (message "No property to delete in this entry")
15726 (org-entry-delete nil property)
15727 (message "Property \"%s\" deleted" property)))
15729 (defun org-delete-property-globally (property)
15730 "Remove PROPERTY globally, from all entries.
15731 This function ignores narrowing, if any."
15732 (interactive
15733 (let* ((completion-ignore-case t)
15734 (prop (completing-read
15735 "Globally remove property: "
15736 (mapcar #'list (org-buffer-property-keys)))))
15737 (list prop)))
15738 (org-with-wide-buffer
15739 (goto-char (point-min))
15740 (let ((count 0)
15741 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15742 (while (re-search-forward re nil t)
15743 (when (org-entry-delete (point) property) (cl-incf count)))
15744 (message "Property \"%s\" removed from %d entries" property count))))
15746 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15748 (defun org-compute-property-at-point ()
15749 "Compute the property at point.
15750 This looks for an enclosing column format, extracts the operator and
15751 then applies it to the property in the column format's scope."
15752 (interactive)
15753 (unless (org-at-property-p)
15754 (user-error "Not at a property"))
15755 (let ((prop (match-string-no-properties 2)))
15756 (org-columns-get-format-and-top-level)
15757 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15758 (user-error "No operator defined for property %s" prop))
15759 (org-columns-compute prop)))
15761 (defvar org-property-allowed-value-functions nil
15762 "Hook for functions supplying allowed values for a specific property.
15763 The functions must take a single argument, the name of the property, and
15764 return a flat list of allowed values. If \":ETC\" is one of
15765 the values, this means that these values are intended as defaults for
15766 completion, but that other values should be allowed too.
15767 The functions must return nil if they are not responsible for this
15768 property.")
15770 (defun org-property-get-allowed-values (pom property &optional table)
15771 "Get allowed values for the property PROPERTY.
15772 When TABLE is non-nil, return an alist that can directly be used for
15773 completion."
15774 (let (vals)
15775 (cond
15776 ((equal property "TODO")
15777 (setq vals (org-with-point-at pom
15778 (append org-todo-keywords-1 '("")))))
15779 ((equal property "PRIORITY")
15780 (let ((n org-lowest-priority))
15781 (while (>= n org-highest-priority)
15782 (push (char-to-string n) vals)
15783 (setq n (1- n)))))
15784 ((equal property "CATEGORY"))
15785 ((member property org-special-properties))
15786 ((setq vals (run-hook-with-args-until-success
15787 'org-property-allowed-value-functions property)))
15789 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15790 (when (and vals (string-match "\\S-" vals))
15791 (setq vals (car (read-from-string (concat "(" vals ")"))))
15792 (setq vals (mapcar (lambda (x)
15793 (cond ((stringp x) x)
15794 ((numberp x) (number-to-string x))
15795 ((symbolp x) (symbol-name x))
15796 (t "???")))
15797 vals)))))
15798 (when (member ":ETC" vals)
15799 (setq vals (remove ":ETC" vals))
15800 (org-add-props (car vals) '(org-unrestricted t)))
15801 (if table (mapcar 'list vals) vals)))
15803 (defun org-property-previous-allowed-value (&optional _previous)
15804 "Switch to the next allowed value for this property."
15805 (interactive)
15806 (org-property-next-allowed-value t))
15808 (defun org-property-next-allowed-value (&optional previous)
15809 "Switch to the next allowed value for this property."
15810 (interactive)
15811 (unless (org-at-property-p)
15812 (user-error "Not at a property"))
15813 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15814 (key (match-string 2))
15815 (value (match-string 3))
15816 (allowed (or (org-property-get-allowed-values (point) key)
15817 (and (member value '("[ ]" "[-]" "[X]"))
15818 '("[ ]" "[X]"))))
15819 (heading (save-match-data (nth 4 (org-heading-components))))
15820 nval)
15821 (unless allowed
15822 (user-error "Allowed values for this property have not been defined"))
15823 (when previous (setq allowed (reverse allowed)))
15824 (when (member value allowed)
15825 (setq nval (car (cdr (member value allowed)))))
15826 (setq nval (or nval (car allowed)))
15827 (when (equal nval value)
15828 (user-error "Only one allowed value for this property"))
15829 (org-at-property-p)
15830 (replace-match (concat " :" key ": " nval) t t)
15831 (org-indent-line)
15832 (beginning-of-line 1)
15833 (skip-chars-forward " \t")
15834 (when (equal prop org-effort-property)
15835 (org-refresh-property
15836 '((effort . identity)
15837 (effort-minutes . org-duration-to-minutes))
15838 nval)
15839 (when (string= org-clock-current-task heading)
15840 (setq org-clock-effort nval)
15841 (org-clock-update-mode-line)))
15842 (run-hook-with-args 'org-property-changed-functions key nval)))
15844 (defun org-find-olp (path &optional this-buffer)
15845 "Return a marker pointing to the entry at outline path OLP.
15846 If anything goes wrong, throw an error.
15847 You can wrap this call to catch the error like this:
15849 (condition-case msg
15850 (org-mobile-locate-entry (match-string 4))
15851 (error (nth 1 msg)))
15853 The return value will then be either a string with the error message,
15854 or a marker if everything is OK.
15856 If THIS-BUFFER is set, the outline path does not contain a file,
15857 only headings."
15858 (let* ((file (if this-buffer buffer-file-name (pop path)))
15859 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15860 (level 1)
15861 (lmin 1)
15862 (lmax 1)
15863 end found flevel)
15864 (unless buffer (error "File not found :%s" file))
15865 (with-current-buffer buffer
15866 (unless (derived-mode-p 'org-mode)
15867 (error "Buffer %s needs to be in Org mode" buffer))
15868 (org-with-wide-buffer
15869 (goto-char (point-min))
15870 (dolist (heading path)
15871 (let ((re (format org-complex-heading-regexp-format
15872 (regexp-quote heading)))
15873 (cnt 0))
15874 (while (re-search-forward re end t)
15875 (setq level (- (match-end 1) (match-beginning 1)))
15876 (when (and (>= level lmin) (<= level lmax))
15877 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15878 (when (= cnt 0)
15879 (error "Heading not found on level %d: %s" lmax heading))
15880 (when (> cnt 1)
15881 (error "Heading not unique on level %d: %s" lmax heading))
15882 (goto-char found)
15883 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15884 (setq end (save-excursion (org-end-of-subtree t t)))))
15885 (when (org-at-heading-p)
15886 (point-marker))))))
15888 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15889 "Find node HEADING in BUFFER.
15890 Return a marker to the heading if it was found, or nil if not.
15891 If POS-ONLY is set, return just the position instead of a marker.
15893 The heading text must match exact, but it may have a TODO keyword,
15894 a priority cookie and tags in the standard locations."
15895 (with-current-buffer (or buffer (current-buffer))
15896 (org-with-wide-buffer
15897 (goto-char (point-min))
15898 (let (case-fold-search)
15899 (when (re-search-forward
15900 (format org-complex-heading-regexp-format
15901 (regexp-quote heading)) nil t)
15902 (if pos-only
15903 (match-beginning 0)
15904 (move-marker (make-marker) (match-beginning 0))))))))
15906 (defun org-find-exact-heading-in-directory (heading &optional dir)
15907 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15908 When the target headline is found, return a marker to this location."
15909 (let ((files (directory-files (or dir default-directory)
15910 t "\\`[^.#].*\\.org\\'"))
15911 visiting m buffer)
15912 (catch 'found
15913 (dolist (file files)
15914 (message "trying %s" file)
15915 (setq visiting (org-find-base-buffer-visiting file))
15916 (setq buffer (or visiting (find-file-noselect file)))
15917 (setq m (org-find-exact-headline-in-buffer
15918 heading buffer))
15919 (when (and (not m) (not visiting)) (kill-buffer buffer))
15920 (and m (throw 'found m))))))
15922 (defun org-find-entry-with-id (ident)
15923 "Locate the entry that contains the ID property with exact value IDENT.
15924 IDENT can be a string, a symbol or a number, this function will search for
15925 the string representation of it.
15926 Return the position where this entry starts, or nil if there is no such entry."
15927 (interactive "sID: ")
15928 (let ((id (cond
15929 ((stringp ident) ident)
15930 ((symbolp ident) (symbol-name ident))
15931 ((numberp ident) (number-to-string ident))
15932 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15933 (org-with-wide-buffer (org-find-property "ID" id))))
15935 ;;;; Timestamps
15937 (defvar org-last-changed-timestamp nil)
15938 (defvar org-last-inserted-timestamp nil
15939 "The last time stamp inserted with `org-insert-time-stamp'.")
15941 (defun org-time-stamp (arg &optional inactive)
15942 "Prompt for a date/time and insert a time stamp.
15944 If the user specifies a time like HH:MM or if this command is
15945 called with at least one prefix argument, the time stamp contains
15946 the date and the time. Otherwise, only the date is included.
15948 All parts of a date not specified by the user are filled in from
15949 the timestamp at point, if any, or the current date/time
15950 otherwise.
15952 If there is already a timestamp at the cursor, it is replaced.
15954 With two universal prefix arguments, insert an active timestamp
15955 with the current time without prompting the user.
15957 When called from lisp, the timestamp is inactive if INACTIVE is
15958 non-nil."
15959 (interactive "P")
15960 (let* ((ts (cond
15961 ((org-at-date-range-p t)
15962 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15963 ((org-at-timestamp-p 'lax) (match-string 0))))
15964 ;; Default time is either the timestamp at point or today.
15965 ;; When entering a range, only the range start is considered.
15966 (default-time (if (not ts) (current-time)
15967 (apply #'encode-time (org-parse-time-string ts))))
15968 (default-input (and ts (org-get-compact-tod ts)))
15969 (repeater (and ts
15970 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15971 (match-string 0 ts)))
15972 org-time-was-given
15973 org-end-time-was-given
15974 (time
15975 (and (if (equal arg '(16)) (current-time)
15976 ;; Preserve `this-command' and `last-command'.
15977 (let ((this-command this-command)
15978 (last-command last-command))
15979 (org-read-date
15980 arg 'totime nil nil default-time default-input
15981 inactive))))))
15982 (cond
15983 ((and ts
15984 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15985 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15986 (insert "--")
15987 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15989 ;; Make sure we're on a timestamp. When in the middle of a date
15990 ;; range, move arbitrarily to range end.
15991 (unless (org-at-timestamp-p 'lax)
15992 (skip-chars-forward "-")
15993 (org-at-timestamp-p 'lax))
15994 (replace-match "")
15995 (setq org-last-changed-timestamp
15996 (org-insert-time-stamp
15997 time (or org-time-was-given arg)
15998 inactive nil nil (list org-end-time-was-given)))
15999 (when repeater
16000 (backward-char)
16001 (insert " " repeater)
16002 (setq org-last-changed-timestamp
16003 (concat (substring org-last-inserted-timestamp 0 -1)
16004 " " repeater ">")))
16005 (message "Timestamp updated"))
16006 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16007 (t (org-insert-time-stamp
16008 time (or org-time-was-given arg) inactive nil nil
16009 (list org-end-time-was-given))))))
16011 ;; FIXME: can we use this for something else, like computing time differences?
16012 (defun org-get-compact-tod (s)
16013 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16014 (let* ((t1 (match-string 1 s))
16015 (h1 (string-to-number (match-string 2 s)))
16016 (m1 (string-to-number (match-string 3 s)))
16017 (t2 (and (match-end 4) (match-string 5 s)))
16018 (h2 (and t2 (string-to-number (match-string 6 s))))
16019 (m2 (and t2 (string-to-number (match-string 7 s))))
16020 dh dm)
16021 (if (not t2)
16023 (setq dh (- h2 h1) dm (- m2 m1))
16024 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16025 (concat t1 "+" (number-to-string dh)
16026 (and (/= 0 dm) (format ":%02d" dm)))))))
16028 (defun org-time-stamp-inactive (&optional arg)
16029 "Insert an inactive time stamp.
16031 An inactive time stamp is enclosed in square brackets instead of angle
16032 brackets. It is inactive in the sense that it does not trigger agenda entries,
16033 does not link to the calendar and cannot be changed with the S-cursor keys.
16034 So these are more for recording a certain time/date.
16036 If the user specifies a time like HH:MM or if this command is called with
16037 at least one prefix argument, the time stamp contains the date and the time.
16038 Otherwise, only the date is included.
16040 When called with two universal prefix arguments, insert an active time stamp
16041 with the current time without prompting the user."
16042 (interactive "P")
16043 (org-time-stamp arg 'inactive))
16045 (defvar org-date-ovl (make-overlay 1 1))
16046 (overlay-put org-date-ovl 'face 'org-date-selected)
16047 (delete-overlay org-date-ovl)
16049 (defvar org-ans1) ; dynamically scoped parameter
16050 (defvar org-ans2) ; dynamically scoped parameter
16052 (defvar org-plain-time-of-day-regexp) ; defined below
16054 (defvar org-overriding-default-time nil) ; dynamically scoped
16055 (defvar org-read-date-overlay nil)
16056 (defvar org-dcst nil) ; dynamically scoped
16057 (defvar org-read-date-history nil)
16058 (defvar org-read-date-final-answer nil)
16059 (defvar org-read-date-analyze-futurep nil)
16060 (defvar org-read-date-analyze-forced-year nil)
16061 (defvar org-read-date-inactive)
16063 (defvar org-read-date-minibuffer-local-map
16064 (let* ((map (make-sparse-keymap)))
16065 (set-keymap-parent map minibuffer-local-map)
16066 (org-defkey map (kbd ".")
16067 (lambda () (interactive)
16068 ;; Are we at the beginning of the prompt?
16069 (if (looking-back "^[^:]+: "
16070 (let ((inhibit-field-text-motion t))
16071 (line-beginning-position)))
16072 (org-eval-in-calendar '(calendar-goto-today))
16073 (insert "."))))
16074 (org-defkey map (kbd "C-.")
16075 (lambda () (interactive)
16076 (org-eval-in-calendar '(calendar-goto-today))))
16077 (org-defkey map (kbd "M-S-<left>")
16078 (lambda () (interactive)
16079 (org-eval-in-calendar '(calendar-backward-month 1))))
16080 (org-defkey map (kbd "ESC S-<left>")
16081 (lambda () (interactive)
16082 (org-eval-in-calendar '(calendar-backward-month 1))))
16083 (org-defkey map (kbd "M-S-<right>")
16084 (lambda () (interactive)
16085 (org-eval-in-calendar '(calendar-forward-month 1))))
16086 (org-defkey map (kbd "ESC S-<right>")
16087 (lambda () (interactive)
16088 (org-eval-in-calendar '(calendar-forward-month 1))))
16089 (org-defkey map (kbd "M-S-<up>")
16090 (lambda () (interactive)
16091 (org-eval-in-calendar '(calendar-backward-year 1))))
16092 (org-defkey map (kbd "ESC S-<up>")
16093 (lambda () (interactive)
16094 (org-eval-in-calendar '(calendar-backward-year 1))))
16095 (org-defkey map (kbd "M-S-<down>")
16096 (lambda () (interactive)
16097 (org-eval-in-calendar '(calendar-forward-year 1))))
16098 (org-defkey map (kbd "ESC S-<down>")
16099 (lambda () (interactive)
16100 (org-eval-in-calendar '(calendar-forward-year 1))))
16101 (org-defkey map (kbd "S-<up>")
16102 (lambda () (interactive)
16103 (org-eval-in-calendar '(calendar-backward-week 1))))
16104 (org-defkey map (kbd "S-<down>")
16105 (lambda () (interactive)
16106 (org-eval-in-calendar '(calendar-forward-week 1))))
16107 (org-defkey map (kbd "S-<left>")
16108 (lambda () (interactive)
16109 (org-eval-in-calendar '(calendar-backward-day 1))))
16110 (org-defkey map (kbd "S-<right>")
16111 (lambda () (interactive)
16112 (org-eval-in-calendar '(calendar-forward-day 1))))
16113 (org-defkey map (kbd "!")
16114 (lambda () (interactive)
16115 (org-eval-in-calendar '(diary-view-entries))
16116 (message "")))
16117 (org-defkey map (kbd ">")
16118 (lambda () (interactive)
16119 (org-eval-in-calendar '(calendar-scroll-left 1))))
16120 (org-defkey map (kbd "<")
16121 (lambda () (interactive)
16122 (org-eval-in-calendar '(calendar-scroll-right 1))))
16123 (org-defkey map (kbd "C-v")
16124 (lambda () (interactive)
16125 (org-eval-in-calendar
16126 '(calendar-scroll-left-three-months 1))))
16127 (org-defkey map (kbd "M-v")
16128 (lambda () (interactive)
16129 (org-eval-in-calendar
16130 '(calendar-scroll-right-three-months 1))))
16131 map)
16132 "Keymap for minibuffer commands when using `org-read-date'.")
16134 (defvar org-def)
16135 (defvar org-defdecode)
16136 (defvar org-with-time)
16138 (defvar calendar-setup) ; Dynamically scoped.
16139 (defun org-read-date (&optional with-time to-time from-string prompt
16140 default-time default-input inactive)
16141 "Read a date, possibly a time, and make things smooth for the user.
16142 The prompt will suggest to enter an ISO date, but you can also enter anything
16143 which will at least partially be understood by `parse-time-string'.
16144 Unrecognized parts of the date will default to the current day, month, year,
16145 hour and minute. If this command is called to replace a timestamp at point,
16146 or to enter the second timestamp of a range, the default time is taken
16147 from the existing stamp. Furthermore, the command prefers the future,
16148 so if you are giving a date where the year is not given, and the day-month
16149 combination is already past in the current year, it will assume you
16150 mean next year. For details, see the manual. A few examples:
16152 3-2-5 --> 2003-02-05
16153 feb 15 --> currentyear-02-15
16154 2/15 --> currentyear-02-15
16155 sep 12 9 --> 2009-09-12
16156 12:45 --> today 12:45
16157 22 sept 0:34 --> currentyear-09-22 0:34
16158 12 --> currentyear-currentmonth-12
16159 Fri --> nearest Friday after today
16160 -Tue --> last Tuesday
16161 etc.
16163 Furthermore you can specify a relative date by giving, as the *first* thing
16164 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16165 change in days weeks, months, years.
16166 With a single plus or minus, the date is relative to today. With a double
16167 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16168 +4d --> four days from today
16169 +4 --> same as above
16170 +2w --> two weeks from today
16171 ++5 --> five days from default date
16173 The function understands only English month and weekday abbreviations.
16175 While prompting, a calendar is popped up - you can also select the
16176 date with the mouse (button 1). The calendar shows a period of three
16177 months. To scroll it to other months, use the keys `>' and `<'.
16178 If you don't like the calendar, turn it off with
16179 (setq org-read-date-popup-calendar nil)
16181 With optional argument TO-TIME, the date will immediately be converted
16182 to an internal time.
16183 With an optional argument WITH-TIME, the prompt will suggest to
16184 also insert a time. Note that when WITH-TIME is not set, you can
16185 still enter a time, and this function will inform the calling routine
16186 about this change. The calling routine may then choose to change the
16187 format used to insert the time stamp into the buffer to include the time.
16188 With optional argument FROM-STRING, read from this string instead from
16189 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16190 the time/date that is used for everything that is not specified by the
16191 user."
16192 (require 'parse-time)
16193 (let* ((org-with-time with-time)
16194 (org-time-stamp-rounding-minutes
16195 (if (equal org-with-time '(16))
16196 '(0 0)
16197 org-time-stamp-rounding-minutes))
16198 (org-dcst org-display-custom-times)
16199 (ct (org-current-time))
16200 (org-def (or org-overriding-default-time default-time ct))
16201 (org-defdecode (decode-time org-def))
16202 (cur-frame (selected-frame))
16203 (mouse-autoselect-window nil) ; Don't let the mouse jump
16204 (calendar-setup
16205 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16206 (calendar-move-hook nil)
16207 (calendar-view-diary-initially-flag nil)
16208 (calendar-view-holidays-initially-flag nil)
16209 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16210 ;; Rationalize `org-def' and `org-defdecode', if required.
16211 (when (< (nth 2 org-defdecode) org-extend-today-until)
16212 (setf (nth 2 org-defdecode) -1)
16213 (setf (nth 1 org-defdecode) 59)
16214 (setq org-def (apply #'encode-time org-defdecode))
16215 (setq org-defdecode (decode-time org-def)))
16216 (let* ((timestr (format-time-string
16217 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16218 org-def))
16219 (prompt (concat (if prompt (concat prompt " ") "")
16220 (format "Date+time [%s]: " timestr))))
16221 (cond
16222 (from-string (setq ans from-string))
16223 (org-read-date-popup-calendar
16224 (save-excursion
16225 (save-window-excursion
16226 (calendar)
16227 (when (eq calendar-setup 'calendar-only)
16228 (setq cal-frame
16229 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16230 (select-frame cal-frame))
16231 (org-eval-in-calendar '(setq cursor-type nil) t)
16232 (unwind-protect
16233 (progn
16234 (calendar-forward-day (- (time-to-days org-def)
16235 (calendar-absolute-from-gregorian
16236 (calendar-current-date))))
16237 (org-eval-in-calendar nil t)
16238 (let* ((old-map (current-local-map))
16239 (map (copy-keymap calendar-mode-map))
16240 (minibuffer-local-map
16241 (copy-keymap org-read-date-minibuffer-local-map)))
16242 (org-defkey map (kbd "RET") 'org-calendar-select)
16243 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16244 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16245 (unwind-protect
16246 (progn
16247 (use-local-map map)
16248 (setq org-read-date-inactive inactive)
16249 (add-hook 'post-command-hook 'org-read-date-display)
16250 (setq org-ans0
16251 (read-string prompt
16252 default-input
16253 'org-read-date-history
16254 nil))
16255 ;; org-ans0: from prompt
16256 ;; org-ans1: from mouse click
16257 ;; org-ans2: from calendar motion
16258 (setq ans
16259 (concat org-ans0 " " (or org-ans1 org-ans2))))
16260 (remove-hook 'post-command-hook 'org-read-date-display)
16261 (use-local-map old-map)
16262 (when org-read-date-overlay
16263 (delete-overlay org-read-date-overlay)
16264 (setq org-read-date-overlay nil)))))
16265 (bury-buffer "*Calendar*")
16266 (when cal-frame
16267 (delete-frame cal-frame)
16268 (select-frame-set-input-focus cur-frame))))))
16270 (t ; Naked prompt only
16271 (unwind-protect
16272 (setq ans (read-string prompt default-input
16273 'org-read-date-history timestr))
16274 (when org-read-date-overlay
16275 (delete-overlay org-read-date-overlay)
16276 (setq org-read-date-overlay nil))))))
16278 (setq final (org-read-date-analyze ans org-def org-defdecode))
16280 (when org-read-date-analyze-forced-year
16281 (message "Year was forced into %s"
16282 (if org-read-date-force-compatible-dates
16283 "compatible range (1970-2037)"
16284 "range representable on this machine"))
16285 (ding))
16287 ;; One round trip to get rid of 34th of August and stuff like that....
16288 (setq final (decode-time (apply 'encode-time final)))
16290 (setq org-read-date-final-answer ans)
16292 (if to-time
16293 (apply 'encode-time final)
16294 (if (and (boundp 'org-time-was-given) org-time-was-given)
16295 (format "%04d-%02d-%02d %02d:%02d"
16296 (nth 5 final) (nth 4 final) (nth 3 final)
16297 (nth 2 final) (nth 1 final))
16298 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16300 (defun org-read-date-display ()
16301 "Display the current date prompt interpretation in the minibuffer."
16302 (when org-read-date-display-live
16303 (when org-read-date-overlay
16304 (delete-overlay org-read-date-overlay))
16305 (when (minibufferp (current-buffer))
16306 (save-excursion
16307 (end-of-line 1)
16308 (while (not (equal (buffer-substring
16309 (max (point-min) (- (point) 4)) (point))
16310 " "))
16311 (insert " ")))
16312 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16313 " " (or org-ans1 org-ans2)))
16314 (org-end-time-was-given nil)
16315 (f (org-read-date-analyze ans org-def org-defdecode))
16316 (fmts (if org-dcst
16317 org-time-stamp-custom-formats
16318 org-time-stamp-formats))
16319 (fmt (if (or org-with-time
16320 (and (boundp 'org-time-was-given) org-time-was-given))
16321 (cdr fmts)
16322 (car fmts)))
16323 (txt (format-time-string fmt (apply 'encode-time f)))
16324 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16325 (txt (concat "=> " txt)))
16326 (when (and org-end-time-was-given
16327 (string-match org-plain-time-of-day-regexp txt))
16328 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16329 org-end-time-was-given
16330 (substring txt (match-end 0)))))
16331 (when org-read-date-analyze-futurep
16332 (setq txt (concat txt " (=>F)")))
16333 (setq org-read-date-overlay
16334 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16335 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16337 (defun org-read-date-analyze (ans def defdecode)
16338 "Analyze the combined answer of the date prompt."
16339 ;; FIXME: cleanup and comment
16340 ;; Pass `current-time' result to `decode-time' (instead of calling
16341 ;; without arguments) so that only `current-time' has to be
16342 ;; overridden in tests.
16343 (let ((org-def def)
16344 (org-defdecode defdecode)
16345 (nowdecode (decode-time (current-time)))
16346 delta deltan deltaw deltadef year month day
16347 hour minute second wday pm h2 m2 tl wday1
16348 iso-year iso-weekday iso-week iso-date futurep kill-year)
16349 (setq org-read-date-analyze-futurep nil
16350 org-read-date-analyze-forced-year nil)
16351 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16352 (setq ans "+0"))
16354 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16355 (setq ans (replace-match "" t t ans)
16356 deltan (car delta)
16357 deltaw (nth 1 delta)
16358 deltadef (nth 2 delta)))
16360 ;; Check if there is an iso week date in there. If yes, store the
16361 ;; info and postpone interpreting it until the rest of the parsing
16362 ;; is done.
16363 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16364 (setq iso-year (when (match-end 1)
16365 (org-small-year-to-year
16366 (string-to-number (match-string 1 ans))))
16367 iso-weekday (when (match-end 3)
16368 (string-to-number (match-string 3 ans)))
16369 iso-week (string-to-number (match-string 2 ans)))
16370 (setq ans (replace-match "" t t ans)))
16372 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16373 (when (string-match
16374 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16375 (setq year (if (match-end 2)
16376 (string-to-number (match-string 2 ans))
16377 (progn (setq kill-year t)
16378 (string-to-number (format-time-string "%Y"))))
16379 month (string-to-number (match-string 3 ans))
16380 day (string-to-number (match-string 4 ans)))
16381 (setq year (org-small-year-to-year year))
16382 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16383 t nil ans)))
16385 ;; Help matching dotted european dates
16386 (when (string-match
16387 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16388 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16389 (setq kill-year t)
16390 (string-to-number (format-time-string "%Y")))
16391 day (string-to-number (match-string 1 ans))
16392 month (string-to-number (match-string 2 ans))
16393 ans (replace-match (format "%04d-%02d-%02d" year month day)
16394 t nil ans)))
16396 ;; Help matching american dates, like 5/30 or 5/30/7
16397 (when (string-match
16398 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16399 (setq year (if (match-end 4)
16400 (string-to-number (match-string 4 ans))
16401 (progn (setq kill-year t)
16402 (string-to-number (format-time-string "%Y"))))
16403 month (string-to-number (match-string 1 ans))
16404 day (string-to-number (match-string 2 ans)))
16405 (setq year (org-small-year-to-year year))
16406 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16407 t nil ans)))
16408 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16409 ;; If there is a time with am/pm, and *no* time without it, we convert
16410 ;; so that matching will be successful.
16411 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16412 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16413 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16414 (setq hour (string-to-number (match-string 1 ans))
16415 minute (if (match-end 3)
16416 (string-to-number (match-string 3 ans))
16418 pm (equal ?p
16419 (string-to-char (downcase (match-string 4 ans)))))
16420 (if (and (= hour 12) (not pm))
16421 (setq hour 0)
16422 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16423 (setq ans (replace-match (format "%02d:%02d" hour minute)
16424 t t ans))))
16426 ;; Check if a time range is given as a duration
16427 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16428 (setq hour (string-to-number (match-string 1 ans))
16429 h2 (+ hour (string-to-number (match-string 3 ans)))
16430 minute (string-to-number (match-string 2 ans))
16431 m2 (+ minute (if (match-end 5) (string-to-number
16432 (match-string 5 ans))0)))
16433 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16434 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16435 t t ans)))
16437 ;; Check if there is a time range
16438 (when (boundp 'org-end-time-was-given)
16439 (setq org-time-was-given nil)
16440 (when (and (string-match org-plain-time-of-day-regexp ans)
16441 (match-end 8))
16442 (setq org-end-time-was-given (match-string 8 ans))
16443 (setq ans (concat (substring ans 0 (match-beginning 7))
16444 (substring ans (match-end 7))))))
16446 (setq tl (parse-time-string ans)
16447 day (or (nth 3 tl) (nth 3 org-defdecode))
16448 month
16449 (cond ((nth 4 tl))
16450 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16451 ;; Day was specified. Make sure DAY+MONTH
16452 ;; combination happens in the future.
16453 ((nth 3 tl)
16454 (setq futurep t)
16455 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16456 (nth 4 nowdecode)))
16457 (t (nth 4 org-defdecode)))
16458 year
16459 (cond ((and (not kill-year) (nth 5 tl)))
16460 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16461 ;; Month was guessed in the future and is at least
16462 ;; equal to NOWDECODE's. Fix year accordingly.
16463 (futurep
16464 (if (or (> month (nth 4 nowdecode))
16465 (>= day (nth 3 nowdecode)))
16466 (nth 5 nowdecode)
16467 (1+ (nth 5 nowdecode))))
16468 ;; Month was specified. Make sure MONTH+YEAR
16469 ;; combination happens in the future.
16470 ((nth 4 tl)
16471 (setq futurep t)
16472 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16473 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16474 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16475 (t (nth 5 nowdecode))))
16476 (t (nth 5 org-defdecode)))
16477 hour (or (nth 2 tl) (nth 2 org-defdecode))
16478 minute (or (nth 1 tl) (nth 1 org-defdecode))
16479 second (or (nth 0 tl) 0)
16480 wday (nth 6 tl))
16482 (when (and (eq org-read-date-prefer-future 'time)
16483 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16484 (equal day (nth 3 nowdecode))
16485 (equal month (nth 4 nowdecode))
16486 (equal year (nth 5 nowdecode))
16487 (nth 2 tl)
16488 (or (< (nth 2 tl) (nth 2 nowdecode))
16489 (and (= (nth 2 tl) (nth 2 nowdecode))
16490 (nth 1 tl)
16491 (< (nth 1 tl) (nth 1 nowdecode)))))
16492 (setq day (1+ day)
16493 futurep t))
16495 ;; Special date definitions below
16496 (cond
16497 (iso-week
16498 ;; There was an iso week
16499 (require 'cal-iso)
16500 (setq futurep nil)
16501 (setq year (or iso-year year)
16502 day (or iso-weekday wday 1)
16503 wday nil ; to make sure that the trigger below does not match
16504 iso-date (calendar-gregorian-from-absolute
16505 (calendar-iso-to-absolute
16506 (list iso-week day year))))
16507 ; FIXME: Should we also push ISO weeks into the future?
16508 ; (when (and org-read-date-prefer-future
16509 ; (not iso-year)
16510 ; (< (calendar-absolute-from-gregorian iso-date)
16511 ; (time-to-days (current-time))))
16512 ; (setq year (1+ year)
16513 ; iso-date (calendar-gregorian-from-absolute
16514 ; (calendar-iso-to-absolute
16515 ; (list iso-week day year)))))
16516 (setq month (car iso-date)
16517 year (nth 2 iso-date)
16518 day (nth 1 iso-date)))
16519 (deltan
16520 (setq futurep nil)
16521 (unless deltadef
16522 ;; Pass `current-time' result to `decode-time' (instead of
16523 ;; calling without arguments) so that only `current-time' has
16524 ;; to be overridden in tests.
16525 (let ((now (decode-time (current-time))))
16526 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16527 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16528 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16529 ((equal deltaw "m") (setq month (+ month deltan)))
16530 ((equal deltaw "y") (setq year (+ year deltan)))))
16531 ((and wday (not (nth 3 tl)))
16532 ;; Weekday was given, but no day, so pick that day in the week
16533 ;; on or after the derived date.
16534 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16535 (unless (equal wday wday1)
16536 (setq day (+ day (% (- wday wday1 -7) 7))))))
16537 (when (and (boundp 'org-time-was-given)
16538 (nth 2 tl))
16539 (setq org-time-was-given t))
16540 (when (< year 100) (setq year (+ 2000 year)))
16541 ;; Check of the date is representable
16542 (if org-read-date-force-compatible-dates
16543 (progn
16544 (when (< year 1970)
16545 (setq year 1970 org-read-date-analyze-forced-year t))
16546 (when (> year 2037)
16547 (setq year 2037 org-read-date-analyze-forced-year t)))
16548 (condition-case nil
16549 (ignore (encode-time second minute hour day month year))
16550 (error
16551 (setq year (nth 5 org-defdecode))
16552 (setq org-read-date-analyze-forced-year t))))
16553 (setq org-read-date-analyze-futurep futurep)
16554 (list second minute hour day month year)))
16556 (defvar parse-time-weekdays)
16557 (defun org-read-date-get-relative (s today default)
16558 "Check string S for special relative date string.
16559 TODAY and DEFAULT are internal times, for today and for a default.
16560 Return shift list (N what def-flag)
16561 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16562 N is the number of WHATs to shift.
16563 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16564 the DEFAULT date rather than TODAY."
16565 (require 'parse-time)
16566 (when (and
16567 (string-match
16568 (concat
16569 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16570 "\\([0-9]+\\)?"
16571 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16572 "\\([ \t]\\|$\\)") s)
16573 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16574 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16575 (string-to-char (substring (match-string 1 s) -1))
16576 ?+))
16577 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16578 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16579 (what (if (match-end 3) (match-string 3 s) "d"))
16580 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16581 (date (if rel default today))
16582 (wday (nth 6 (decode-time date)))
16583 delta)
16584 (if wday1
16585 (progn
16586 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16587 (when (= delta 0) (setq delta 7))
16588 (when (= dir ?-)
16589 (setq delta (- delta 7))
16590 (when (= delta 0) (setq delta -7)))
16591 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16592 (list delta "d" rel))
16593 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16595 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16596 "Turn a user-specified date into the internal representation.
16597 The internal representation needed by the calendar is (month day year).
16598 This is a wrapper to handle the brain-dead convention in calendar that
16599 user function argument order change dependent on argument order."
16600 (pcase calendar-date-style
16601 (`american (list arg1 arg2 arg3))
16602 (`european (list arg2 arg1 arg3))
16603 (`iso (list arg2 arg3 arg1))))
16605 (defun org-eval-in-calendar (form &optional keepdate)
16606 "Eval FORM in the calendar window and return to current window.
16607 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16608 (let ((sf (selected-frame))
16609 (sw (selected-window)))
16610 (select-window (get-buffer-window "*Calendar*" t))
16611 (eval form)
16612 (when (and (not keepdate) (calendar-cursor-to-date))
16613 (let* ((date (calendar-cursor-to-date))
16614 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16615 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16616 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16617 (select-window sw)
16618 (select-frame-set-input-focus sf)))
16620 (defun org-calendar-select ()
16621 "Return to `org-read-date' with the date currently selected.
16622 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16623 (interactive)
16624 (when (calendar-cursor-to-date)
16625 (let* ((date (calendar-cursor-to-date))
16626 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16627 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16628 (when (active-minibuffer-window) (exit-minibuffer))))
16630 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16631 "Insert a date stamp for the date given by the internal TIME.
16632 See `format-time-string' for the format of TIME.
16633 WITH-HM means use the stamp format that includes the time of the day.
16634 INACTIVE means use square brackets instead of angular ones, so that the
16635 stamp will not contribute to the agenda.
16636 PRE and POST are optional strings to be inserted before and after the
16637 stamp.
16638 The command returns the inserted time stamp."
16639 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16640 stamp)
16641 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16642 (insert-before-markers (or pre ""))
16643 (when (listp extra)
16644 (setq extra (car extra))
16645 (if (and (stringp extra)
16646 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16647 (setq extra (format "-%02d:%02d"
16648 (string-to-number (match-string 1 extra))
16649 (string-to-number (match-string 2 extra))))
16650 (setq extra nil)))
16651 (when extra
16652 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16653 (insert-before-markers (setq stamp (format-time-string fmt time)))
16654 (insert-before-markers (or post ""))
16655 (setq org-last-inserted-timestamp stamp)))
16657 (defun org-toggle-time-stamp-overlays ()
16658 "Toggle the use of custom time stamp formats."
16659 (interactive)
16660 (setq org-display-custom-times (not org-display-custom-times))
16661 (unless org-display-custom-times
16662 (let ((p (point-min)) (bmp (buffer-modified-p)))
16663 (while (setq p (next-single-property-change p 'display))
16664 (when (and (get-text-property p 'display)
16665 (eq (get-text-property p 'face) 'org-date))
16666 (remove-text-properties
16667 p (setq p (next-single-property-change p 'display))
16668 '(display t))))
16669 (set-buffer-modified-p bmp)))
16670 (org-restart-font-lock)
16671 (setq org-table-may-need-update t)
16672 (if org-display-custom-times
16673 (message "Time stamps are overlaid with custom format")
16674 (message "Time stamp overlays removed")))
16676 (defun org-display-custom-time (beg end)
16677 "Overlay modified time stamp format over timestamp between BEG and END."
16678 (let* ((ts (buffer-substring beg end))
16679 t1 with-hm tf time str (off 0))
16680 (save-match-data
16681 (setq t1 (org-parse-time-string ts t))
16682 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16683 (setq off (- (match-end 0) (match-beginning 0)))))
16684 (setq end (- end off))
16685 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16686 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16687 time (org-fix-decoded-time t1)
16688 str (org-add-props
16689 (format-time-string
16690 (substring tf 1 -1) (apply 'encode-time time))
16691 nil 'mouse-face 'highlight))
16692 (put-text-property beg end 'display str)))
16694 (defun org-fix-decoded-time (time)
16695 "Set 0 instead of nil for the first 6 elements of time.
16696 Don't touch the rest."
16697 (let ((n 0))
16698 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16700 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16701 "Difference between TIMESTAMP-STRING and now in days.
16702 If SECONDS is non-nil, return the difference in seconds."
16703 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16704 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16705 (funcall fdiff (current-time)))))
16707 (defun org-deadline-close-p (timestamp-string &optional ndays)
16708 "Is the time in TIMESTAMP-STRING close to the current date?"
16709 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16710 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16711 (not (org-entry-is-done-p))))
16713 (defun org-get-wdays (ts &optional delay zero-delay)
16714 "Get the deadline lead time appropriate for timestring TS.
16715 When DELAY is non-nil, get the delay time for scheduled items
16716 instead of the deadline lead time. When ZERO-DELAY is non-nil
16717 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16718 don't try to find the delay cookie in the scheduled timestamp."
16719 (let ((tv (if delay org-scheduled-delay-days
16720 org-deadline-warning-days)))
16721 (cond
16722 ((or (and delay (< tv 0))
16723 (and delay zero-delay (<= tv 0))
16724 (and (not delay) (<= tv 0)))
16725 ;; Enforce this value no matter what
16726 (- tv))
16727 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16728 ;; lead time is specified.
16729 (floor (* (string-to-number (match-string 1 ts))
16730 (cdr (assoc (match-string 2 ts)
16731 '(("d" . 1) ("w" . 7)
16732 ("m" . 30.4) ("y" . 365.25)
16733 ("h" . 0.041667)))))))
16734 ;; go for the default.
16735 (t tv))))
16737 (defun org-calendar-select-mouse (ev)
16738 "Return to `org-read-date' with the date currently selected.
16739 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16740 (interactive "e")
16741 (mouse-set-point ev)
16742 (when (calendar-cursor-to-date)
16743 (let* ((date (calendar-cursor-to-date))
16744 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16745 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16746 (when (active-minibuffer-window) (exit-minibuffer))))
16748 (defun org-check-deadlines (ndays)
16749 "Check if there are any deadlines due or past due.
16750 A deadline is considered due if it happens within `org-deadline-warning-days'
16751 days from today's date. If the deadline appears in an entry marked DONE,
16752 it is not shown. A numeric prefix argument NDAYS can be used to test that
16753 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16754 are shown."
16755 (interactive "P")
16756 (let* ((org-warn-days
16757 (cond
16758 ((equal ndays '(4)) 100000)
16759 (ndays (prefix-numeric-value ndays))
16760 (t (abs org-deadline-warning-days))))
16761 (case-fold-search nil)
16762 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16763 (callback
16764 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16765 (message "%d deadlines past-due or due within %d days"
16766 (org-occur regexp nil callback)
16767 org-warn-days)))
16769 (defsubst org-re-timestamp (type)
16770 "Return a regexp for timestamp TYPE.
16771 Allowed values for TYPE are:
16773 all: all timestamps
16774 active: only active timestamps (<...>)
16775 inactive: only inactive timestamps ([...])
16776 scheduled: only scheduled timestamps
16777 deadline: only deadline timestamps
16778 closed: only closed time-stamps
16780 When TYPE is nil, fall back on returning a regexp that matches
16781 both scheduled and deadline timestamps."
16782 (cl-case type
16783 (all org-ts-regexp-both)
16784 (active org-ts-regexp)
16785 (inactive org-ts-regexp-inactive)
16786 (scheduled org-scheduled-time-regexp)
16787 (deadline org-deadline-time-regexp)
16788 (closed org-closed-time-regexp)
16789 (otherwise
16790 (concat "\\<"
16791 (regexp-opt (list org-deadline-string org-scheduled-string))
16792 " *<\\([^>]+\\)>"))))
16794 (defun org-check-before-date (d)
16795 "Check if there are deadlines or scheduled entries before date D."
16796 (interactive (list (org-read-date)))
16797 (let* ((case-fold-search nil)
16798 (regexp (org-re-timestamp org-ts-type))
16799 (ts-type org-ts-type)
16800 (callback
16801 (lambda ()
16802 (let ((match (match-string 1)))
16803 (and (if (memq ts-type '(active inactive all))
16804 (eq (org-element-type (save-excursion
16805 (backward-char)
16806 (org-element-context)))
16807 'timestamp)
16808 (org-at-planning-p))
16809 (time-less-p
16810 (org-time-string-to-time match)
16811 (org-time-string-to-time d)))))))
16812 (message "%d entries before %s"
16813 (org-occur regexp nil callback)
16814 d)))
16816 (defun org-check-after-date (d)
16817 "Check if there are deadlines or scheduled entries after date D."
16818 (interactive (list (org-read-date)))
16819 (let* ((case-fold-search nil)
16820 (regexp (org-re-timestamp org-ts-type))
16821 (ts-type org-ts-type)
16822 (callback
16823 (lambda ()
16824 (let ((match (match-string 1)))
16825 (and (if (memq ts-type '(active inactive all))
16826 (eq (org-element-type (save-excursion
16827 (backward-char)
16828 (org-element-context)))
16829 'timestamp)
16830 (org-at-planning-p))
16831 (not (time-less-p
16832 (org-time-string-to-time match)
16833 (org-time-string-to-time d))))))))
16834 (message "%d entries after %s"
16835 (org-occur regexp nil callback)
16836 d)))
16838 (defun org-check-dates-range (start-date end-date)
16839 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16840 (interactive (list (org-read-date nil nil nil "Range starts")
16841 (org-read-date nil nil nil "Range end")))
16842 (let ((case-fold-search nil)
16843 (regexp (org-re-timestamp org-ts-type))
16844 (callback
16845 (let ((type org-ts-type))
16846 (lambda ()
16847 (let ((match (match-string 1)))
16848 (and
16849 (if (memq type '(active inactive all))
16850 (eq (org-element-type (save-excursion
16851 (backward-char)
16852 (org-element-context)))
16853 'timestamp)
16854 (org-at-planning-p))
16855 (not (time-less-p
16856 (org-time-string-to-time match)
16857 (org-time-string-to-time start-date)))
16858 (time-less-p
16859 (org-time-string-to-time match)
16860 (org-time-string-to-time end-date))))))))
16861 (message "%d entries between %s and %s"
16862 (org-occur regexp nil callback) start-date end-date)))
16864 (defun org-evaluate-time-range (&optional to-buffer)
16865 "Evaluate a time range by computing the difference between start and end.
16866 Normally the result is just printed in the echo area, but with prefix arg
16867 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16868 If the time range is actually in a table, the result is inserted into the
16869 next column.
16870 For time difference computation, a year is assumed to be exactly 365
16871 days in order to avoid rounding problems."
16872 (interactive "P")
16874 (org-clock-update-time-maybe)
16875 (save-excursion
16876 (unless (org-at-date-range-p t)
16877 (goto-char (point-at-bol))
16878 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16879 (unless (org-at-date-range-p t)
16880 (user-error "Not at a time-stamp range, and none found in current line")))
16881 (let* ((ts1 (match-string 1))
16882 (ts2 (match-string 2))
16883 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16884 (match-end (match-end 0))
16885 (time1 (org-time-string-to-time ts1))
16886 (time2 (org-time-string-to-time ts2))
16887 (t1 (float-time time1))
16888 (t2 (float-time time2))
16889 (diff (abs (- t2 t1)))
16890 (negative (< (- t2 t1) 0))
16891 ;; (ys (floor (* 365 24 60 60)))
16892 (ds (* 24 60 60))
16893 (hs (* 60 60))
16894 (fy "%dy %dd %02d:%02d")
16895 (fy1 "%dy %dd")
16896 (fd "%dd %02d:%02d")
16897 (fd1 "%dd")
16898 (fh "%02d:%02d")
16899 y d h m align)
16900 (if havetime
16901 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16903 d (floor (/ diff ds)) diff (mod diff ds)
16904 h (floor (/ diff hs)) diff (mod diff hs)
16905 m (floor (/ diff 60)))
16906 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16908 d (floor (+ (/ diff ds) 0.5))
16909 h 0 m 0))
16910 (if (not to-buffer)
16911 (message "%s" (org-make-tdiff-string y d h m))
16912 (if (org-at-table-p)
16913 (progn
16914 (goto-char match-end)
16915 (setq align t)
16916 (and (looking-at " *|") (goto-char (match-end 0))))
16917 (goto-char match-end))
16918 (when (looking-at
16919 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16920 (replace-match ""))
16921 (when negative (insert " -"))
16922 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16923 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16924 (insert " " (format fh h m))))
16925 (when align (org-table-align))
16926 (message "Time difference inserted")))))
16928 (defun org-make-tdiff-string (y d h m)
16929 (let ((fmt "")
16930 (l nil))
16931 (when (> y 0)
16932 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16933 (push y l))
16934 (when (> d 0)
16935 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16936 (push d l))
16937 (when (> h 0)
16938 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16939 (push h l))
16940 (when (> m 0)
16941 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16942 (push m l))
16943 (apply 'format fmt (nreverse l))))
16945 (defun org-time-string-to-time (s)
16946 "Convert timestamp string S into internal time."
16947 (apply #'encode-time (org-parse-time-string s)))
16949 (defun org-time-string-to-seconds (s)
16950 "Convert a timestamp string S into a number of seconds."
16951 (float-time (org-time-string-to-time s)))
16953 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16955 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16956 "Convert time stamp S to an absolute day number.
16958 If DAYNR in non-nil, and there is a specifier for a cyclic time
16959 stamp, get the closest date to DAYNR. If PREFER is
16960 `past' (respectively `future') return a date past (respectively
16961 after) or equal to DAYNR.
16963 POS is the location of time stamp S, as a buffer position in
16964 BUFFER.
16966 Diary sexp timestamps are matched against DAYNR, when non-nil.
16967 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16968 signaled."
16969 (cond
16970 ((string-match "\\`%%\\((.*)\\)" s)
16971 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16972 ;; only able to match individual dates. If it fails, raise an
16973 ;; error.
16974 (if (and daynr
16975 (org-diary-sexp-entry
16976 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16977 daynr
16978 (signal 'org-diary-sexp-no-match (list s))))
16979 (daynr (org-closest-date s daynr prefer))
16980 (t (time-to-days
16981 (condition-case errdata
16982 (apply #'encode-time (org-parse-time-string s))
16983 (error (error "Bad timestamp `%s'%s\nError was: %s"
16985 (if (not (and buffer pos)) ""
16986 (format-message " at %d in buffer `%s'" pos buffer))
16987 (cdr errdata))))))))
16989 (defun org-days-to-iso-week (days)
16990 "Return the iso week number."
16991 (require 'cal-iso)
16992 (car (calendar-iso-from-absolute days)))
16994 (defun org-small-year-to-year (year)
16995 "Convert 2-digit years into 4-digit years.
16996 YEAR is expanded into one of the 30 next years, if possible, or
16997 into a past one. Any year larger than 99 is returned unchanged."
16998 (if (>= year 100) year
16999 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17000 (century (/ current 100))
17001 (offset (- year (% current 100))))
17002 (cond ((> offset 30) (+ (* (1- century) 100) year))
17003 ((> offset -70) (+ (* century 100) year))
17004 (t (+ (* (1+ century) 100) year))))))
17006 (defun org-time-from-absolute (d)
17007 "Return the time corresponding to date D.
17008 D may be an absolute day number, or a calendar-type list (month day year)."
17009 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17010 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17012 (defvar org-agenda-current-date)
17013 (defun org-calendar-holiday ()
17014 "List of holidays, for Diary display in Org mode."
17015 (require 'holidays)
17016 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17017 (and hl (mapconcat #'identity hl "; "))))
17019 (defun org-diary-sexp-entry (sexp entry d)
17020 "Process a SEXP diary ENTRY for date D."
17021 (require 'diary-lib)
17022 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17023 ;; dynamically.
17024 (let* ((sexp `(let ((entry ,entry)
17025 (date ',d))
17026 ,(car (read-from-string sexp))))
17027 (result (if calendar-debug-sexp (eval sexp)
17028 (condition-case nil
17029 (eval sexp)
17030 (error
17031 (beep)
17032 (message "Bad sexp at line %d in %s: %s"
17033 (org-current-line)
17034 (buffer-file-name) sexp)
17035 (sleep-for 2))))))
17036 (cond ((stringp result) (split-string result "; "))
17037 ((and (consp result)
17038 (not (consp (cdr result)))
17039 (stringp (cdr result))) (cdr result))
17040 ((and (consp result)
17041 (stringp (car result))) result)
17042 (result entry))))
17044 (defun org-diary-to-ical-string (frombuf)
17045 "Get iCalendar entries from diary entries in buffer FROMBUF.
17046 This uses the icalendar.el library."
17047 (let* ((tmpdir temporary-file-directory)
17048 (tmpfile (make-temp-name
17049 (expand-file-name "orgics" tmpdir)))
17050 buf rtn b e)
17051 (with-current-buffer frombuf
17052 (icalendar-export-region (point-min) (point-max) tmpfile)
17053 (setq buf (find-buffer-visiting tmpfile))
17054 (set-buffer buf)
17055 (goto-char (point-min))
17056 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17057 (setq b (match-beginning 0)))
17058 (goto-char (point-max))
17059 (when (re-search-backward "^END:VEVENT" nil t)
17060 (setq e (match-end 0)))
17061 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17062 (kill-buffer buf)
17063 (delete-file tmpfile)
17064 rtn))
17066 (defun org-closest-date (start current prefer)
17067 "Return closest date to CURRENT starting from START.
17069 CURRENT and START are both time stamps.
17071 When PREFER is `past', return a date that is either CURRENT or
17072 past. When PREFER is `future', return a date that is either
17073 CURRENT or future.
17075 Only time stamps with a repeater are modified. Any other time
17076 stamp stay unchanged. In any case, return value is an absolute
17077 day number."
17078 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17079 ;; No repeater. Do not shift time stamp.
17080 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17081 (let ((value (string-to-number (match-string 1 start)))
17082 (type (match-string 2 start)))
17083 (if (= 0 value)
17084 ;; Repeater with a 0-value is considered as void.
17085 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17086 (let* ((base (org-date-to-gregorian start))
17087 (target (org-date-to-gregorian current))
17088 (sday (calendar-absolute-from-gregorian base))
17089 (cday (calendar-absolute-from-gregorian target))
17090 n1 n2)
17091 ;; If START is already past CURRENT, just return START.
17092 (if (<= cday sday) sday
17093 ;; Compute closest date before (N1) and closest date past
17094 ;; (N2) CURRENT.
17095 (pcase type
17096 ("h"
17097 (let ((missing-hours
17098 (mod (+ (- (* 24 (- cday sday))
17099 (nth 2 (org-parse-time-string start)))
17100 org-extend-today-until)
17101 value)))
17102 (setf n1 (if (= missing-hours 0) cday
17103 (- cday (1+ (/ missing-hours 24)))))
17104 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17105 ((or "d" "w")
17106 (let ((value (if (equal type "w") (* 7 value) value)))
17107 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17108 (setf n2 (+ n1 value))))
17109 ("m"
17110 (let* ((add-months
17111 (lambda (d n)
17112 ;; Add N months to gregorian date D, i.e.,
17113 ;; a list (MONTH DAY YEAR). Return a valid
17114 ;; gregorian date.
17115 (let ((m (+ (nth 0 d) n)))
17116 (list (mod m 12)
17117 (nth 1 d)
17118 (+ (/ m 12) (nth 2 d))))))
17119 (months ; Complete months to TARGET.
17120 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17121 (- (nth 0 target) (nth 0 base))
17122 ;; If START's day is greater than
17123 ;; TARGET's, remove incomplete month.
17124 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17125 value)
17126 value))
17127 (before (funcall add-months base months)))
17128 (setf n1 (calendar-absolute-from-gregorian before))
17129 (setf n2
17130 (calendar-absolute-from-gregorian
17131 (funcall add-months before value)))))
17133 (let* ((d (nth 1 base))
17134 (m (nth 0 base))
17135 (y (nth 2 base))
17136 (years ; Complete years to TARGET.
17137 (* (/ (- (nth 2 target)
17139 ;; If START's month and day are
17140 ;; greater than TARGET's, remove
17141 ;; incomplete year.
17142 (if (or (> (nth 0 target) m)
17143 (and (= (nth 0 target) m)
17144 (> (nth 1 target) d)))
17147 value)
17148 value))
17149 (before (list m d (+ y years))))
17150 (setf n1 (calendar-absolute-from-gregorian before))
17151 (setf n2 (calendar-absolute-from-gregorian
17152 (list m d (+ (nth 2 before) value)))))))
17153 ;; Handle PREFER parameter, if any.
17154 (cond
17155 ((eq prefer 'past) (if (= cday n2) n2 n1))
17156 ((eq prefer 'future) (if (= cday n1) n1 n2))
17157 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17159 (defun org-date-to-gregorian (d)
17160 "Turn any specification of date D into a Gregorian date for the calendar."
17161 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17162 ((and (listp d) (= (length d) 3)) d)
17163 ((stringp d)
17164 (let ((d (org-parse-time-string d)))
17165 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17166 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17168 (defun org-parse-time-string (s &optional nodefault)
17169 "Parse the standard Org time string.
17171 This should be a lot faster than the normal `parse-time-string'.
17173 If time is not given, defaults to 0:00. However, with optional
17174 NODEFAULT, hour and minute fields will be nil if not given."
17175 (cond ((string-match org-ts-regexp0 s)
17176 (list 0
17177 (when (or (match-beginning 8) (not nodefault))
17178 (string-to-number (or (match-string 8 s) "0")))
17179 (when (or (match-beginning 7) (not nodefault))
17180 (string-to-number (or (match-string 7 s) "0")))
17181 (string-to-number (match-string 4 s))
17182 (string-to-number (match-string 3 s))
17183 (string-to-number (match-string 2 s))
17184 nil nil nil))
17185 ((string-match "^<[^>]+>$" s)
17186 ;; FIXME: `decode-time' needs to be called with ZONE as its
17187 ;; second argument. However, this requires at least Emacs
17188 ;; 25.1. We can do it when we switch to this version as our
17189 ;; minimal requirement.
17190 (decode-time (seconds-to-time (org-matcher-time s))))
17191 (t (error "Not a standard Org time string: %s" s))))
17193 (defun org-timestamp-up (&optional arg)
17194 "Increase the date item at the cursor by one.
17195 If the cursor is on the year, change the year. If it is on the month,
17196 the day or the time, change that.
17197 With prefix ARG, change by that many units."
17198 (interactive "p")
17199 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17201 (defun org-timestamp-down (&optional arg)
17202 "Decrease the date item at the cursor by one.
17203 If the cursor is on the year, change the year. If it is on the month,
17204 the day or the time, change that.
17205 With prefix ARG, change by that many units."
17206 (interactive "p")
17207 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17209 (defun org-timestamp-up-day (&optional arg)
17210 "Increase the date in the time stamp by one day.
17211 With prefix ARG, change that many days."
17212 (interactive "p")
17213 (if (and (not (org-at-timestamp-p 'lax))
17214 (org-at-heading-p))
17215 (org-todo 'up)
17216 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17218 (defun org-timestamp-down-day (&optional arg)
17219 "Decrease the date in the time stamp by one day.
17220 With prefix ARG, change that many days."
17221 (interactive "p")
17222 (if (and (not (org-at-timestamp-p 'lax))
17223 (org-at-heading-p))
17224 (org-todo 'down)
17225 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17227 (defun org-at-timestamp-p (&optional extended)
17228 "Non-nil if point is inside a timestamp.
17230 By default, the function only consider syntactically valid active
17231 timestamps. However, the caller may have a broader definition
17232 for timestamps. As a consequence, optional argument EXTENDED can
17233 be set to the following values
17235 `inactive'
17237 Include also syntactically valid inactive timestamps.
17239 `agenda'
17241 Include timestamps allowed in Agenda, i.e., those in
17242 properties drawers, planning lines and clock lines.
17244 `lax'
17246 Ignore context. The function matches any part of the
17247 document looking like a timestamp. This includes comments,
17248 example blocks...
17250 For backward-compatibility with Org 9.0, every other non-nil
17251 value is equivalent to `inactive'.
17253 When at a timestamp, return the position of the point as a symbol
17254 among `bracket', `after', `year', `month', `hour', `minute',
17255 `day' or a number of character from the last know part of the
17256 time stamp.
17258 When matching, the match groups are the following:
17259 group 1: year
17260 group 2: month
17261 group 3: day number
17262 group 4: day name
17263 group 5: hours, if any
17264 group 6: minutes, if any"
17265 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17266 (pos (point))
17267 (match?
17268 (let ((boundaries (org-in-regexp regexp)))
17269 (save-match-data
17270 (cond ((null boundaries) nil)
17271 ((eq extended 'lax) t)
17273 (or (and (eq extended 'agenda)
17274 (or (org-at-planning-p)
17275 (org-at-property-p)
17276 (and (bound-and-true-p
17277 org-agenda-include-inactive-timestamps)
17278 (org-at-clock-log-p))))
17279 (eq 'timestamp
17280 (save-excursion
17281 (when (= pos (cdr boundaries)) (forward-char -1))
17282 (org-element-type (org-element-context)))))))))))
17283 (cond
17284 ((not match?) nil)
17285 ((= pos (match-beginning 0)) 'bracket)
17286 ;; Distinguish location right before the closing bracket from
17287 ;; right after it.
17288 ((= pos (1- (match-end 0))) 'bracket)
17289 ((= pos (match-end 0)) 'after)
17290 ((org-pos-in-match-range pos 2) 'year)
17291 ((org-pos-in-match-range pos 3) 'month)
17292 ((org-pos-in-match-range pos 7) 'hour)
17293 ((org-pos-in-match-range pos 8) 'minute)
17294 ((or (org-pos-in-match-range pos 4)
17295 (org-pos-in-match-range pos 5)) 'day)
17296 ((and (> pos (or (match-end 8) (match-end 5)))
17297 (< pos (match-end 0)))
17298 (- pos (or (match-end 8) (match-end 5))))
17299 (t 'day))))
17301 (defun org-toggle-timestamp-type ()
17302 "Toggle the type (<active> or [inactive]) of a time stamp."
17303 (interactive)
17304 (when (org-at-timestamp-p 'lax)
17305 (let ((beg (match-beginning 0)) (end (match-end 0))
17306 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17307 (save-excursion
17308 (goto-char beg)
17309 (while (re-search-forward "[][<>]" end t)
17310 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17311 t t)))
17312 (message "Timestamp is now %sactive"
17313 (if (equal (char-after beg) ?<) "" "in")))))
17315 (defun org-at-clock-log-p ()
17316 "Non-nil if point is on a clock log line."
17317 (and (org-match-line org-clock-line-re)
17318 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17320 (defvar org-clock-history) ; defined in org-clock.el
17321 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17322 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17323 "Change the date in the time stamp at point.
17324 The date will be changed by N times WHAT. WHAT can be `day', `month',
17325 `year', `minute', `second'. If WHAT is not given, the cursor position
17326 in the timestamp determines what will be changed.
17327 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17328 (let ((origin (point))
17329 (timestamp? (org-at-timestamp-p 'lax))
17330 origin-cat
17331 with-hm inactive
17332 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17333 extra rem
17334 ts time time0 fixnext clrgx)
17335 (unless timestamp? (user-error "Not at a timestamp"))
17336 (if (and (not what) (eq timestamp? 'bracket))
17337 (org-toggle-timestamp-type)
17338 ;; Point isn't on brackets. Remember the part of the time-stamp
17339 ;; the point was in. Indeed, size of time-stamps may change,
17340 ;; but point must be kept in the same category nonetheless.
17341 (setq origin-cat timestamp?)
17342 (when (and (not what) (not (eq timestamp? 'day))
17343 org-display-custom-times
17344 (get-text-property (point) 'display)
17345 (not (get-text-property (1- (point)) 'display)))
17346 (setq timestamp? 'day))
17347 (setq timestamp? (or what timestamp?)
17348 inactive (= (char-after (match-beginning 0)) ?\[)
17349 ts (match-string 0))
17350 (replace-match "")
17351 (when (string-match
17352 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17354 (setq extra (match-string 1 ts))
17355 (when suppress-tmp-delay
17356 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17357 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17358 (setq with-hm t))
17359 (setq time0 (org-parse-time-string ts))
17360 (when (and updown
17361 (eq timestamp? 'minute)
17362 (not current-prefix-arg))
17363 ;; This looks like s-up and s-down. Change by one rounding step.
17364 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17365 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17366 (setcar (cdr time0) (+ (nth 1 time0)
17367 (if (> n 0) (- rem) (- dm rem))))))
17368 (setq time
17369 (apply #'encode-time
17370 (or (car time0) 0)
17371 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17372 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17373 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17374 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17375 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17376 (nthcdr 6 time0)))
17377 (when (and (memq timestamp? '(hour minute))
17378 extra
17379 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17380 (setq extra (org-modify-ts-extra
17381 extra
17382 (if (eq timestamp? 'hour) 2 5)
17383 n dm)))
17384 (when (integerp timestamp?)
17385 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17386 (when (eq what 'calendar)
17387 (let ((cal-date (org-get-date-from-calendar)))
17388 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17389 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17390 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17391 (setcar time0 (or (car time0) 0))
17392 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17393 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17394 (setq time (apply 'encode-time time0))))
17395 ;; Insert the new time-stamp, and ensure point stays in the same
17396 ;; category as before (i.e. not after the last position in that
17397 ;; category).
17398 (let ((pos (point)))
17399 ;; Stay before inserted string. `save-excursion' is of no use.
17400 (setq org-last-changed-timestamp
17401 (org-insert-time-stamp time with-hm inactive nil nil extra))
17402 (goto-char pos))
17403 (save-match-data
17404 (looking-at org-ts-regexp3)
17405 (goto-char
17406 (pcase origin-cat
17407 ;; `day' category ends before `hour' if any, or at the end
17408 ;; of the day name.
17409 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17410 (`hour (min (match-end 7) origin))
17411 (`minute (min (1- (match-end 8)) origin))
17412 ((pred integerp) (min (1- (match-end 0)) origin))
17413 ;; Point was right after the time-stamp. However, the
17414 ;; time-stamp length might have changed, so refer to
17415 ;; (match-end 0) instead.
17416 (`after (match-end 0))
17417 ;; `year' and `month' have both fixed size: point couldn't
17418 ;; have moved into another part.
17419 (_ origin))))
17420 ;; Update clock if on a CLOCK line.
17421 (org-clock-update-time-maybe)
17422 ;; Maybe adjust the closest clock in `org-clock-history'
17423 (when org-clock-adjust-closest
17424 (if (not (and (org-at-clock-log-p)
17425 (< 1 (length (delq nil (mapcar 'marker-position
17426 org-clock-history))))))
17427 (message "No clock to adjust")
17428 (cond ((save-excursion ; fix previous clock?
17429 (re-search-backward org-ts-regexp0 nil t)
17430 (looking-back (concat org-clock-string " \\[")
17431 (line-beginning-position)))
17432 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17433 ((save-excursion ; fix next clock?
17434 (re-search-backward org-ts-regexp0 nil t)
17435 (looking-at (concat org-ts-regexp0 "\\] =>")))
17436 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17437 (save-window-excursion
17438 ;; Find closest clock to point, adjust the previous/next one in history
17439 (let* ((p (save-excursion (org-back-to-heading t)))
17440 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17441 (clfixnth
17442 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17443 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17444 (if (not clfixpos)
17445 (message "No clock to adjust")
17446 (save-excursion
17447 (org-goto-marker-or-bmk clfixpos)
17448 (org-show-subtree)
17449 (when (re-search-forward clrgx nil t)
17450 (goto-char (match-beginning 1))
17451 (let (org-clock-adjust-closest)
17452 (org-timestamp-change n timestamp? updown))
17453 (message "Clock adjusted in %s for heading: %s"
17454 (file-name-nondirectory (buffer-file-name))
17455 (org-get-heading t t)))))))))
17456 ;; Try to recenter the calendar window, if any.
17457 (when (and org-calendar-follow-timestamp-change
17458 (get-buffer-window "*Calendar*" t)
17459 (memq timestamp? '(day month year)))
17460 (org-recenter-calendar (time-to-days time))))))
17462 (defun org-modify-ts-extra (s pos n dm)
17463 "Change the different parts of the lead-time and repeat fields in timestamp."
17464 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17465 ng h m new rem)
17466 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17467 (cond
17468 ((or (org-pos-in-match-range pos 2)
17469 (org-pos-in-match-range pos 3))
17470 (setq m (string-to-number (match-string 3 s))
17471 h (string-to-number (match-string 2 s)))
17472 (if (org-pos-in-match-range pos 2)
17473 (setq h (+ h n))
17474 (setq n (* dm (with-no-warnings (signum n))))
17475 (unless (= 0 (setq rem (% m dm)))
17476 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17477 (setq m (+ m n)))
17478 (when (< m 0) (setq m (+ m 60) h (1- h)))
17479 (when (> m 59) (setq m (- m 60) h (1+ h)))
17480 (setq h (mod h 24))
17481 (setq ng 1 new (format "-%02d:%02d" h m)))
17482 ((org-pos-in-match-range pos 6)
17483 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17484 ((org-pos-in-match-range pos 5)
17485 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17487 ((org-pos-in-match-range pos 9)
17488 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17489 ((org-pos-in-match-range pos 8)
17490 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17492 (when ng
17493 (setq s (concat
17494 (substring s 0 (match-beginning ng))
17496 (substring s (match-end ng))))))
17499 (defun org-recenter-calendar (d)
17500 "If the calendar is visible, recenter it to date D."
17501 (let ((cwin (get-buffer-window "*Calendar*" t)))
17502 (when cwin
17503 (let ((calendar-move-hook nil))
17504 (with-selected-window cwin
17505 (calendar-goto-date
17506 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17508 (defun org-goto-calendar (&optional arg)
17509 "Go to the Emacs calendar at the current date.
17510 If there is a time stamp in the current line, go to that date.
17511 A prefix ARG can be used to force the current date."
17512 (interactive "P")
17513 (let ((calendar-move-hook nil)
17514 (calendar-view-holidays-initially-flag nil)
17515 (calendar-view-diary-initially-flag nil)
17516 diff)
17517 (when (or (org-at-timestamp-p 'lax)
17518 (org-match-line (concat ".*" org-ts-regexp)))
17519 (let ((d1 (time-to-days (current-time)))
17520 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17521 (setq diff (- d2 d1))))
17522 (calendar)
17523 (calendar-goto-today)
17524 (when (and diff (not arg)) (calendar-forward-day diff))))
17526 (defun org-get-date-from-calendar ()
17527 "Return a list (month day year) of date at point in calendar."
17528 (with-current-buffer "*Calendar*"
17529 (save-match-data
17530 (calendar-cursor-to-date))))
17532 (defun org-date-from-calendar ()
17533 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17534 If there is already a time stamp at the cursor position, update it."
17535 (interactive)
17536 (if (org-at-timestamp-p 'lax)
17537 (org-timestamp-change 0 'calendar)
17538 (let ((cal-date (org-get-date-from-calendar)))
17539 (org-insert-time-stamp
17540 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17542 (defcustom org-effort-durations
17543 `(("min" . 1)
17544 ("h" . 60)
17545 ("d" . ,(* 60 8))
17546 ("w" . ,(* 60 8 5))
17547 ("m" . ,(* 60 8 5 4))
17548 ("y" . ,(* 60 8 5 40)))
17549 "Conversion factor to minutes for an effort modifier.
17551 Each entry has the form (MODIFIER . MINUTES).
17553 In an effort string, a number followed by MODIFIER is multiplied
17554 by the specified number of MINUTES to obtain an effort in
17555 minutes.
17557 For example, if the value of this variable is ((\"hours\" . 60)), then an
17558 effort string \"2hours\" is equivalent to 120 minutes."
17559 :group 'org-agenda
17560 :version "26.1"
17561 :package-version '(Org . "8.3")
17562 :type '(alist :key-type (string :tag "Modifier")
17563 :value-type (number :tag "Minutes")))
17565 (defcustom org-image-actual-width t
17566 "Should we use the actual width of images when inlining them?
17568 When set to t, always use the image width.
17570 When set to a number, use imagemagick (when available) to set
17571 the image's width to this value.
17573 When set to a number in a list, try to get the width from any
17574 #+ATTR.* keyword if it matches a width specification like
17576 #+ATTR_HTML: :width 300px
17578 and fall back on that number if none is found.
17580 When set to nil, try to get the width from an #+ATTR.* keyword
17581 and fall back on the original width if none is found.
17583 This requires Emacs >= 24.1, build with imagemagick support."
17584 :group 'org-appearance
17585 :version "24.4"
17586 :package-version '(Org . "8.0")
17587 :type '(choice
17588 (const :tag "Use the image width" t)
17589 (integer :tag "Use a number of pixels")
17590 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17591 (const :tag "Use #+ATTR* or don't resize" nil)))
17593 (defcustom org-agenda-inhibit-startup nil
17594 "Inhibit startup when preparing agenda buffers.
17595 When this variable is t, the initialization of the Org agenda
17596 buffers is inhibited: e.g. the visibility state is not set, the
17597 tables are not re-aligned, etc."
17598 :type 'boolean
17599 :version "24.3"
17600 :group 'org-agenda)
17602 (defcustom org-agenda-ignore-properties nil
17603 "Avoid updating text properties when building the agenda.
17604 Properties are used to prepare buffers for effort estimates,
17605 appointments, statistics and subtree-local categories.
17606 If you don't use these in the agenda, you can add them to this
17607 list and agenda building will be a bit faster.
17608 The value is a list, with zero or more of the symbols `effort', `appt',
17609 `stats' or `category'."
17610 :type '(set :greedy t
17611 (const effort)
17612 (const appt)
17613 (const stats)
17614 (const category))
17615 :version "26.1"
17616 :package-version '(Org . "8.3")
17617 :group 'org-agenda)
17619 ;;;; Files
17621 (defun org-save-all-org-buffers ()
17622 "Save all Org buffers without user confirmation."
17623 (interactive)
17624 (message "Saving all Org buffers...")
17625 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17626 (when (featurep 'org-id) (org-id-locations-save))
17627 (message "Saving all Org buffers... done"))
17629 (defun org-revert-all-org-buffers ()
17630 "Revert all Org buffers.
17631 Prompt for confirmation when there are unsaved changes.
17632 Be sure you know what you are doing before letting this function
17633 overwrite your changes.
17635 This function is useful in a setup where one tracks Org files
17636 with a version control system, to revert on one machine after pulling
17637 changes from another. I believe the procedure must be like this:
17639 1. M-x org-save-all-org-buffers
17640 2. Pull changes from the other machine, resolve conflicts
17641 3. M-x org-revert-all-org-buffers"
17642 (interactive)
17643 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17644 (user-error "Abort"))
17645 (save-excursion
17646 (save-window-excursion
17647 (dolist (b (buffer-list))
17648 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17649 (with-current-buffer b buffer-file-name))
17650 (pop-to-buffer-same-window b)
17651 (revert-buffer t 'no-confirm)))
17652 (when (and (featurep 'org-id) org-id-track-globally)
17653 (org-id-locations-load)))))
17655 ;;;; Agenda files
17657 ;;;###autoload
17658 (defun org-switchb (&optional arg)
17659 "Switch between Org buffers.
17661 With `\\[universal-argument]' prefix, restrict available buffers to files.
17663 With `\\[universal-argument] \\[universal-argument]' \
17664 prefix, restrict available buffers to agenda files."
17665 (interactive "P")
17666 (let ((blist (org-buffer-list
17667 (cond ((equal arg '(4)) 'files)
17668 ((equal arg '(16)) 'agenda)))))
17669 (pop-to-buffer-same-window
17670 (completing-read "Org buffer: "
17671 (mapcar #'list (mapcar #'buffer-name blist))
17672 nil t))))
17674 (defun org-buffer-list (&optional predicate exclude-tmp)
17675 "Return a list of Org buffers.
17676 PREDICATE can be `export', `files' or `agenda'.
17678 export restrict the list to Export buffers.
17679 files restrict the list to buffers visiting Org files.
17680 agenda restrict the list to buffers visiting agenda files.
17682 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17683 (let* ((bfn nil)
17684 (agenda-files (and (eq predicate 'agenda)
17685 (mapcar 'file-truename (org-agenda-files t))))
17686 (filter
17687 (cond
17688 ((eq predicate 'files)
17689 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17690 ((eq predicate 'export)
17691 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17692 ((eq predicate 'agenda)
17693 (lambda (b)
17694 (with-current-buffer b
17695 (and (derived-mode-p 'org-mode)
17696 (setq bfn (buffer-file-name b))
17697 (member (file-truename bfn) agenda-files)))))
17698 (t (lambda (b) (with-current-buffer b
17699 (or (derived-mode-p 'org-mode)
17700 (string-match "\\*Org .*Export"
17701 (buffer-name b)))))))))
17702 (delq nil
17703 (mapcar
17704 (lambda(b)
17705 (if (and (funcall filter b)
17706 (or (not exclude-tmp)
17707 (not (string-match "tmp" (buffer-name b)))))
17709 nil))
17710 (buffer-list)))))
17712 (defun org-agenda-files (&optional unrestricted archives)
17713 "Get the list of agenda files.
17714 Optional UNRESTRICTED means return the full list even if a restriction
17715 is currently in place.
17716 When ARCHIVES is t, include all archive files that are really being
17717 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17718 `org-agenda-archives-mode' is t."
17719 (let ((files
17720 (cond
17721 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17722 ((stringp org-agenda-files) (org-read-agenda-file-list))
17723 ((listp org-agenda-files) org-agenda-files)
17724 (t (error "Invalid value of `org-agenda-files'")))))
17725 (setq files (apply 'append
17726 (mapcar (lambda (f)
17727 (if (file-directory-p f)
17728 (directory-files
17729 f t org-agenda-file-regexp)
17730 (list f)))
17731 files)))
17732 (when org-agenda-skip-unavailable-files
17733 (setq files (delq nil
17734 (mapcar (function
17735 (lambda (file)
17736 (and (file-readable-p file) file)))
17737 files))))
17738 (when (or (eq archives t)
17739 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17740 (setq files (org-add-archive-files files)))
17741 files))
17743 (defun org-agenda-file-p (&optional file)
17744 "Return non-nil, if FILE is an agenda file.
17745 If FILE is omitted, use the file associated with the current
17746 buffer."
17747 (let ((fname (or file (buffer-file-name))))
17748 (and fname
17749 (member (file-truename fname)
17750 (mapcar #'file-truename (org-agenda-files t))))))
17752 (defun org-edit-agenda-file-list ()
17753 "Edit the list of agenda files.
17754 Depending on setup, this either uses customize to edit the variable
17755 `org-agenda-files', or it visits the file that is holding the list. In the
17756 latter case, the buffer is set up in a way that saving it automatically kills
17757 the buffer and restores the previous window configuration."
17758 (interactive)
17759 (if (stringp org-agenda-files)
17760 (let ((cw (current-window-configuration)))
17761 (find-file org-agenda-files)
17762 (setq-local org-window-configuration cw)
17763 (add-hook 'after-save-hook
17764 (lambda ()
17765 (set-window-configuration
17766 (prog1 org-window-configuration
17767 (kill-buffer (current-buffer))))
17768 (org-install-agenda-files-menu)
17769 (message "New agenda file list installed"))
17770 nil 'local)
17771 (message "%s" (substitute-command-keys
17772 "Edit list and finish with \\[save-buffer]")))
17773 (customize-variable 'org-agenda-files)))
17775 (defun org-store-new-agenda-file-list (list)
17776 "Set new value for the agenda file list and save it correctly."
17777 (if (stringp org-agenda-files)
17778 (let ((fe (org-read-agenda-file-list t)) b u)
17779 (while (setq b (find-buffer-visiting org-agenda-files))
17780 (kill-buffer b))
17781 (with-temp-file org-agenda-files
17782 (insert
17783 (mapconcat
17784 (lambda (f) ;; Keep un-expanded entries.
17785 (if (setq u (assoc f fe))
17786 (cdr u)
17788 list "\n")
17789 "\n")))
17790 (let ((org-mode-hook nil) (org-inhibit-startup t)
17791 (org-insert-mode-line-in-empty-file nil))
17792 (setq org-agenda-files list)
17793 (customize-save-variable 'org-agenda-files org-agenda-files))))
17795 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17796 "Read the list of agenda files from a file.
17797 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17798 filenames, used by `org-store-new-agenda-file-list' to write back
17799 un-expanded file names."
17800 (when (file-directory-p org-agenda-files)
17801 (error "`org-agenda-files' cannot be a single directory"))
17802 (when (stringp org-agenda-files)
17803 (with-temp-buffer
17804 (insert-file-contents org-agenda-files)
17805 (mapcar
17806 (lambda (f)
17807 (let ((e (expand-file-name (substitute-in-file-name f)
17808 org-directory)))
17809 (if pair-with-expansion
17810 (cons e f)
17811 e)))
17812 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17814 ;;;###autoload
17815 (defun org-cycle-agenda-files ()
17816 "Cycle through the files in `org-agenda-files'.
17817 If the current buffer visits an agenda file, find the next one in the list.
17818 If the current buffer does not, find the first agenda file."
17819 (interactive)
17820 (let* ((fs (or (org-agenda-files t)
17821 (user-error "No agenda files")))
17822 (files (copy-sequence fs))
17823 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17824 file)
17825 (when tcf
17826 (while (and (setq file (pop files))
17827 (not (equal (file-truename file) tcf)))))
17828 (find-file (car (or files fs)))
17829 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17831 (defun org-agenda-file-to-front (&optional to-end)
17832 "Move/add the current file to the top of the agenda file list.
17833 If the file is not present in the list, it is added to the front. If it is
17834 present, it is moved there. With optional argument TO-END, add/move to the
17835 end of the list."
17836 (interactive "P")
17837 (let ((org-agenda-skip-unavailable-files nil)
17838 (file-alist (mapcar (lambda (x)
17839 (cons (file-truename x) x))
17840 (org-agenda-files t)))
17841 (ctf (file-truename
17842 (or buffer-file-name
17843 (user-error "Please save the current buffer to a file"))))
17844 x had)
17845 (setq x (assoc ctf file-alist) had x)
17847 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17848 (if to-end
17849 (setq file-alist (append (delq x file-alist) (list x)))
17850 (setq file-alist (cons x (delq x file-alist))))
17851 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17852 (org-install-agenda-files-menu)
17853 (message "File %s to %s of agenda file list"
17854 (if had "moved" "added") (if to-end "end" "front"))))
17856 (defun org-remove-file (&optional file)
17857 "Remove current file from the list of files in variable `org-agenda-files'.
17858 These are the files which are being checked for agenda entries.
17859 Optional argument FILE means use this file instead of the current."
17860 (interactive)
17861 (let* ((org-agenda-skip-unavailable-files nil)
17862 (file (or file buffer-file-name
17863 (user-error "Current buffer does not visit a file")))
17864 (true-file (file-truename file))
17865 (afile (abbreviate-file-name file))
17866 (files (delq nil (mapcar
17867 (lambda (x)
17868 (unless (equal true-file
17869 (file-truename x))
17871 (org-agenda-files t)))))
17872 (if (not (= (length files) (length (org-agenda-files t))))
17873 (progn
17874 (org-store-new-agenda-file-list files)
17875 (org-install-agenda-files-menu)
17876 (message "Removed from Org Agenda list: %s" afile))
17877 (message "File was not in list: %s (not removed)" afile))))
17879 (defun org-file-menu-entry (file)
17880 (vector file (list 'find-file file) t))
17882 (defun org-check-agenda-file (file)
17883 "Make sure FILE exists. If not, ask user what to do."
17884 (unless (file-exists-p file)
17885 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17886 (abbreviate-file-name file))
17887 (let ((r (downcase (read-char-exclusive))))
17888 (cond
17889 ((equal r ?r)
17890 (org-remove-file file)
17891 (throw 'nextfile t))
17892 (t (user-error "Abort"))))))
17894 (defun org-get-agenda-file-buffer (file)
17895 "Get an agenda buffer visiting FILE.
17896 If the buffer needs to be created, add it to the list of buffers
17897 which might be released later."
17898 (let ((buf (org-find-base-buffer-visiting file)))
17899 (if buf
17900 buf ; just return it
17901 ;; Make a new buffer and remember it
17902 (setq buf (find-file-noselect file))
17903 (when buf (push buf org-agenda-new-buffers))
17904 buf)))
17906 (defun org-release-buffers (blist)
17907 "Release all buffers in list, asking the user for confirmation when needed.
17908 When a buffer is unmodified, it is just killed. When modified, it is saved
17909 \(if the user agrees) and then killed."
17910 (let (file)
17911 (dolist (buf blist)
17912 (setq file (buffer-file-name buf))
17913 (when (and (buffer-modified-p buf)
17914 file
17915 (y-or-n-p (format "Save file %s? " file)))
17916 (with-current-buffer buf (save-buffer)))
17917 (kill-buffer buf))))
17919 (defun org-agenda-prepare-buffers (files)
17920 "Create buffers for all agenda files, protect archived trees and comments."
17921 (interactive)
17922 (let ((pa '(:org-archived t))
17923 (pc '(:org-comment t))
17924 (pall '(:org-archived t :org-comment t))
17925 (inhibit-read-only t)
17926 (org-inhibit-startup org-agenda-inhibit-startup)
17927 (rea (org-make-tag-string (list org-archive-tag)))
17928 re pos)
17929 (setq org-tag-alist-for-agenda nil
17930 org-tag-groups-alist-for-agenda nil)
17931 (save-excursion
17932 (save-restriction
17933 (dolist (file files)
17934 (catch 'nextfile
17935 (if (bufferp file)
17936 (set-buffer file)
17937 (org-check-agenda-file file)
17938 (set-buffer (org-get-agenda-file-buffer file)))
17939 (widen)
17940 (org-set-regexps-and-options 'tags-only)
17941 (setq pos (point))
17942 (or (memq 'category org-agenda-ignore-properties)
17943 (org-refresh-category-properties))
17944 (or (memq 'stats org-agenda-ignore-properties)
17945 (org-refresh-stats-properties))
17946 (or (memq 'effort org-agenda-ignore-properties)
17947 (org-refresh-effort-properties))
17948 (or (memq 'appt org-agenda-ignore-properties)
17949 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17950 (setq org-todo-keywords-for-agenda
17951 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17952 (setq org-done-keywords-for-agenda
17953 (append org-done-keywords-for-agenda org-done-keywords))
17954 (setq org-todo-keyword-alist-for-agenda
17955 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17956 (setq org-tag-alist-for-agenda
17957 (org-tag-add-to-alist
17958 org-tag-alist-for-agenda
17959 org-current-tag-alist))
17960 ;; Merge current file's tag groups into global
17961 ;; `org-tag-groups-alist-for-agenda'.
17962 (when org-group-tags
17963 (dolist (alist org-tag-groups-alist)
17964 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17965 (if old
17966 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17967 (push alist org-tag-groups-alist-for-agenda)))))
17968 (org-with-silent-modifications
17969 (save-excursion
17970 (remove-text-properties (point-min) (point-max) pall)
17971 (when org-agenda-skip-archived-trees
17972 (goto-char (point-min))
17973 (while (re-search-forward rea nil t)
17974 (when (org-at-heading-p t)
17975 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17976 (goto-char (point-min))
17977 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17978 (while (re-search-forward re nil t)
17979 (when (save-match-data (org-in-commented-heading-p t))
17980 (add-text-properties
17981 (match-beginning 0) (org-end-of-subtree t) pc)))))
17982 (goto-char pos)))))
17983 (setq org-todo-keywords-for-agenda
17984 (org-uniquify org-todo-keywords-for-agenda))
17985 (setq org-todo-keyword-alist-for-agenda
17986 (org-uniquify org-todo-keyword-alist-for-agenda))))
17989 ;;;; CDLaTeX minor mode
17991 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17992 "Keymap for the minor `org-cdlatex-mode'.")
17994 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17995 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17996 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17997 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17998 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
18000 (defvar org-cdlatex-texmathp-advice-is-done nil
18001 "Flag remembering if we have applied the advice to texmathp already.")
18003 (define-minor-mode org-cdlatex-mode
18004 "Toggle the minor `org-cdlatex-mode'.
18005 This mode supports entering LaTeX environment and math in LaTeX fragments
18006 in Org mode.
18007 \\{org-cdlatex-mode-map}"
18008 nil " OCDL" nil
18009 (when org-cdlatex-mode
18010 (require 'cdlatex)
18011 (run-hooks 'cdlatex-mode-hook)
18012 (cdlatex-compute-tables))
18013 (unless org-cdlatex-texmathp-advice-is-done
18014 (setq org-cdlatex-texmathp-advice-is-done t)
18015 (defadvice texmathp (around org-math-always-on activate)
18016 "Always return t in Org buffers.
18017 This is because we want to insert math symbols without dollars even outside
18018 the LaTeX math segments. If Org mode thinks that point is actually inside
18019 an embedded LaTeX fragment, let `texmathp' do its job.
18020 `\\[org-cdlatex-mode-map]'"
18021 (interactive)
18022 (let (p)
18023 (cond
18024 ((not (derived-mode-p 'org-mode)) ad-do-it)
18025 ((eq this-command 'cdlatex-math-symbol)
18026 (setq ad-return-value t
18027 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18029 (let ((p (org-inside-LaTeX-fragment-p)))
18030 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18031 (setq ad-return-value t
18032 texmathp-why '("Org mode embedded math" . 0))
18033 (when p ad-do-it)))))))))
18035 (defun turn-on-org-cdlatex ()
18036 "Unconditionally turn on `org-cdlatex-mode'."
18037 (org-cdlatex-mode 1))
18039 (defun org-try-cdlatex-tab ()
18040 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18041 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18042 - inside a LaTeX fragment, or
18043 - after the first word in a line, where an abbreviation expansion could
18044 insert a LaTeX environment."
18045 (when org-cdlatex-mode
18046 (cond
18047 ;; Before any word on the line: No expansion possible.
18048 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18049 ;; Just after first word on the line: Expand it. Make sure it
18050 ;; cannot happen on headlines, though.
18051 ((save-excursion
18052 (skip-chars-backward "a-zA-Z0-9*")
18053 (skip-chars-backward " \t")
18054 (and (bolp) (not (org-at-heading-p))))
18055 (cdlatex-tab) t)
18056 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18058 (defun org-cdlatex-underscore-caret (&optional _arg)
18059 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18060 Revert to the normal definition outside of these fragments."
18061 (interactive "P")
18062 (if (org-inside-LaTeX-fragment-p)
18063 (call-interactively 'cdlatex-sub-superscript)
18064 (let (org-cdlatex-mode)
18065 (call-interactively (key-binding (vector last-input-event))))))
18067 (defun org-cdlatex-math-modify (&optional _arg)
18068 "Execute `cdlatex-math-modify' in LaTeX fragments.
18069 Revert to the normal definition outside of these fragments."
18070 (interactive "P")
18071 (if (org-inside-LaTeX-fragment-p)
18072 (call-interactively 'cdlatex-math-modify)
18073 (let (org-cdlatex-mode)
18074 (call-interactively (key-binding (vector last-input-event))))))
18076 (defun org-cdlatex-environment-indent (&optional environment item)
18077 "Execute `cdlatex-environment' and indent the inserted environment.
18079 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18081 The inserted environment is indented to current indentation
18082 unless point is at the beginning of the line, in which the
18083 environment remains unintended."
18084 (interactive)
18085 ;; cdlatex-environment always return nil. Therefore, capture output
18086 ;; first and determine if an environment was selected.
18087 (let* ((beg (point-marker))
18088 (end (copy-marker (point) t))
18089 (inserted (progn
18090 (ignore-errors (cdlatex-environment environment item))
18091 (< beg end)))
18092 ;; Figure out how many lines to move forward after the
18093 ;; environment has been inserted.
18094 (lines (when inserted
18095 (save-excursion
18096 (- (cl-loop while (< beg (point))
18097 with x = 0
18098 do (forward-line -1)
18099 (cl-incf x)
18100 finally return x)
18101 (if (progn (goto-char beg)
18102 (and (progn (skip-chars-forward " \t") (eolp))
18103 (progn (skip-chars-backward " \t") (bolp))))
18104 1 0)))))
18105 (env (org-trim (delete-and-extract-region beg end))))
18106 (when inserted
18107 ;; Get indentation of next line unless at column 0.
18108 (let ((ind (if (bolp) 0
18109 (save-excursion
18110 (org-return-indent)
18111 (prog1 (org-get-indentation)
18112 (when (progn (skip-chars-forward " \t") (eolp))
18113 (delete-region beg (point)))))))
18114 (bol (progn (skip-chars-backward " \t") (bolp))))
18115 ;; Insert a newline before environment unless at column zero
18116 ;; to "escape" the current line. Insert a newline if
18117 ;; something is one the same line as \end{ENVIRONMENT}.
18118 (insert
18119 (concat (unless bol "\n") env
18120 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18121 (unless (zerop ind)
18122 (save-excursion
18123 (goto-char beg)
18124 (while (< (point) end)
18125 (unless (eolp) (indent-line-to ind))
18126 (forward-line))))
18127 (goto-char beg)
18128 (forward-line lines)
18129 (indent-line-to ind)))
18130 (set-marker beg nil)
18131 (set-marker end nil)))
18134 ;;;; LaTeX fragments
18136 (defun org-inside-LaTeX-fragment-p ()
18137 "Test if point is inside a LaTeX fragment.
18138 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18139 sequence appearing also before point.
18140 Even though the matchers for math are configurable, this function assumes
18141 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18142 delimiters are skipped when they have been removed by customization.
18143 The return value is nil, or a cons cell with the delimiter and the
18144 position of this delimiter.
18146 This function does a reasonably good job, but can locally be fooled by
18147 for example currency specifications. For example it will assume being in
18148 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18149 fragments that are properly closed, but during editing, we have to live
18150 with the uncertainty caused by missing closing delimiters. This function
18151 looks only before point, not after."
18152 (catch 'exit
18153 (let ((pos (point))
18154 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18155 (lim (save-excursion (org-backward-paragraph) (point)))
18156 dd-on str (start 0) m re)
18157 (goto-char pos)
18158 (when dodollar
18159 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18160 re (nth 1 (assoc "$" org-latex-regexps)))
18161 (while (string-match re str start)
18162 (cond
18163 ((= (match-end 0) (length str))
18164 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18165 ((= (match-end 0) (- (length str) 5))
18166 (throw 'exit nil))
18167 (t (setq start (match-end 0))))))
18168 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18169 (goto-char pos)
18170 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18171 (and (match-beginning 2) (throw 'exit nil))
18172 ;; count $$
18173 (while (re-search-backward "\\$\\$" lim t)
18174 (setq dd-on (not dd-on)))
18175 (goto-char pos)
18176 (when dd-on (cons "$$" m))))))
18178 (defun org-inside-latex-macro-p ()
18179 "Is point inside a LaTeX macro or its arguments?"
18180 (save-match-data
18181 (org-in-regexp
18182 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18184 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18185 "Build an overlay between BEG and END using IMAGE file.
18186 Argument IMAGETYPE is the extension of the displayed image,
18187 as a string. It defaults to \"png\"."
18188 (let ((ov (make-overlay beg end))
18189 (imagetype (or (intern imagetype) 'png)))
18190 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18191 (overlay-put ov 'evaporate t)
18192 (overlay-put ov
18193 'modification-hooks
18194 (list (lambda (o _flag _beg _end &optional _l)
18195 (delete-overlay o))))
18196 (overlay-put ov
18197 'display
18198 (list 'image :type imagetype :file image :ascent 'center))))
18200 (defun org--list-latex-overlays (&optional beg end)
18201 "List all Org LaTeX overlays in current buffer.
18202 Limit to overlays between BEG and END when those are provided."
18203 (cl-remove-if-not
18204 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18205 (overlays-in (or beg (point-min)) (or end (point-max)))))
18207 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18208 "Remove all overlays with LaTeX fragment images in current buffer.
18209 When optional arguments BEG and END are non-nil, remove all
18210 overlays between them instead. Return a non-nil value when some
18211 overlays were removed, nil otherwise."
18212 (let ((overlays (org--list-latex-overlays beg end)))
18213 (mapc #'delete-overlay overlays)
18214 overlays))
18216 (defun org-toggle-latex-fragment (&optional arg)
18217 "Preview the LaTeX fragment at point, or all locally or globally.
18219 If the cursor is on a LaTeX fragment, create the image and overlay
18220 it over the source code, if there is none. Remove it otherwise.
18221 If there is no fragment at point, display all fragments in the
18222 current section.
18224 With prefix ARG, preview or clear image for all fragments in the
18225 current subtree or in the whole buffer when used before the first
18226 headline. With a prefix ARG `\\[universal-argument] \
18227 \\[universal-argument]' preview or clear images
18228 for all fragments in the buffer."
18229 (interactive "P")
18230 (when (display-graphic-p)
18231 (catch 'exit
18232 (save-excursion
18233 (let (beg end msg)
18234 (cond
18235 ((or (equal arg '(16))
18236 (and (equal arg '(4))
18237 (org-with-limited-levels (org-before-first-heading-p))))
18238 (if (org-remove-latex-fragment-image-overlays)
18239 (progn (message "LaTeX fragments images removed from buffer")
18240 (throw 'exit nil))
18241 (setq msg "Creating images for buffer...")))
18242 ((equal arg '(4))
18243 (org-with-limited-levels (org-back-to-heading t))
18244 (setq beg (point))
18245 (setq end (progn (org-end-of-subtree t) (point)))
18246 (if (org-remove-latex-fragment-image-overlays beg end)
18247 (progn
18248 (message "LaTeX fragment images removed from subtree")
18249 (throw 'exit nil))
18250 (setq msg "Creating images for subtree...")))
18251 ((let ((datum (org-element-context)))
18252 (when (memq (org-element-type datum)
18253 '(latex-environment latex-fragment))
18254 (setq beg (org-element-property :begin datum))
18255 (setq end (org-element-property :end datum))
18256 (if (org-remove-latex-fragment-image-overlays beg end)
18257 (progn (message "LaTeX fragment image removed")
18258 (throw 'exit nil))
18259 (setq msg "Creating image...")))))
18261 (org-with-limited-levels
18262 (setq beg (if (org-at-heading-p) (line-beginning-position)
18263 (outline-previous-heading)
18264 (point)))
18265 (setq end (progn (outline-next-heading) (point)))
18266 (if (org-remove-latex-fragment-image-overlays beg end)
18267 (progn
18268 (message "LaTeX fragment images removed from section")
18269 (throw 'exit nil))
18270 (setq msg "Creating images for section...")))))
18271 (let ((file (buffer-file-name (buffer-base-buffer))))
18272 (org-format-latex
18273 (concat org-preview-latex-image-directory "org-ltximg")
18274 beg end
18275 ;; Emacs cannot overlay images from remote hosts. Create
18276 ;; it in `temporary-file-directory' instead.
18277 (if (or (not file) (file-remote-p file))
18278 temporary-file-directory
18279 default-directory)
18280 'overlays msg 'forbuffer org-preview-latex-default-process))
18281 (message (concat msg "done")))))))
18283 (defun org-format-latex
18284 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18285 "Replace LaTeX fragments with links to an image.
18287 The function takes care of creating the replacement image.
18289 Only consider fragments between BEG and END when those are
18290 provided.
18292 When optional argument OVERLAYS is non-nil, display the image on
18293 top of the fragment instead of replacing it.
18295 PROCESSING-TYPE is the conversion method to use, as a symbol.
18297 Some of the options can be changed using the variable
18298 `org-format-latex-options', which see."
18299 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18300 (unless (eq processing-type 'verbatim)
18301 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18302 (cnt 0)
18303 checkdir-flag)
18304 (goto-char (or beg (point-min)))
18305 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18306 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18307 (overlay-recenter (or end (point-max))))
18308 (while (re-search-forward math-regexp end t)
18309 (unless (and overlays
18310 (eq (get-char-property (point) 'org-overlay-type)
18311 'org-latex-overlay))
18312 (let* ((context (org-element-context))
18313 (type (org-element-type context)))
18314 (when (memq type '(latex-environment latex-fragment))
18315 (let ((block-type (eq type 'latex-environment))
18316 (value (org-element-property :value context))
18317 (beg (org-element-property :begin context))
18318 (end (save-excursion
18319 (goto-char (org-element-property :end context))
18320 (skip-chars-backward " \r\t\n")
18321 (point))))
18322 (cond
18323 ((eq processing-type 'mathjax)
18324 ;; Prepare for MathJax processing.
18325 (if (not (string-match "\\`\\$\\$?" value))
18326 (goto-char end)
18327 (delete-region beg end)
18328 (if (string= (match-string 0 value) "$$")
18329 (insert "\\[" (substring value 2 -2) "\\]")
18330 (insert "\\(" (substring value 1 -1) "\\)"))))
18331 ((assq processing-type org-preview-latex-process-alist)
18332 ;; Process to an image.
18333 (cl-incf cnt)
18334 (goto-char beg)
18335 (let* ((processing-info
18336 (cdr (assq processing-type org-preview-latex-process-alist)))
18337 (face (face-at-point))
18338 ;; Get the colors from the face at point.
18340 (let ((color (plist-get org-format-latex-options
18341 :foreground)))
18342 (if (and forbuffer (eq color 'auto))
18343 (face-attribute face :foreground nil 'default)
18344 color)))
18346 (let ((color (plist-get org-format-latex-options
18347 :background)))
18348 (if (and forbuffer (eq color 'auto))
18349 (face-attribute face :background nil 'default)
18350 color)))
18351 (hash (sha1 (prin1-to-string
18352 (list org-format-latex-header
18353 org-latex-default-packages-alist
18354 org-latex-packages-alist
18355 org-format-latex-options
18356 forbuffer value fg bg))))
18357 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18358 (absprefix (expand-file-name prefix dir))
18359 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18360 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18361 (sep (and block-type "\n\n"))
18362 (link (concat sep "[[file:" linkfile "]]" sep))
18363 (options
18364 (org-combine-plists
18365 org-format-latex-options
18366 `(:foreground ,fg :background ,bg))))
18367 (when msg (message msg cnt))
18368 (unless checkdir-flag ; Ensure the directory exists.
18369 (setq checkdir-flag t)
18370 (let ((todir (file-name-directory absprefix)))
18371 (unless (file-directory-p todir)
18372 (make-directory todir t))))
18373 (unless (file-exists-p movefile)
18374 (org-create-formula-image
18375 value movefile options forbuffer processing-type))
18376 (if overlays
18377 (progn
18378 (dolist (o (overlays-in beg end))
18379 (when (eq (overlay-get o 'org-overlay-type)
18380 'org-latex-overlay)
18381 (delete-overlay o)))
18382 (org--format-latex-make-overlay beg end movefile imagetype)
18383 (goto-char end))
18384 (delete-region beg end)
18385 (insert
18386 (org-add-props link
18387 (list 'org-latex-src
18388 (replace-regexp-in-string "\"" "" value)
18389 'org-latex-src-embed-type
18390 (if block-type 'paragraph 'character)))))))
18391 ((eq processing-type 'mathml)
18392 ;; Process to MathML.
18393 (unless (org-format-latex-mathml-available-p)
18394 (user-error "LaTeX to MathML converter not configured"))
18395 (cl-incf cnt)
18396 (when msg (message msg cnt))
18397 (goto-char beg)
18398 (delete-region beg end)
18399 (insert (org-format-latex-as-mathml
18400 value block-type prefix dir)))
18402 (error "Unknown conversion process %s for LaTeX fragments"
18403 processing-type)))))))))))
18405 (defun org-create-math-formula (latex-frag &optional mathml-file)
18406 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18407 Use `org-latex-to-mathml-convert-command'. If the conversion is
18408 sucessful, return the portion between \"<math...> </math>\"
18409 elements otherwise return nil. When MATHML-FILE is specified,
18410 write the results in to that file. When invoked as an
18411 interactive command, prompt for LATEX-FRAG, with initial value
18412 set to the current active region and echo the results for user
18413 inspection."
18414 (interactive (list (let ((frag (when (org-region-active-p)
18415 (buffer-substring-no-properties
18416 (region-beginning) (region-end)))))
18417 (read-string "LaTeX Fragment: " frag nil frag))))
18418 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18419 (let* ((tmp-in-file
18420 (let ((file (file-relative-name
18421 (make-temp-name (expand-file-name "ltxmathml-in")))))
18422 (write-region latex-frag nil file)
18423 file))
18424 (tmp-out-file (file-relative-name
18425 (make-temp-name (expand-file-name "ltxmathml-out"))))
18426 (cmd (format-spec
18427 org-latex-to-mathml-convert-command
18428 `((?j . ,(and org-latex-to-mathml-jar-file
18429 (shell-quote-argument
18430 (expand-file-name
18431 org-latex-to-mathml-jar-file))))
18432 (?I . ,(shell-quote-argument tmp-in-file))
18433 (?i . ,latex-frag)
18434 (?o . ,(shell-quote-argument tmp-out-file)))))
18435 mathml shell-command-output)
18436 (when (called-interactively-p 'any)
18437 (unless (org-format-latex-mathml-available-p)
18438 (user-error "LaTeX to MathML converter not configured")))
18439 (message "Running %s" cmd)
18440 (setq shell-command-output (shell-command-to-string cmd))
18441 (setq mathml
18442 (when (file-readable-p tmp-out-file)
18443 (with-current-buffer (find-file-noselect tmp-out-file t)
18444 (goto-char (point-min))
18445 (when (re-search-forward
18446 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18447 (regexp-quote
18448 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18449 nil t)
18450 (prog1 (match-string 0) (kill-buffer))))))
18451 (cond
18452 (mathml
18453 (setq mathml
18454 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18455 (when mathml-file
18456 (write-region mathml nil mathml-file))
18457 (when (called-interactively-p 'any)
18458 (message mathml)))
18459 ((message "LaTeX to MathML conversion failed")
18460 (message shell-command-output)))
18461 (delete-file tmp-in-file)
18462 (when (file-exists-p tmp-out-file)
18463 (delete-file tmp-out-file))
18464 mathml))
18466 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18467 prefix &optional dir)
18468 "Use `org-create-math-formula' but check local cache first."
18469 (let* ((absprefix (expand-file-name prefix dir))
18470 (print-length nil) (print-level nil)
18471 (formula-id (concat
18472 "formula-"
18473 (sha1
18474 (prin1-to-string
18475 (list latex-frag
18476 org-latex-to-mathml-convert-command)))))
18477 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18478 (formula-cache-dir (file-name-directory formula-cache)))
18480 (unless (file-directory-p formula-cache-dir)
18481 (make-directory formula-cache-dir t))
18483 (unless (file-exists-p formula-cache)
18484 (org-create-math-formula latex-frag formula-cache))
18486 (if (file-exists-p formula-cache)
18487 ;; Successful conversion. Return the link to MathML file.
18488 (org-add-props
18489 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18490 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18491 'org-latex-src-embed-type (if latex-frag-type
18492 'paragraph 'character)))
18493 ;; Failed conversion. Return the LaTeX fragment verbatim
18494 latex-frag)))
18496 (defun org--get-display-dpi ()
18497 "Get the DPI of the display.
18498 The function assumes that the display has the same pixel width in
18499 the horizontal and vertical directions."
18500 (if (display-graphic-p)
18501 (round (/ (display-pixel-height)
18502 (/ (display-mm-height) 25.4)))
18503 (error "Attempt to calculate the dpi of a non-graphic display")))
18505 (defun org-create-formula-image
18506 (string tofile options buffer &optional processing-type)
18507 "Create an image from LaTeX source using external processes.
18509 The LaTeX STRING is saved to a temporary LaTeX file, then
18510 converted to an image file by process PROCESSING-TYPE defined in
18511 `org-preview-latex-process-alist'. A nil value defaults to
18512 `org-preview-latex-default-process'.
18514 The generated image file is eventually moved to TOFILE.
18516 The OPTIONS argument controls the size, foreground color and
18517 background color of the generated image.
18519 When BUFFER non-nil, this function is used for LaTeX previewing.
18520 Otherwise, it is used to deal with LaTeX snippets showed in
18521 a HTML file."
18522 (let* ((processing-type (or processing-type
18523 org-preview-latex-default-process))
18524 (processing-info
18525 (cdr (assq processing-type org-preview-latex-process-alist)))
18526 (programs (plist-get processing-info :programs))
18527 (error-message (or (plist-get processing-info :message) ""))
18528 (use-xcolor (plist-get processing-info :use-xcolor))
18529 (image-input-type (plist-get processing-info :image-input-type))
18530 (image-output-type (plist-get processing-info :image-output-type))
18531 (post-clean (or (plist-get processing-info :post-clean)
18532 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18533 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18534 (latex-header
18535 (or (plist-get processing-info :latex-header)
18536 (org-latex-make-preamble
18537 (org-export-get-environment (org-export-get-backend 'latex))
18538 org-format-latex-header
18539 'snippet)))
18540 (latex-compiler (plist-get processing-info :latex-compiler))
18541 (image-converter (plist-get processing-info :image-converter))
18542 (tmpdir temporary-file-directory)
18543 (texfilebase (make-temp-name
18544 (expand-file-name "orgtex" tmpdir)))
18545 (texfile (concat texfilebase ".tex"))
18546 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18547 '(1.0 . 1.0)))
18548 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18549 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18550 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18551 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18552 "Black"))
18553 (bg (or (plist-get options (if buffer :background :html-background))
18554 "Transparent"))
18555 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18556 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18557 (dolist (program programs)
18558 (org-check-external-command program error-message))
18559 (if use-xcolor
18560 (progn (if (eq fg 'default)
18561 (setq fg (org-latex-color :foreground))
18562 (setq fg (org-latex-color-format fg)))
18563 (if (eq bg 'default)
18564 (setq bg (org-latex-color :background))
18565 (setq bg (org-latex-color-format
18566 (if (string= bg "Transparent") "white" bg))))
18567 (with-temp-file texfile
18568 (insert latex-header)
18569 (insert "\n\\begin{document}\n"
18570 "\\definecolor{fg}{rgb}{" fg "}\n"
18571 "\\definecolor{bg}{rgb}{" bg "}\n"
18572 "\n\\pagecolor{bg}\n"
18573 "\n{\\color{fg}\n"
18574 string
18575 "\n}\n"
18576 "\n\\end{document}\n")))
18577 (if (eq fg 'default)
18578 (setq fg (org-dvipng-color :foreground))
18579 (unless (string= fg "Transparent")
18580 (setq fg (org-dvipng-color-format fg))))
18581 (if (eq bg 'default)
18582 (setq bg (org-dvipng-color :background))
18583 (unless (string= bg "Transparent")
18584 (setq bg (org-dvipng-color-format bg))))
18585 (with-temp-file texfile
18586 (insert latex-header)
18587 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18589 (let* ((err-msg (format "Please adjust `%s' part of \
18590 `org-preview-latex-process-alist'."
18591 processing-type))
18592 (image-input-file
18593 (org-compile-file
18594 texfile latex-compiler image-input-type err-msg log-buf))
18595 (image-output-file
18596 (org-compile-file
18597 image-input-file image-converter image-output-type err-msg log-buf
18598 `((?F . ,(shell-quote-argument fg))
18599 (?B . ,(shell-quote-argument bg))
18600 (?D . ,(shell-quote-argument (format "%s" dpi)))
18601 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18602 (copy-file image-output-file tofile 'replace)
18603 (dolist (e post-clean)
18604 (when (file-exists-p (concat texfilebase e))
18605 (delete-file (concat texfilebase e))))
18606 image-output-file)))
18608 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18609 "Fill a LaTeX header template TPL.
18610 In the template, the following place holders will be recognized:
18612 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18613 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18614 [PACKAGES] \\usepackage statements for PKG
18615 [NO-PACKAGES] do not include PKG
18616 [EXTRA] the string EXTRA
18617 [NO-EXTRA] do not include EXTRA
18619 For backward compatibility, if both the positive and the negative place
18620 holder is missing, the positive one (without the \"NO-\") will be
18621 assumed to be present at the end of the template.
18622 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18623 EXTRA is a string.
18624 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18625 (let (rpl (end ""))
18626 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18627 (setq rpl (if (or (match-end 1) (not def-pkg))
18628 "" (org-latex-packages-to-string def-pkg snippets-p t))
18629 tpl (replace-match rpl t t tpl))
18630 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18632 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18633 (setq rpl (if (or (match-end 1) (not pkg))
18634 "" (org-latex-packages-to-string pkg snippets-p t))
18635 tpl (replace-match rpl t t tpl))
18636 (when pkg (setq end
18637 (concat end "\n"
18638 (org-latex-packages-to-string pkg snippets-p)))))
18640 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18641 (setq rpl (if (or (match-end 1) (not extra))
18642 "" (concat extra "\n"))
18643 tpl (replace-match rpl t t tpl))
18644 (when (and extra (string-match "\\S-" extra))
18645 (setq end (concat end "\n" extra))))
18647 (if (string-match "\\S-" end)
18648 (concat tpl "\n" end)
18649 tpl)))
18651 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18652 "Turn an alist of packages into a string with the \\usepackage macros."
18653 (setq pkg (mapconcat (lambda(p)
18654 (cond
18655 ((stringp p) p)
18656 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18657 (format "%% Package %s omitted" (cadr p)))
18658 ((equal "" (car p))
18659 (format "\\usepackage{%s}" (cadr p)))
18661 (format "\\usepackage[%s]{%s}"
18662 (car p) (cadr p)))))
18664 "\n"))
18665 (if newline (concat pkg "\n") pkg))
18667 (defun org-dvipng-color (attr)
18668 "Return a RGB color specification for dvipng."
18669 (org-dvipng-color-format (face-attribute 'default attr nil)))
18671 (defun org-dvipng-color-format (color-name)
18672 "Convert COLOR-NAME to a RGB color value for dvipng."
18673 (apply #'format "rgb %s %s %s"
18674 (mapcar 'org-normalize-color
18675 (color-values color-name))))
18677 (defun org-latex-color (attr)
18678 "Return a RGB color for the LaTeX color package."
18679 (org-latex-color-format (face-attribute 'default attr nil)))
18681 (defun org-latex-color-format (color-name)
18682 "Convert COLOR-NAME to a RGB color value."
18683 (apply #'format "%s,%s,%s"
18684 (mapcar 'org-normalize-color
18685 (color-values color-name))))
18687 (defun org-normalize-color (value)
18688 "Return string to be used as color value for an RGB component."
18689 (format "%g" (/ value 65535.0)))
18692 ;; Image display
18694 (defvar-local org-inline-image-overlays nil)
18696 (defun org-toggle-inline-images (&optional include-linked)
18697 "Toggle the display of inline images.
18698 INCLUDE-LINKED is passed to `org-display-inline-images'."
18699 (interactive "P")
18700 (if org-inline-image-overlays
18701 (progn
18702 (org-remove-inline-images)
18703 (when (called-interactively-p 'interactive)
18704 (message "Inline image display turned off")))
18705 (org-display-inline-images include-linked)
18706 (when (called-interactively-p 'interactive)
18707 (message (if org-inline-image-overlays
18708 (format "%d images displayed inline"
18709 (length org-inline-image-overlays))
18710 "No images to display inline")))))
18712 (defun org-redisplay-inline-images ()
18713 "Refresh the display of inline images."
18714 (interactive)
18715 (if (not org-inline-image-overlays)
18716 (org-toggle-inline-images)
18717 (org-toggle-inline-images)
18718 (org-toggle-inline-images)))
18720 (defun org-display-inline-images (&optional include-linked refresh beg end)
18721 "Display inline images.
18723 An inline image is a link which follows either of these
18724 conventions:
18726 1. Its path is a file with an extension matching return value
18727 from `image-file-name-regexp' and it has no contents.
18729 2. Its description consists in a single link of the previous
18730 type.
18732 When optional argument INCLUDE-LINKED is non-nil, also links with
18733 a text description part will be inlined. This can be nice for
18734 a quick look at those images, but it does not reflect what
18735 exported files will look like.
18737 When optional argument REFRESH is non-nil, refresh existing
18738 images between BEG and END. This will create new image displays
18739 only if necessary. BEG and END default to the buffer
18740 boundaries."
18741 (interactive "P")
18742 (when (display-graphic-p)
18743 (unless refresh
18744 (org-remove-inline-images)
18745 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18746 (org-with-wide-buffer
18747 (goto-char (or beg (point-min)))
18748 (let* ((case-fold-search t)
18749 (file-extension-re (image-file-name-regexp))
18750 (link-abbrevs (mapcar #'car
18751 (append org-link-abbrev-alist-local
18752 org-link-abbrev-alist)))
18753 ;; Check absolute, relative file names and explicit
18754 ;; "file:" links. Also check link abbreviations since
18755 ;; some might expand to "file" links.
18756 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18757 (if (not link-abbrevs) ""
18758 (format "\\|\\(?:%s:\\)"
18759 (regexp-opt link-abbrevs))))))
18760 (while (re-search-forward file-types-re end t)
18761 (let ((link (save-match-data (org-element-context))))
18762 ;; Check if we're at an inline image, i.e., an image file
18763 ;; link without a description (unless INCLUDE-LINKED is
18764 ;; non-nil).
18765 (when (and (equal "file" (org-element-property :type link))
18766 (or include-linked
18767 (null (org-element-contents link)))
18768 (string-match-p file-extension-re
18769 (org-element-property :path link)))
18770 (let ((file (expand-file-name
18771 (org-link-unescape
18772 (org-element-property :path link)))))
18773 (when (file-exists-p file)
18774 (let ((width
18775 ;; Apply `org-image-actual-width' specifications.
18776 (cond
18777 ((not (image-type-available-p 'imagemagick)) nil)
18778 ((eq org-image-actual-width t) nil)
18779 ((listp org-image-actual-width)
18781 ;; First try to find a width among
18782 ;; attributes associated to the paragraph
18783 ;; containing link.
18784 (let ((paragraph
18785 (let ((e link))
18786 (while (and (setq e (org-element-property
18787 :parent e))
18788 (not (eq (org-element-type e)
18789 'paragraph))))
18790 e)))
18791 (when paragraph
18792 (save-excursion
18793 (goto-char (org-element-property :begin paragraph))
18794 (when
18795 (re-search-forward
18796 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18797 (org-element-property
18798 :post-affiliated paragraph)
18800 (string-to-number (match-string 1))))))
18801 ;; Otherwise, fall-back to provided number.
18802 (car org-image-actual-width)))
18803 ((numberp org-image-actual-width)
18804 org-image-actual-width)))
18805 (old (get-char-property-and-overlay
18806 (org-element-property :begin link)
18807 'org-image-overlay)))
18808 (if (and (car-safe old) refresh)
18809 (image-refresh (overlay-get (cdr old) 'display))
18810 (let ((image (create-image file
18811 (and width 'imagemagick)
18813 :width width)))
18814 (when image
18815 (let ((ov (make-overlay
18816 (org-element-property :begin link)
18817 (progn
18818 (goto-char
18819 (org-element-property :end link))
18820 (skip-chars-backward " \t")
18821 (point)))))
18822 (overlay-put ov 'display image)
18823 (overlay-put ov 'face 'default)
18824 (overlay-put ov 'org-image-overlay t)
18825 (overlay-put
18826 ov 'modification-hooks
18827 (list 'org-display-inline-remove-overlay))
18828 (push ov org-inline-image-overlays)))))))))))))))
18830 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18831 "Remove inline-display overlay if a corresponding region is modified."
18832 (let ((inhibit-modification-hooks t))
18833 (when (and ov after)
18834 (delete ov org-inline-image-overlays)
18835 (delete-overlay ov))))
18837 (defun org-remove-inline-images ()
18838 "Remove inline display of images."
18839 (interactive)
18840 (mapc #'delete-overlay org-inline-image-overlays)
18841 (setq org-inline-image-overlays nil))
18844 ;;; Key bindings
18846 (defun org-remap (map &rest commands)
18847 "In MAP, remap the functions given in COMMANDS.
18848 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18849 (let (new old)
18850 (while commands
18851 (setq old (pop commands) new (pop commands))
18852 (org-defkey map (vector 'remap old) new))))
18854 ;;;; Outline functions that can be remapped in Org
18855 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18856 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18857 (define-key org-mode-map [remap outline-forward-same-level]
18858 #'org-forward-heading-same-level)
18859 (define-key org-mode-map [remap outline-backward-same-level]
18860 #'org-backward-heading-same-level)
18861 (define-key org-mode-map [remap outline-show-branches]
18862 #'org-kill-note-or-show-branches)
18863 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18864 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18865 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18866 (define-key org-mode-map [remap outline-next-visible-heading]
18867 #'org-next-visible-heading)
18868 (define-key org-mode-map [remap outline-previous-visible-heading]
18869 #'org-previous-visible-heading)
18870 (define-key org-mode-map [remap show-children] #'org-show-children)
18872 ;;;; Make `C-c C-x' a prefix key
18873 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18875 ;;;; TAB key with modifiers
18876 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18877 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18878 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18879 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18880 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18882 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18883 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18884 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18886 ;;;; RET key with modifiers
18887 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18888 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18889 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18890 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18891 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18893 ;;;; Cursor keys with modifiers
18894 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18895 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18896 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18897 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18898 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18899 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18900 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18902 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18903 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18904 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18905 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18906 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18907 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18908 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18909 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18910 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18911 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18913 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18914 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18915 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18916 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18918 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18919 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18920 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18921 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18923 ;;;; Babel keys
18924 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18925 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18926 (define-key org-babel-map key def))
18928 ;;;; Extra keys for TTY access.
18930 ;; We only set them when really needed because otherwise the
18931 ;; menus don't show the simple keys
18933 (when (or org-use-extra-keys (not window-system))
18934 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18935 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18936 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18937 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18938 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18939 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18940 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18941 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18942 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18943 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18944 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18945 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18946 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18947 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18948 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18949 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18950 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18951 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18952 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18953 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18954 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18956 ;;;; Narrow map
18957 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18958 (org-defkey narrow-map "b" #'org-narrow-to-block)
18959 (org-defkey narrow-map "e" #'org-narrow-to-element)
18961 ;;;; Remap usual Emacs bindings
18962 (org-remap org-mode-map
18963 'self-insert-command 'org-self-insert-command
18964 'delete-char 'org-delete-char
18965 'delete-backward-char 'org-delete-backward-char
18966 'kill-line 'org-kill-line
18967 'open-line 'org-open-line
18968 'yank 'org-yank
18969 'comment-dwim 'org-comment-dwim
18970 'move-beginning-of-line 'org-beginning-of-line
18971 'move-end-of-line 'org-end-of-line
18972 'forward-paragraph 'org-forward-paragraph
18973 'backward-paragraph 'org-backward-paragraph
18974 'backward-sentence 'org-backward-sentence
18975 'forward-sentence 'org-forward-sentence
18976 'fill-paragraph 'org-fill-paragraph
18977 'delete-indentation 'org-delete-indentation
18978 'transpose-words 'org-transpose-words)
18980 ;;;; All the other keys
18981 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18982 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18983 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18984 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18985 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18986 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18987 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18988 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18989 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18990 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18991 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18992 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18993 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18994 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18995 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18996 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18997 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18998 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18999 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
19000 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
19001 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
19002 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
19003 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
19004 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
19005 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
19006 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
19007 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
19008 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
19009 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
19010 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
19011 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
19012 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
19013 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
19014 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
19015 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
19016 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
19017 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
19018 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
19019 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
19020 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
19021 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
19022 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
19023 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
19024 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19025 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19026 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19027 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19028 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19029 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19030 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19031 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19032 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19033 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19034 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19035 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19036 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19037 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19038 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19039 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19040 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19041 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19042 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19043 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19044 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19045 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19046 (org-defkey org-mode-map (kbd "RET") #'org-return)
19047 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19048 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19049 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19050 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19051 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19052 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19053 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19054 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19055 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19056 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19057 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19058 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19059 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19060 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19061 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19062 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19063 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19064 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19065 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19066 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19067 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19068 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19069 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19071 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19072 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19073 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19075 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19076 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19077 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19078 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19079 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19080 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19081 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19082 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19083 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19084 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19085 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19086 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19087 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19088 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19089 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19090 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19091 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19092 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19093 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19094 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19095 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19096 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19097 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19098 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19099 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19100 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19101 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19102 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19104 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19106 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19108 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19109 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19111 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19114 ;;; Speed commands
19116 (defconst org-speed-commands-default
19118 ("Outline Navigation")
19119 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19120 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19121 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19122 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19123 ("F" . org-next-block)
19124 ("B" . org-previous-block)
19125 ("u" . (org-speed-move-safe 'outline-up-heading))
19126 ("j" . org-goto)
19127 ("g" . (org-refile t))
19128 ("Outline Visibility")
19129 ("c" . org-cycle)
19130 ("C" . org-shifttab)
19131 (" " . org-display-outline-path)
19132 ("s" . org-narrow-to-subtree)
19133 ("=" . org-columns)
19134 ("Outline Structure Editing")
19135 ("U" . org-metaup)
19136 ("D" . org-metadown)
19137 ("r" . org-metaright)
19138 ("l" . org-metaleft)
19139 ("R" . org-shiftmetaright)
19140 ("L" . org-shiftmetaleft)
19141 ("i" . (progn (forward-char 1) (call-interactively
19142 'org-insert-heading-respect-content)))
19143 ("^" . org-sort)
19144 ("w" . org-refile)
19145 ("a" . org-archive-subtree-default-with-confirmation)
19146 ("@" . org-mark-subtree)
19147 ("#" . org-toggle-comment)
19148 ("Clock Commands")
19149 ("I" . org-clock-in)
19150 ("O" . org-clock-out)
19151 ("Meta Data Editing")
19152 ("t" . org-todo)
19153 ("," . (org-priority))
19154 ("0" . (org-priority ?\ ))
19155 ("1" . (org-priority ?A))
19156 ("2" . (org-priority ?B))
19157 ("3" . (org-priority ?C))
19158 (":" . org-set-tags-command)
19159 ("e" . org-set-effort)
19160 ("E" . org-inc-effort)
19161 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19162 (org-entry-put (point) "APPT_WARNTIME" m)))
19163 ("Agenda Views etc")
19164 ("v" . org-agenda)
19165 ("/" . org-sparse-tree)
19166 ("Misc")
19167 ("o" . org-open-at-point)
19168 ("?" . org-speed-command-help)
19169 ("<" . (org-agenda-set-restriction-lock 'subtree))
19170 (">" . (org-agenda-remove-restriction-lock))
19172 "The default speed commands.")
19174 (defun org-print-speed-command (e)
19175 (if (> (length (car e)) 1)
19176 (progn
19177 (princ "\n")
19178 (princ (car e))
19179 (princ "\n")
19180 (princ (make-string (length (car e)) ?-))
19181 (princ "\n"))
19182 (princ (car e))
19183 (princ " ")
19184 (if (symbolp (cdr e))
19185 (princ (symbol-name (cdr e)))
19186 (prin1 (cdr e)))
19187 (princ "\n")))
19189 (defun org-speed-command-help ()
19190 "Show the available speed commands."
19191 (interactive)
19192 (if (not org-use-speed-commands)
19193 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19194 (with-output-to-temp-buffer "*Help*"
19195 (princ "User-defined Speed commands\n===========================\n")
19196 (mapc #'org-print-speed-command org-speed-commands-user)
19197 (princ "\n")
19198 (princ "Built-in Speed commands\n=======================\n")
19199 (mapc #'org-print-speed-command org-speed-commands-default))
19200 (with-current-buffer "*Help*"
19201 (setq truncate-lines t))))
19203 (defun org-speed-move-safe (cmd)
19204 "Execute CMD, but make sure that the cursor always ends up in a headline.
19205 If not, return to the original position and throw an error."
19206 (interactive)
19207 (let ((pos (point)))
19208 (call-interactively cmd)
19209 (unless (and (bolp) (org-at-heading-p))
19210 (goto-char pos)
19211 (error "Boundary reached while executing %s" cmd))))
19213 (defvar org-self-insert-command-undo-counter 0)
19215 (defvar org-table-auto-blank-field) ; defined in org-table.el
19216 (defvar org-speed-command nil)
19218 (defun org-speed-command-activate (keys)
19219 "Hook for activating single-letter speed commands.
19220 `org-speed-commands-default' specifies a minimal command set.
19221 Use `org-speed-commands-user' for further customization."
19222 (when (or (and (bolp) (looking-at org-outline-regexp))
19223 (and (functionp org-use-speed-commands)
19224 (funcall org-use-speed-commands)))
19225 (cdr (assoc keys (append org-speed-commands-user
19226 org-speed-commands-default)))))
19228 (defun org-babel-speed-command-activate (keys)
19229 "Hook for activating single-letter code block commands."
19230 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19231 (cdr (assoc keys org-babel-key-bindings))))
19233 (defcustom org-speed-command-hook
19234 '(org-speed-command-activate org-babel-speed-command-activate)
19235 "Hook for activating speed commands at strategic locations.
19236 Hook functions are called in sequence until a valid handler is
19237 found.
19239 Each hook takes a single argument, a user-pressed command key
19240 which is also a `self-insert-command' from the global map.
19242 Within the hook, examine the cursor position and the command key
19243 and return nil or a valid handler as appropriate. Handler could
19244 be one of an interactive command, a function, or a form.
19246 Set `org-use-speed-commands' to non-nil value to enable this
19247 hook. The default setting is `org-speed-command-activate'."
19248 :group 'org-structure
19249 :version "24.1"
19250 :type 'hook)
19252 (defun org-self-insert-command (N)
19253 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19254 If the cursor is in a table looking at whitespace, the whitespace is
19255 overwritten, and the table is not marked as requiring realignment."
19256 (interactive "p")
19257 (org-check-before-invisible-edit 'insert)
19258 (cond
19259 ((and org-use-speed-commands
19260 (let ((kv (this-command-keys-vector)))
19261 (setq org-speed-command
19262 (run-hook-with-args-until-success
19263 'org-speed-command-hook
19264 (make-string 1 (aref kv (1- (length kv))))))))
19265 (cond
19266 ((commandp org-speed-command)
19267 (setq this-command org-speed-command)
19268 (call-interactively org-speed-command))
19269 ((functionp org-speed-command)
19270 (funcall org-speed-command))
19271 ((and org-speed-command (listp org-speed-command))
19272 (eval org-speed-command))
19273 (t (let (org-use-speed-commands)
19274 (call-interactively 'org-self-insert-command)))))
19275 ((and
19276 (= N 1)
19277 (not (org-region-active-p))
19278 (org-at-table-p)
19279 (progn
19280 ;; Check if we blank the field, and if that triggers align.
19281 (and (featurep 'org-table)
19282 org-table-auto-blank-field
19283 (memq last-command
19284 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19285 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19286 ;; Got extra space, this field does not determine
19287 ;; column width.
19288 (let (org-table-may-need-update) (org-table-blank-field))
19289 ;; No extra space, this field may determine column
19290 ;; width.
19291 (org-table-blank-field)))
19293 (looking-at "[^|\n]* |"))
19294 ;; There is room for insertion without re-aligning the table.
19295 (self-insert-command N)
19296 (org-table-with-shrunk-field
19297 (save-excursion
19298 (skip-chars-forward "^|")
19299 ;; Do not delete last space, which is
19300 ;; `org-table-separator-space', but the regular space before
19301 ;; it.
19302 (delete-region (- (point) 2) (1- (point))))))
19304 (setq org-table-may-need-update t)
19305 (self-insert-command N)
19306 (org-fix-tags-on-the-fly)
19307 (when org-self-insert-cluster-for-undo
19308 (if (not (eq last-command 'org-self-insert-command))
19309 (setq org-self-insert-command-undo-counter 1)
19310 (if (>= org-self-insert-command-undo-counter 20)
19311 (setq org-self-insert-command-undo-counter 1)
19312 (and (> org-self-insert-command-undo-counter 0)
19313 buffer-undo-list (listp buffer-undo-list)
19314 (not (cadr buffer-undo-list)) ; remove nil entry
19315 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19316 (setq org-self-insert-command-undo-counter
19317 (1+ org-self-insert-command-undo-counter))))))))
19319 (defun org-check-before-invisible-edit (kind)
19320 "Check is editing if kind KIND would be dangerous with invisible text around.
19321 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19322 ;; First, try to get out of here as quickly as possible, to reduce overhead
19323 (when (and org-catch-invisible-edits
19324 (or (not (boundp 'visible-mode)) (not visible-mode))
19325 (or (get-char-property (point) 'invisible)
19326 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19327 ;; OK, we need to take a closer look. Do not consider
19328 ;; invisibility obtained through text properties (e.g., link
19329 ;; fontification), as it cannot be toggled.
19330 (let* ((invisible-at-point
19331 (pcase (get-char-property-and-overlay (point) 'invisible)
19332 (`(,_ . ,(and (pred overlayp) o)) o)))
19333 ;; Assume that point cannot land in the middle of an
19334 ;; overlay, or between two overlays.
19335 (invisible-before-point
19336 (and (not invisible-at-point)
19337 (not (bobp))
19338 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19339 (`(,_ . ,(and (pred overlayp) o)) o))))
19340 (border-and-ok-direction
19342 ;; Check if we are acting predictably before invisible
19343 ;; text.
19344 (and invisible-at-point
19345 (memq kind '(insert delete-backward)))
19346 ;; Check if we are acting predictably after invisible text
19347 ;; This works not well, and I have turned it off. It seems
19348 ;; better to always show and stop after invisible text.
19349 ;; (and (not invisible-at-point) invisible-before-point
19350 ;; (memq kind '(insert delete)))
19352 (when (or invisible-at-point invisible-before-point)
19353 (when (eq org-catch-invisible-edits 'error)
19354 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19355 (if (and org-custom-properties-overlays
19356 (y-or-n-p "Display invisible properties in this buffer? "))
19357 (org-toggle-custom-properties-visibility)
19358 ;; Make the area visible
19359 (save-excursion
19360 (when invisible-before-point
19361 (goto-char
19362 (previous-single-char-property-change (point) 'invisible)))
19363 ;; Remove whatever overlay is currently making yet-to-be
19364 ;; edited text invisible. Also remove nested invisibility
19365 ;; related overlays.
19366 (delete-overlay (or invisible-at-point invisible-before-point))
19367 (let ((origin (if invisible-at-point (point) (1- (point)))))
19368 (while (pcase (get-char-property-and-overlay origin 'invisible)
19369 (`(,_ . ,(and (pred overlayp) o))
19370 (delete-overlay o)
19371 t)))))
19372 (cond
19373 ((eq org-catch-invisible-edits 'show)
19374 ;; That's it, we do the edit after showing
19375 (message
19376 "Unfolding invisible region around point before editing")
19377 (sit-for 1))
19378 ((and (eq org-catch-invisible-edits 'smart)
19379 border-and-ok-direction)
19380 (message "Unfolding invisible region around point before editing"))
19382 ;; Don't do the edit, make the user repeat it in full visibility
19383 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19385 (defun org-fix-tags-on-the-fly ()
19386 "Align tags in headline at point.
19387 Unlike to `org-set-tags', it ignores region and sorting."
19388 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19389 (org-at-heading-p))
19390 (let ((org-ignore-region t)
19391 (org-tags-sort-function nil))
19392 (org-set-tags nil t))))
19394 (defun org-delete-backward-char (N)
19395 "Like `delete-backward-char', insert whitespace at field end in tables.
19396 When deleting backwards, in tables this function will insert whitespace in
19397 front of the next \"|\" separator, to keep the table aligned. The table will
19398 still be marked for re-alignment if the field did fill the entire column,
19399 because, in this case the deletion might narrow the column."
19400 (interactive "p")
19401 (save-match-data
19402 (org-check-before-invisible-edit 'delete-backward)
19403 (if (and (= N 1)
19404 (not overwrite-mode)
19405 (not (org-region-active-p))
19406 (not (eq (char-before) ?|))
19407 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19408 (looking-at-p ".*?|")
19409 (org-at-table-p))
19410 (progn (forward-char -1) (org-delete-char 1))
19411 (backward-delete-char N)
19412 (org-fix-tags-on-the-fly))))
19414 (defun org-delete-char (N)
19415 "Like `delete-char', but insert whitespace at field end in tables.
19416 When deleting characters, in tables this function will insert whitespace in
19417 front of the next \"|\" separator, to keep the table aligned. The table will
19418 still be marked for re-alignment if the field did fill the entire column,
19419 because, in this case the deletion might narrow the column."
19420 (interactive "p")
19421 (save-match-data
19422 (org-check-before-invisible-edit 'delete)
19423 (cond
19424 ((or (/= N 1)
19425 (eq (char-after) ?|)
19426 (save-excursion (skip-chars-backward " \t") (bolp))
19427 (not (org-at-table-p)))
19428 (delete-char N)
19429 (org-fix-tags-on-the-fly))
19430 ((looking-at ".\\(.*?\\)|")
19431 (let* ((update? org-table-may-need-update)
19432 (noalign (looking-at-p ".*? |")))
19433 (delete-char 1)
19434 (org-table-with-shrunk-field
19435 (save-excursion
19436 ;; Last space is `org-table-separator-space', so insert
19437 ;; a regular one before it instead.
19438 (goto-char (- (match-end 0) 2))
19439 (insert " ")))
19440 ;; If there were two spaces at the end, this field does not
19441 ;; determine the width of the column.
19442 (when noalign (setq org-table-may-need-update update?))))
19444 (delete-char N)))))
19446 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19447 (put 'org-self-insert-command 'delete-selection
19448 (lambda ()
19449 (not (run-hook-with-args-until-success
19450 'self-insert-uses-region-functions))))
19451 (put 'orgtbl-self-insert-command 'delete-selection
19452 (lambda ()
19453 (not (run-hook-with-args-until-success
19454 'self-insert-uses-region-functions))))
19455 (put 'org-delete-char 'delete-selection 'supersede)
19456 (put 'org-delete-backward-char 'delete-selection 'supersede)
19457 (put 'org-yank 'delete-selection 'yank)
19459 ;; Make `flyspell-mode' delay after some commands
19460 (put 'org-self-insert-command 'flyspell-delayed t)
19461 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19462 (put 'org-delete-char 'flyspell-delayed t)
19463 (put 'org-delete-backward-char 'flyspell-delayed t)
19465 ;; Make pabbrev-mode expand after Org mode commands
19466 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19467 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19469 (defun org-transpose-words ()
19470 "Transpose words for Org.
19471 This uses the `org-mode-transpose-word-syntax-table' syntax
19472 table, which interprets characters in `org-emphasis-alist' as
19473 word constituents."
19474 (interactive)
19475 (with-syntax-table org-mode-transpose-word-syntax-table
19476 (call-interactively 'transpose-words)))
19478 (defvar org-ctrl-c-ctrl-c-hook nil
19479 "Hook for functions attaching themselves to `C-c C-c'.
19481 This can be used to add additional functionality to the C-c C-c
19482 key which executes context-dependent commands. This hook is run
19483 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19484 run after the last test.
19486 Each function will be called with no arguments. The function
19487 must check if the context is appropriate for it to act. If yes,
19488 it should do its thing and then return a non-nil value. If the
19489 context is wrong, just do nothing and return nil.")
19491 (defvar org-ctrl-c-ctrl-c-final-hook nil
19492 "Hook for functions attaching themselves to `C-c C-c'.
19494 This can be used to add additional functionality to the C-c C-c
19495 key which executes context-dependent commands. This hook is run
19496 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19497 before the first test.
19499 Each function will be called with no arguments. The function
19500 must check if the context is appropriate for it to act. If yes,
19501 it should do its thing and then return a non-nil value. If the
19502 context is wrong, just do nothing and return nil.")
19504 (defvar org-tab-first-hook nil
19505 "Hook for functions to attach themselves to TAB.
19506 See `org-ctrl-c-ctrl-c-hook' for more information.
19507 This hook runs as the first action when TAB is pressed, even before
19508 `org-cycle' messes around with the `outline-regexp' to cater for
19509 inline tasks and plain list item folding.
19510 If any function in this hook returns t, any other actions that
19511 would have been caused by TAB (such as table field motion or visibility
19512 cycling) will not occur.")
19514 (defvar org-tab-after-check-for-table-hook nil
19515 "Hook for functions to attach themselves to TAB.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.
19517 This hook runs after it has been established that the cursor is not in a
19518 table, but before checking if the cursor is in a headline or if global cycling
19519 should be done.
19520 If any function in this hook returns t, not other actions like visibility
19521 cycling will be done.")
19523 (defvar org-tab-after-check-for-cycling-hook nil
19524 "Hook for functions to attach themselves to TAB.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.
19526 This hook runs after it has been established that not table field motion and
19527 not visibility should be done because of current context. This is probably
19528 the place where a package like yasnippets can hook in.")
19530 (defvar org-tab-before-tab-emulation-hook nil
19531 "Hook for functions to attach themselves to TAB.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.
19533 This hook runs after every other options for TAB have been exhausted, but
19534 before indentation and \t insertion takes place.")
19536 (defvar org-metaleft-hook nil
19537 "Hook for functions attaching themselves to `M-left'.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.")
19539 (defvar org-metaright-hook nil
19540 "Hook for functions attaching themselves to `M-right'.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.")
19542 (defvar org-metaup-hook nil
19543 "Hook for functions attaching themselves to `M-up'.
19544 See `org-ctrl-c-ctrl-c-hook' for more information.")
19545 (defvar org-metadown-hook nil
19546 "Hook for functions attaching themselves to `M-down'.
19547 See `org-ctrl-c-ctrl-c-hook' for more information.")
19548 (defvar org-shiftmetaleft-hook nil
19549 "Hook for functions attaching themselves to `M-S-left'.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-shiftmetaright-hook nil
19552 "Hook for functions attaching themselves to `M-S-right'.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defvar org-shiftmetaup-hook nil
19555 "Hook for functions attaching themselves to `M-S-up'.
19556 See `org-ctrl-c-ctrl-c-hook' for more information.")
19557 (defvar org-shiftmetadown-hook nil
19558 "Hook for functions attaching themselves to `M-S-down'.
19559 See `org-ctrl-c-ctrl-c-hook' for more information.")
19560 (defvar org-metareturn-hook nil
19561 "Hook for functions attaching themselves to `M-RET'.
19562 See `org-ctrl-c-ctrl-c-hook' for more information.")
19563 (defvar org-shiftup-hook nil
19564 "Hook for functions attaching themselves to `S-up'.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-shiftup-final-hook nil
19567 "Hook for functions attaching themselves to `S-up'.
19568 This one runs after all other options except shift-select have been excluded.
19569 See `org-ctrl-c-ctrl-c-hook' for more information.")
19570 (defvar org-shiftdown-hook nil
19571 "Hook for functions attaching themselves to `S-down'.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.")
19573 (defvar org-shiftdown-final-hook nil
19574 "Hook for functions attaching themselves to `S-down'.
19575 This one runs after all other options except shift-select have been excluded.
19576 See `org-ctrl-c-ctrl-c-hook' for more information.")
19577 (defvar org-shiftleft-hook nil
19578 "Hook for functions attaching themselves to `S-left'.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.")
19580 (defvar org-shiftleft-final-hook nil
19581 "Hook for functions attaching themselves to `S-left'.
19582 This one runs after all other options except shift-select have been excluded.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.")
19584 (defvar org-shiftright-hook nil
19585 "Hook for functions attaching themselves to `S-right'.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.")
19587 (defvar org-shiftright-final-hook nil
19588 "Hook for functions attaching themselves to `S-right'.
19589 This one runs after all other options except shift-select have been excluded.
19590 See `org-ctrl-c-ctrl-c-hook' for more information.")
19592 (defun org-modifier-cursor-error ()
19593 "Throw an error, a modified cursor command was applied in wrong context."
19594 (user-error "This command is active in special context like tables, headlines or items"))
19596 (defun org-shiftselect-error ()
19597 "Throw an error because Shift-Cursor command was applied in wrong context."
19598 (if (and (boundp 'shift-select-mode) shift-select-mode)
19599 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19600 (user-error "This command works only in special context like headlines or timestamps")))
19602 (defun org-call-for-shift-select (cmd)
19603 (let ((this-command-keys-shift-translated t))
19604 (call-interactively cmd)))
19606 (defun org-shifttab (&optional arg)
19607 "Global visibility cycling or move to previous table field.
19608 Call `org-table-previous-field' within a table.
19609 When ARG is nil, cycle globally through visibility states.
19610 When ARG is a numeric prefix, show contents of this level."
19611 (interactive "P")
19612 (cond
19613 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19614 ((integerp arg)
19615 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19616 (message "Content view to level: %d" arg)
19617 (org-content (prefix-numeric-value arg2))
19618 (org-cycle-show-empty-lines t)
19619 (setq org-cycle-global-status 'overview)))
19620 (t (call-interactively 'org-global-cycle))))
19622 (defun org-shiftmetaleft ()
19623 "Promote subtree or delete table column.
19624 Calls `org-promote-subtree', `org-outdent-item-tree', or
19625 `org-table-delete-column', depending on context. See the
19626 individual commands for more information."
19627 (interactive)
19628 (cond
19629 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19630 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19631 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19632 ((if (not (org-region-active-p)) (org-at-item-p)
19633 (save-excursion (goto-char (region-beginning))
19634 (org-at-item-p)))
19635 (call-interactively 'org-outdent-item-tree))
19636 (t (org-modifier-cursor-error))))
19638 (defun org-shiftmetaright ()
19639 "Demote subtree or insert table column.
19640 Calls `org-demote-subtree', `org-indent-item-tree', or
19641 `org-table-insert-column', depending on context. See the
19642 individual commands for more information."
19643 (interactive)
19644 (cond
19645 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19646 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19647 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19648 ((if (not (org-region-active-p)) (org-at-item-p)
19649 (save-excursion (goto-char (region-beginning))
19650 (org-at-item-p)))
19651 (call-interactively 'org-indent-item-tree))
19652 (t (org-modifier-cursor-error))))
19654 (defun org-shiftmetaup (&optional _arg)
19655 "Drag the line at point up.
19656 In a table, kill the current row.
19657 On a clock timestamp, update the value of the timestamp like `S-<up>'
19658 but also adjust the previous clocked item in the clock history.
19659 Everywhere else, drag the line at point up."
19660 (interactive "P")
19661 (cond
19662 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19663 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19664 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19665 (call-interactively 'org-timestamp-up)))
19666 (t (call-interactively 'org-drag-line-backward))))
19668 (defun org-shiftmetadown (&optional _arg)
19669 "Drag the line at point down.
19670 In a table, insert an empty row at the current line.
19671 On a clock timestamp, update the value of the timestamp like `S-<down>'
19672 but also adjust the previous clocked item in the clock history.
19673 Everywhere else, drag the line at point down."
19674 (interactive "P")
19675 (cond
19676 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19677 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19678 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19679 (call-interactively 'org-timestamp-down)))
19680 (t (call-interactively 'org-drag-line-forward))))
19682 (defsubst org-hidden-tree-error ()
19683 (user-error
19684 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19686 (defun org-metaleft (&optional _arg)
19687 "Promote heading, list item at point or move table column left.
19689 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19690 depending on context. With no specific context, calls the Emacs
19691 default `backward-word'. See the individual commands for more
19692 information.
19694 This function runs the hook `org-metaleft-hook' as a first step,
19695 and returns at first non-nil value."
19696 (interactive "P")
19697 (cond
19698 ((run-hook-with-args-until-success 'org-metaleft-hook))
19699 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19700 ((org-with-limited-levels
19701 (or (org-at-heading-p)
19702 (and (org-region-active-p)
19703 (save-excursion
19704 (goto-char (region-beginning))
19705 (org-at-heading-p)))))
19706 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19707 (call-interactively 'org-do-promote))
19708 ;; At an inline task.
19709 ((org-at-heading-p)
19710 (call-interactively 'org-inlinetask-promote))
19711 ((or (org-at-item-p)
19712 (and (org-region-active-p)
19713 (save-excursion
19714 (goto-char (region-beginning))
19715 (org-at-item-p))))
19716 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19717 (call-interactively 'org-outdent-item))
19718 (t (call-interactively 'backward-word))))
19720 (defun org-metaright (&optional _arg)
19721 "Demote heading, list item at point or move table column right.
19723 In front of a drawer or a block keyword, indent it correctly.
19725 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19726 `org-indent-drawer' or `org-indent-block' depending on context.
19727 With no specific context, calls the Emacs default `forward-word'.
19728 See the individual commands for more information.
19730 This function runs the hook `org-metaright-hook' as a first step,
19731 and returns at first non-nil value."
19732 (interactive "P")
19733 (cond
19734 ((run-hook-with-args-until-success 'org-metaright-hook))
19735 ((org-at-table-p) (call-interactively 'org-table-move-column))
19736 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19737 ((org-at-block-p) (call-interactively 'org-indent-block))
19738 ((org-with-limited-levels
19739 (or (org-at-heading-p)
19740 (and (org-region-active-p)
19741 (save-excursion
19742 (goto-char (region-beginning))
19743 (org-at-heading-p)))))
19744 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19745 (call-interactively 'org-do-demote))
19746 ;; At an inline task.
19747 ((org-at-heading-p)
19748 (call-interactively 'org-inlinetask-demote))
19749 ((or (org-at-item-p)
19750 (and (org-region-active-p)
19751 (save-excursion
19752 (goto-char (region-beginning))
19753 (org-at-item-p))))
19754 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19755 (call-interactively 'org-indent-item))
19756 (t (call-interactively 'forward-word))))
19758 (defun org-check-for-hidden (what)
19759 "Check if there are hidden headlines/items in the current visual line.
19760 WHAT can be either `headlines' or `items'. If the current line is
19761 an outline or item heading and it has a folded subtree below it,
19762 this function returns t, nil otherwise."
19763 (let ((re (cond
19764 ((eq what 'headlines) org-outline-regexp-bol)
19765 ((eq what 'items) (org-item-beginning-re))
19766 (t (error "This should not happen"))))
19767 beg end)
19768 (save-excursion
19769 (catch 'exit
19770 (unless (org-region-active-p)
19771 (setq beg (point-at-bol))
19772 (beginning-of-line 2)
19773 (while (and (not (eobp)) ;; this is like `next-line'
19774 (get-char-property (1- (point)) 'invisible))
19775 (beginning-of-line 2))
19776 (setq end (point))
19777 (goto-char beg)
19778 (goto-char (point-at-eol))
19779 (setq end (max end (point)))
19780 (while (re-search-forward re end t)
19781 (when (get-char-property (match-beginning 0) 'invisible)
19782 (throw 'exit t))))
19783 nil))))
19785 (defun org-metaup (&optional _arg)
19786 "Move subtree up or move table row up.
19787 Calls `org-move-subtree-up' or `org-table-move-row' or
19788 `org-move-item-up', depending on context. See the individual commands
19789 for more information."
19790 (interactive "P")
19791 (cond
19792 ((run-hook-with-args-until-success 'org-metaup-hook))
19793 ((org-region-active-p)
19794 (let* ((a (min (region-beginning) (region-end)))
19795 (b (1- (max (region-beginning) (region-end))))
19796 (c (save-excursion (goto-char a)
19797 (move-beginning-of-line 0)))
19798 (d (save-excursion (goto-char a)
19799 (move-end-of-line 0) (point))))
19800 (transpose-regions a b c d)
19801 (goto-char c)))
19802 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19803 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19804 ((org-at-item-p) (call-interactively 'org-move-item-up))
19805 (t (org-drag-element-backward))))
19807 (defun org-metadown (&optional _arg)
19808 "Move subtree down or move table row down.
19809 Calls `org-move-subtree-down' or `org-table-move-row' or
19810 `org-move-item-down', depending on context. See the individual
19811 commands for more information."
19812 (interactive "P")
19813 (cond
19814 ((run-hook-with-args-until-success 'org-metadown-hook))
19815 ((org-region-active-p)
19816 (let* ((a (min (region-beginning) (region-end)))
19817 (b (max (region-beginning) (region-end)))
19818 (c (save-excursion (goto-char b)
19819 (move-beginning-of-line 1)))
19820 (d (save-excursion (goto-char b)
19821 (move-end-of-line 1) (1+ (point)))))
19822 (transpose-regions a b c d)
19823 (goto-char d)))
19824 ((org-at-table-p) (call-interactively 'org-table-move-row))
19825 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19826 ((org-at-item-p) (call-interactively 'org-move-item-down))
19827 (t (org-drag-element-forward))))
19829 (defun org-shiftup (&optional arg)
19830 "Increase item in timestamp or increase priority of current headline.
19831 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19832 depending on context. See the individual commands for more information."
19833 (interactive "P")
19834 (cond
19835 ((run-hook-with-args-until-success 'org-shiftup-hook))
19836 ((and org-support-shift-select (org-region-active-p))
19837 (org-call-for-shift-select 'previous-line))
19838 ((org-at-timestamp-p 'lax)
19839 (call-interactively (if org-edit-timestamp-down-means-later
19840 'org-timestamp-down 'org-timestamp-up)))
19841 ((and (not (eq org-support-shift-select 'always))
19842 org-enable-priority-commands
19843 (org-at-heading-p))
19844 (call-interactively 'org-priority-up))
19845 ((and (not org-support-shift-select) (org-at-item-p))
19846 (call-interactively 'org-previous-item))
19847 ((org-clocktable-try-shift 'up arg))
19848 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19849 (org-support-shift-select
19850 (org-call-for-shift-select 'previous-line))
19851 (t (org-shiftselect-error))))
19853 (defun org-shiftdown (&optional arg)
19854 "Decrease item in timestamp or decrease priority of current headline.
19855 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19856 depending on context. See the individual commands for more information."
19857 (interactive "P")
19858 (cond
19859 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19860 ((and org-support-shift-select (org-region-active-p))
19861 (org-call-for-shift-select 'next-line))
19862 ((org-at-timestamp-p 'lax)
19863 (call-interactively (if org-edit-timestamp-down-means-later
19864 'org-timestamp-up 'org-timestamp-down)))
19865 ((and (not (eq org-support-shift-select 'always))
19866 org-enable-priority-commands
19867 (org-at-heading-p))
19868 (call-interactively 'org-priority-down))
19869 ((and (not org-support-shift-select) (org-at-item-p))
19870 (call-interactively 'org-next-item))
19871 ((org-clocktable-try-shift 'down arg))
19872 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19873 (org-support-shift-select
19874 (org-call-for-shift-select 'next-line))
19875 (t (org-shiftselect-error))))
19877 (defun org-shiftright (&optional arg)
19878 "Cycle the thing at point or in the current line, depending on context.
19879 Depending on context, this does one of the following:
19881 - switch a timestamp at point one day into the future
19882 - on a headline, switch to the next TODO keyword.
19883 - on an item, switch entire list to the next bullet type
19884 - on a property line, switch to the next allowed value
19885 - on a clocktable definition line, move time block into the future"
19886 (interactive "P")
19887 (cond
19888 ((run-hook-with-args-until-success 'org-shiftright-hook))
19889 ((and org-support-shift-select (org-region-active-p))
19890 (org-call-for-shift-select 'forward-char))
19891 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19892 ((and (not (eq org-support-shift-select 'always))
19893 (org-at-heading-p))
19894 (let ((org-inhibit-logging
19895 (not org-treat-S-cursor-todo-selection-as-state-change))
19896 (org-inhibit-blocking
19897 (not org-treat-S-cursor-todo-selection-as-state-change)))
19898 (org-call-with-arg 'org-todo 'right)))
19899 ((or (and org-support-shift-select
19900 (not (eq org-support-shift-select 'always))
19901 (org-at-item-bullet-p))
19902 (and (not org-support-shift-select) (org-at-item-p)))
19903 (org-call-with-arg 'org-cycle-list-bullet nil))
19904 ((and (not (eq org-support-shift-select 'always))
19905 (org-at-property-p))
19906 (call-interactively 'org-property-next-allowed-value))
19907 ((org-clocktable-try-shift 'right arg))
19908 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19909 (org-support-shift-select
19910 (org-call-for-shift-select 'forward-char))
19911 (t (org-shiftselect-error))))
19913 (defun org-shiftleft (&optional arg)
19914 "Cycle the thing at point or in the current line, depending on context.
19915 Depending on context, this does one of the following:
19917 - switch a timestamp at point one day into the past
19918 - on a headline, switch to the previous TODO keyword.
19919 - on an item, switch entire list to the previous bullet type
19920 - on a property line, switch to the previous allowed value
19921 - on a clocktable definition line, move time block into the past"
19922 (interactive "P")
19923 (cond
19924 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19925 ((and org-support-shift-select (org-region-active-p))
19926 (org-call-for-shift-select 'backward-char))
19927 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19928 ((and (not (eq org-support-shift-select 'always))
19929 (org-at-heading-p))
19930 (let ((org-inhibit-logging
19931 (not org-treat-S-cursor-todo-selection-as-state-change))
19932 (org-inhibit-blocking
19933 (not org-treat-S-cursor-todo-selection-as-state-change)))
19934 (org-call-with-arg 'org-todo 'left)))
19935 ((or (and org-support-shift-select
19936 (not (eq org-support-shift-select 'always))
19937 (org-at-item-bullet-p))
19938 (and (not org-support-shift-select) (org-at-item-p)))
19939 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19940 ((and (not (eq org-support-shift-select 'always))
19941 (org-at-property-p))
19942 (call-interactively 'org-property-previous-allowed-value))
19943 ((org-clocktable-try-shift 'left arg))
19944 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19945 (org-support-shift-select
19946 (org-call-for-shift-select 'backward-char))
19947 (t (org-shiftselect-error))))
19949 (defun org-shiftcontrolright ()
19950 "Switch to next TODO set."
19951 (interactive)
19952 (cond
19953 ((and org-support-shift-select (org-region-active-p))
19954 (org-call-for-shift-select 'forward-word))
19955 ((and (not (eq org-support-shift-select 'always))
19956 (org-at-heading-p))
19957 (org-call-with-arg 'org-todo 'nextset))
19958 (org-support-shift-select
19959 (org-call-for-shift-select 'forward-word))
19960 (t (org-shiftselect-error))))
19962 (defun org-shiftcontrolleft ()
19963 "Switch to previous TODO set."
19964 (interactive)
19965 (cond
19966 ((and org-support-shift-select (org-region-active-p))
19967 (org-call-for-shift-select 'backward-word))
19968 ((and (not (eq org-support-shift-select 'always))
19969 (org-at-heading-p))
19970 (org-call-with-arg 'org-todo 'previousset))
19971 (org-support-shift-select
19972 (org-call-for-shift-select 'backward-word))
19973 (t (org-shiftselect-error))))
19975 (defun org-shiftcontrolup (&optional n)
19976 "Change timestamps synchronously up in CLOCK log lines.
19977 Optional argument N tells to change by that many units."
19978 (interactive "P")
19979 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19980 (let (org-support-shift-select)
19981 (org-clock-timestamps-up n))
19982 (user-error "Not at a clock log")))
19984 (defun org-shiftcontroldown (&optional n)
19985 "Change timestamps synchronously down in CLOCK log lines.
19986 Optional argument N tells to change by that many units."
19987 (interactive "P")
19988 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19989 (let (org-support-shift-select)
19990 (org-clock-timestamps-down n))
19991 (user-error "Not at a clock log")))
19993 (defun org-increase-number-at-point (&optional inc)
19994 "Increment the number at point.
19995 With an optional prefix numeric argument INC, increment using
19996 this numeric value."
19997 (interactive "p")
19998 (if (not (number-at-point))
19999 (user-error "Not on a number")
20000 (unless inc (setq inc 1))
20001 (let ((pos (point))
20002 (beg (skip-chars-backward "-+^/*0-9eE."))
20003 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20004 (setq nap (buffer-substring-no-properties
20005 (+ pos beg) (+ pos beg end)))
20006 (delete-region (+ pos beg) (+ pos beg end))
20007 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20008 (when (org-at-table-p)
20009 (org-table-align)
20010 (org-table-end-of-field 1))))
20012 (defun org-decrease-number-at-point (&optional inc)
20013 "Decrement the number at point.
20014 With an optional prefix numeric argument INC, decrement using
20015 this numeric value."
20016 (interactive "p")
20017 (org-increase-number-at-point (- (or inc 1))))
20019 (defun org-ctrl-c-ret ()
20020 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20021 (interactive)
20022 (cond
20023 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20024 (t (call-interactively 'org-insert-heading))))
20026 (defun org-find-visible ()
20027 (let ((s (point)))
20028 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20029 (get-char-property s 'invisible)))
20031 (defun org-find-invisible ()
20032 (let ((s (point)))
20033 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20034 (not (get-char-property s 'invisible))))
20037 (defun org-copy-visible (beg end)
20038 "Copy the visible parts of the region."
20039 (interactive "r")
20040 (let ((result ""))
20041 (while (/= beg end)
20042 (when (get-char-property beg 'invisible)
20043 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20044 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20045 (setq result (concat result (buffer-substring beg next)))
20046 (setq beg next)))
20047 (kill-new result)))
20049 (defun org-copy-special ()
20050 "Copy region in table or copy current subtree.
20051 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20052 context. See the individual commands for more information."
20053 (interactive)
20054 (call-interactively
20055 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20057 (defun org-cut-special ()
20058 "Cut region in table or cut current subtree.
20059 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20060 context. See the individual commands for more information."
20061 (interactive)
20062 (call-interactively
20063 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20065 (defun org-paste-special (arg)
20066 "Paste rectangular region into table, or past subtree relative to level.
20067 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20068 See the individual commands for more information."
20069 (interactive "P")
20070 (if (org-at-table-p)
20071 (org-table-paste-rectangle)
20072 (org-paste-subtree arg)))
20074 (defun org-edit-special (&optional arg)
20075 "Call a special editor for the element at point.
20076 When at a table, call the formula editor with `org-table-edit-formulas'.
20077 When in a source code block, call `org-edit-src-code'.
20078 When in a fixed-width region, call `org-edit-fixed-width-region'.
20079 When in an export block, call `org-edit-export-block'.
20080 When in a LaTeX environment, call `org-edit-latex-environment'.
20081 When at an #+INCLUDE keyword, visit the included file.
20082 When at a footnote reference, call `org-edit-footnote-reference'
20083 On a link, call `ffap' to visit the link at point.
20084 Otherwise, return a user error."
20085 (interactive "P")
20086 (let ((element (org-element-at-point)))
20087 (barf-if-buffer-read-only)
20088 (pcase (org-element-type element)
20089 (`src-block
20090 (if (not arg) (org-edit-src-code)
20091 (let* ((info (org-babel-get-src-block-info))
20092 (lang (nth 0 info))
20093 (params (nth 2 info))
20094 (session (cdr (assq :session params))))
20095 (if (not session) (org-edit-src-code)
20096 ;; At a src-block with a session and function called with
20097 ;; an ARG: switch to the buffer related to the inferior
20098 ;; process.
20099 (switch-to-buffer
20100 (funcall (intern (concat "org-babel-prep-session:" lang))
20101 session params))))))
20102 (`keyword
20103 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20104 (org-open-link-from-string
20105 (format "[[%s]]"
20106 (expand-file-name
20107 (let ((value (org-element-property :value element)))
20108 (cond ((org-file-url-p value)
20109 (user-error "The file is specified as a URL, cannot be edited"))
20110 ((not (org-string-nw-p value))
20111 (user-error "No file to edit"))
20112 ((string-match "\\`\"\\(.*?\\)\"" value)
20113 (match-string 1 value))
20114 ((string-match "\\`[^ \t\"]\\S-*" value)
20115 (match-string 0 value))
20116 (t (user-error "No valid file specified")))))))
20117 (user-error "No special environment to edit here")))
20118 (`table
20119 (if (eq (org-element-property :type element) 'table.el)
20120 (org-edit-table.el)
20121 (call-interactively 'org-table-edit-formulas)))
20122 ;; Only Org tables contain `table-row' type elements.
20123 (`table-row (call-interactively 'org-table-edit-formulas))
20124 (`example-block (org-edit-src-code))
20125 (`export-block (org-edit-export-block))
20126 (`fixed-width (org-edit-fixed-width-region))
20127 (`latex-environment (org-edit-latex-environment))
20129 ;; No notable element at point. Though, we may be at a link or
20130 ;; a footnote reference, which are objects. Thus, scan deeper.
20131 (let ((context (org-element-context element)))
20132 (pcase (org-element-type context)
20133 (`footnote-reference (org-edit-footnote-reference))
20134 (`inline-src-block (org-edit-inline-src-code))
20135 (`link (call-interactively #'ffap))
20136 (_ (user-error "No special environment to edit here"))))))))
20138 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20139 (defun org-ctrl-c-ctrl-c (&optional arg)
20140 "Set tags in headline, or update according to changed information at point.
20142 This command does many different things, depending on context:
20144 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20145 this is what we do.
20147 - If the cursor is on a statistics cookie, update it.
20149 - If the cursor is in a headline, prompt for tags and insert them
20150 into the current line, aligned to `org-tags-column'. When called
20151 with prefix arg, realign all tags in the current buffer.
20153 - If the cursor is in one of the special #+KEYWORD lines, this
20154 triggers scanning the buffer for these lines and updating the
20155 information.
20157 - If the cursor is inside a table, realign the table. This command
20158 works even if the automatic table editor has been turned off.
20160 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20161 the entire table.
20163 - If the cursor is at a footnote reference or definition, jump to
20164 the corresponding definition or references, respectively.
20166 - If the cursor is a the beginning of a dynamic block, update it.
20168 - If the current buffer is a capture buffer, close note and file it.
20170 - If the cursor is on a <<<target>>>, update radio targets and
20171 corresponding links in this buffer.
20173 - If the cursor is on a numbered item in a plain list, renumber the
20174 ordered list.
20176 - If the cursor is on a checkbox, toggle it.
20178 - If the cursor is on a code block, evaluate it. The variable
20179 `org-confirm-babel-evaluate' can be used to control prompting
20180 before code block evaluation, by default every code block
20181 evaluation requires confirmation. Code block evaluation can be
20182 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20183 (interactive "P")
20184 (cond
20185 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20186 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20187 (org-remove-occur-highlights)
20188 (message "Temporary highlights/overlays removed from current buffer"))
20189 ((and (local-variable-p 'org-finish-function)
20190 (fboundp org-finish-function))
20191 (funcall org-finish-function))
20192 ((org-babel-hash-at-point))
20193 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20195 (let* ((context
20196 (org-element-lineage
20197 (org-element-context)
20198 ;; Limit to supported contexts.
20199 '(babel-call clock dynamic-block footnote-definition
20200 footnote-reference inline-babel-call inline-src-block
20201 inlinetask item keyword node-property paragraph
20202 plain-list planning property-drawer radio-target
20203 src-block statistics-cookie table table-cell table-row
20204 timestamp)
20206 (type (org-element-type context)))
20207 ;; For convenience: at the first line of a paragraph on the same
20208 ;; line as an item, apply function on that item instead.
20209 (when (eq type 'paragraph)
20210 (let ((parent (org-element-property :parent context)))
20211 (when (and (eq (org-element-type parent) 'item)
20212 (= (line-beginning-position)
20213 (org-element-property :begin parent)))
20214 (setq context parent)
20215 (setq type 'item))))
20216 ;; Act according to type of element or object at point.
20218 ;; Do nothing on a blank line, except if it is contained in
20219 ;; a src block. Hence, we first check if point is in such
20220 ;; a block and then if it is at a blank line.
20221 (pcase type
20222 ((or `inline-src-block `src-block)
20223 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20224 (org-babel-eval-wipe-error-buffer)
20225 (org-babel-execute-src-block
20226 current-prefix-arg (org-babel-get-src-block-info nil context))))
20227 ((guard (org-match-line "[ \t]*$"))
20228 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20229 (user-error
20230 (substitute-command-keys
20231 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20232 ((or `babel-call `inline-babel-call)
20233 (let ((info (org-babel-lob-get-info context)))
20234 (when info (org-babel-execute-src-block nil info))))
20235 (`clock (org-clock-update-time-maybe))
20236 (`dynamic-block
20237 (save-excursion
20238 (goto-char (org-element-property :post-affiliated context))
20239 (org-update-dblock)))
20240 (`footnote-definition
20241 (goto-char (org-element-property :post-affiliated context))
20242 (call-interactively 'org-footnote-action))
20243 (`footnote-reference (call-interactively #'org-footnote-action))
20244 ((or `headline `inlinetask)
20245 (save-excursion (goto-char (org-element-property :begin context))
20246 (call-interactively #'org-set-tags)))
20247 (`item
20248 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20249 ;; unconditionally, whereas `C-u' will toggle its presence.
20250 ;; Without a universal argument, if the item has a checkbox,
20251 ;; toggle it. Otherwise repair the list.
20252 (let* ((box (org-element-property :checkbox context))
20253 (struct (org-element-property :structure context))
20254 (old-struct (copy-tree struct))
20255 (parents (org-list-parents-alist struct))
20256 (prevs (org-list-prevs-alist struct))
20257 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20258 (org-list-set-checkbox
20259 (org-element-property :begin context) struct
20260 (cond ((equal arg '(16)) "[-]")
20261 ((and (not box) (equal arg '(4))) "[ ]")
20262 ((or (not box) (equal arg '(4))) nil)
20263 ((eq box 'on) "[ ]")
20264 (t "[X]")))
20265 ;; Mimic `org-list-write-struct' but with grabbing a return
20266 ;; value from `org-list-struct-fix-box'.
20267 (org-list-struct-fix-ind struct parents 2)
20268 (org-list-struct-fix-item-end struct)
20269 (org-list-struct-fix-bul struct prevs)
20270 (org-list-struct-fix-ind struct parents)
20271 (let ((block-item
20272 (org-list-struct-fix-box struct parents prevs orderedp)))
20273 (if (and box (equal struct old-struct))
20274 (if (equal arg '(16))
20275 (message "Checkboxes already reset")
20276 (user-error "Cannot toggle this checkbox: %s"
20277 (if (eq box 'on)
20278 "all subitems checked"
20279 "unchecked subitems")))
20280 (org-list-struct-apply-struct struct old-struct)
20281 (org-update-checkbox-count-maybe))
20282 (when block-item
20283 (message "Checkboxes were removed due to empty box at line %d"
20284 (org-current-line block-item))))))
20285 (`keyword
20286 (let ((org-inhibit-startup-visibility-stuff t)
20287 (org-startup-align-all-tables nil))
20288 (when (boundp 'org-table-coordinate-overlays)
20289 (mapc #'delete-overlay org-table-coordinate-overlays)
20290 (setq org-table-coordinate-overlays nil))
20291 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20292 (message "Local setup has been refreshed"))
20293 (`plain-list
20294 ;; At a plain list, with a double C-u argument, set
20295 ;; checkboxes of each item to "[-]", whereas a single one
20296 ;; will toggle their presence according to the state of the
20297 ;; first item in the list. Without an argument, repair the
20298 ;; list.
20299 (let* ((begin (org-element-property :contents-begin context))
20300 (struct (org-element-property :structure context))
20301 (old-struct (copy-tree struct))
20302 (first-box (save-excursion
20303 (goto-char begin)
20304 (looking-at org-list-full-item-re)
20305 (match-string-no-properties 3)))
20306 (new-box (cond ((equal arg '(16)) "[-]")
20307 ((equal arg '(4)) (unless first-box "[ ]"))
20308 ((equal first-box "[X]") "[ ]")
20309 (t "[X]"))))
20310 (cond
20311 (arg
20312 (dolist (pos
20313 (org-list-get-all-items
20314 begin struct (org-list-prevs-alist struct)))
20315 (org-list-set-checkbox pos struct new-box)))
20316 ((and first-box (eq (point) begin))
20317 ;; For convenience, when point is at bol on the first
20318 ;; item of the list and no argument is provided, simply
20319 ;; toggle checkbox of that item, if any.
20320 (org-list-set-checkbox begin struct new-box)))
20321 (org-list-write-struct
20322 struct (org-list-parents-alist struct) old-struct)
20323 (org-update-checkbox-count-maybe)))
20324 ((or `property-drawer `node-property)
20325 (call-interactively #'org-property-action))
20326 (`radio-target
20327 (call-interactively #'org-update-radio-target-regexp))
20328 (`statistics-cookie
20329 (call-interactively #'org-update-statistics-cookies))
20330 ((or `table `table-cell `table-row)
20331 ;; At a table, recalculate every field and align it. Also
20332 ;; send the table if necessary. If the table has
20333 ;; a `table.el' type, just give up. At a table row or cell,
20334 ;; maybe recalculate line but always align table.
20335 (if (eq (org-element-property :type context) 'table.el)
20336 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20337 Use `\\[org-edit-special]' to edit table.el tables"))
20338 (if (or (eq type 'table)
20339 ;; Check if point is at a TBLFM line.
20340 (and (eq type 'table-row)
20341 (= (point) (org-element-property :end context))))
20342 (save-excursion
20343 (if (org-at-TBLFM-p)
20344 (progn (require 'org-table)
20345 (org-table-calc-current-TBLFM))
20346 (goto-char (org-element-property :contents-begin context))
20347 (org-call-with-arg 'org-table-recalculate (or arg t))
20348 (orgtbl-send-table 'maybe)))
20349 (org-table-maybe-eval-formula)
20350 (cond (arg (call-interactively #'org-table-recalculate))
20351 ((org-table-maybe-recalculate-line))
20352 (t (org-table-align))))))
20353 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20354 (org-timestamp-change 0 'day))
20355 ((and `nil (guard (org-at-heading-p)))
20356 ;; When point is on an unsupported object type, we can miss
20357 ;; the fact that it also is at a heading. Handle it here.
20358 (call-interactively #'org-set-tags))
20359 ((guard
20360 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20362 (user-error
20363 (substitute-command-keys
20364 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20366 (defun org-mode-restart ()
20367 (interactive)
20368 (let ((indent-status (bound-and-true-p org-indent-mode)))
20369 (funcall major-mode)
20370 (hack-local-variables)
20371 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20372 (org-indent-mode -1))
20373 (org-reset-file-cache))
20374 (message "%s restarted" major-mode))
20376 (defun org-kill-note-or-show-branches ()
20377 "Abort storing current note, or call `outline-show-branches'."
20378 (interactive)
20379 (if (not org-finish-function)
20380 (save-excursion
20381 (save-restriction
20382 (org-narrow-to-subtree)
20383 (org-flag-subtree t)
20384 (call-interactively 'outline-show-branches)
20385 (org-hide-archived-subtrees (point-min) (point-max))))
20386 (let ((org-note-abort t))
20387 (funcall org-finish-function))))
20389 (defun org-delete-indentation (&optional arg)
20390 "Join current line to previous and fix whitespace at join.
20392 If previous line is a headline add to headline title. Otherwise
20393 the function calls `delete-indentation'.
20395 With a non-nil optional argument, join it to the following one."
20396 (interactive "*P")
20397 (if (save-excursion
20398 (beginning-of-line (if arg 1 0))
20399 (let ((case-fold-search nil))
20400 (looking-at org-complex-heading-regexp)))
20401 ;; At headline.
20402 (let ((tags-column (when (match-beginning 5)
20403 (save-excursion (goto-char (match-beginning 5))
20404 (current-column))))
20405 (string (concat " " (progn (when arg (forward-line 1))
20406 (org-trim (delete-and-extract-region
20407 (line-beginning-position)
20408 (line-end-position)))))))
20409 (unless (bobp) (delete-region (point) (1- (point))))
20410 (goto-char (or (match-end 4)
20411 (match-beginning 5)
20412 (match-end 0)))
20413 (skip-chars-backward " \t")
20414 (save-excursion (insert string))
20415 ;; Adjust alignment of tags.
20416 (cond
20417 ((not tags-column)) ;no tags
20418 (org-auto-align-tags (org-set-tags nil t))
20419 (t (org--align-tags-here tags-column)))) ;preserve tags column
20420 (delete-indentation arg)))
20422 (defun org-open-line (n)
20423 "Insert a new row in tables, call `open-line' elsewhere.
20424 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20425 As a special case, when a document starts with a table, allow to
20426 call `open-line' on the very first character."
20427 (interactive "*p")
20428 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20429 (org-table-insert-row)
20430 (open-line n)))
20432 (defun org-return (&optional indent)
20433 "Goto next table row or insert a newline.
20435 Calls `org-table-next-row' or `newline', depending on context.
20437 When optional INDENT argument is non-nil, call
20438 `newline-and-indent' instead of `newline'.
20440 When `org-return-follows-link' is non-nil and point is on
20441 a timestamp or a link, call `org-open-at-point'. However, it
20442 will not happen if point is in a table or on a \"dead\"
20443 object (e.g., within a comment). In these case, you need to use
20444 `org-open-at-point' directly."
20445 (interactive)
20446 (let ((context (if org-return-follows-link (org-element-context)
20447 (org-element-at-point))))
20448 (cond
20449 ;; In a table, call `org-table-next-row'. However, before first
20450 ;; column or after last one, split the table.
20451 ((or (and (eq (org-element-type context) 'table)
20452 (>= (point) (org-element-property :contents-begin context))
20453 (< (point) (org-element-property :contents-end context)))
20454 (org-element-lineage context '(table-row table-cell) t))
20455 (if (or (looking-at-p "[ \t]*$")
20456 (save-excursion (skip-chars-backward " \t") (bolp)))
20457 (insert "\n")
20458 (org-table-justify-field-maybe)
20459 (call-interactively #'org-table-next-row)))
20460 ;; On a link or a timestamp, call `org-open-at-point' if
20461 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20462 ;; locations, e.g., in a comment, as `org-open-at-point'.
20463 ((and org-return-follows-link
20464 (or (and (eq 'link (org-element-type context))
20465 ;; Ensure point is not on the white spaces after
20466 ;; the link.
20467 (let ((origin (point)))
20468 (org-with-point-at (org-element-property :end context)
20469 (skip-chars-backward " \t")
20470 (> (point) origin))))
20471 (org-in-regexp org-ts-regexp-both nil t)
20472 (org-in-regexp org-tsr-regexp-both nil t)
20473 (org-in-regexp org-any-link-re nil t)))
20474 (call-interactively #'org-open-at-point))
20475 ;; Insert newline in heading, but preserve tags.
20476 ((and (not (bolp))
20477 (save-excursion (beginning-of-line)
20478 (let ((case-fold-search nil))
20479 (looking-at org-complex-heading-regexp))))
20480 ;; At headline. Split line. However, if point is on keyword,
20481 ;; priority cookie or tags, do not break any of them: add
20482 ;; a newline after the headline instead.
20483 (let ((tags-column (and (match-beginning 5)
20484 (save-excursion (goto-char (match-beginning 5))
20485 (current-column))))
20486 (string
20487 (when (and (match-end 4) (org-point-in-group (point) 4))
20488 (delete-and-extract-region (point) (match-end 4)))))
20489 ;; Adjust tag alignment.
20490 (cond
20491 ((not (and tags-column string)))
20492 (org-auto-align-tags (org-set-tags nil t))
20493 (t (org--align-tags-here tags-column))) ;preserve tags column
20494 (end-of-line)
20495 (org-show-entry)
20496 (if indent (newline-and-indent) (newline))
20497 (when string (save-excursion (insert (org-trim string))))))
20498 ;; In a list, make sure indenting keeps trailing text within.
20499 ((and indent
20500 (not (eolp))
20501 (org-element-lineage context '(item)))
20502 (let ((trailing-data
20503 (delete-and-extract-region (point) (line-end-position))))
20504 (newline-and-indent)
20505 (save-excursion (insert trailing-data))))
20507 ;; Do not auto-fill when point is in an Org property drawer.
20508 (let ((auto-fill-function (and (not (org-at-property-p))
20509 auto-fill-function)))
20510 (if indent
20511 (newline-and-indent)
20512 (newline)))))))
20514 (defun org-return-indent ()
20515 "Goto next table row or insert a newline and indent.
20516 Calls `org-table-next-row' or `newline-and-indent', depending on
20517 context. See the individual commands for more information."
20518 (interactive)
20519 (org-return t))
20521 (defun org-ctrl-c-tab (&optional _arg)
20522 "Toggle columns width in a table, or show children.
20523 Call `org-table-toggle-column-width' if point is in a table.
20524 Otherwise, call `org-show-children'."
20525 (interactive "p")
20526 (call-interactively
20527 (if (org-at-table-p) #'org-table-toggle-column-width
20528 #'org-show-children)))
20530 (defun org-ctrl-c-star ()
20531 "Compute table, or change heading status of lines.
20532 Calls `org-table-recalculate' or `org-toggle-heading',
20533 depending on context."
20534 (interactive)
20535 (cond
20536 ((org-at-table-p)
20537 (call-interactively 'org-table-recalculate))
20539 ;; Convert all lines in region to list items
20540 (call-interactively 'org-toggle-heading))))
20542 (defun org-ctrl-c-minus ()
20543 "Insert separator line in table or modify bullet status of line.
20544 Also turns a plain line or a region of lines into list items.
20545 Calls `org-table-insert-hline', `org-toggle-item', or
20546 `org-cycle-list-bullet', depending on context."
20547 (interactive)
20548 (cond
20549 ((org-at-table-p)
20550 (call-interactively 'org-table-insert-hline))
20551 ((org-region-active-p)
20552 (call-interactively 'org-toggle-item))
20553 ((org-in-item-p)
20554 (call-interactively 'org-cycle-list-bullet))
20556 (call-interactively 'org-toggle-item))))
20558 (defun org-toggle-heading (&optional nstars)
20559 "Convert headings to normal text, or items or text to headings.
20560 If there is no active region, only convert the current line.
20562 With a `\\[universal-argument]' prefix, convert the whole list at
20563 point into heading.
20565 In a region:
20567 - If the first non blank line is a headline, remove the stars
20568 from all headlines in the region.
20570 - If it is a normal line, turn each and every normal line (i.e.,
20571 not an heading or an item) in the region into headings. If you
20572 want to convert only the first line of this region, use one
20573 universal prefix argument.
20575 - If it is a plain list item, turn all plain list items into headings.
20577 When converting a line into a heading, the number of stars is chosen
20578 such that the lines become children of the current entry. However,
20579 when a numeric prefix argument is given, its value determines the
20580 number of stars to add."
20581 (interactive "P")
20582 (let ((skip-blanks
20583 (function
20584 ;; Return beginning of first non-blank line, starting from
20585 ;; line at POS.
20586 (lambda (pos)
20587 (save-excursion
20588 (goto-char pos)
20589 (while (org-at-comment-p) (forward-line))
20590 (skip-chars-forward " \r\t\n")
20591 (point-at-bol)))))
20592 beg end toggled)
20593 ;; Determine boundaries of changes. If a universal prefix has
20594 ;; been given, put the list in a region. If region ends at a bol,
20595 ;; do not consider the last line to be in the region.
20597 (when (and current-prefix-arg (org-at-item-p))
20598 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20599 (org-mark-element))
20601 (if (org-region-active-p)
20602 (setq beg (funcall skip-blanks (region-beginning))
20603 end (copy-marker (save-excursion
20604 (goto-char (region-end))
20605 (if (bolp) (point) (point-at-eol)))))
20606 (setq beg (funcall skip-blanks (point-at-bol))
20607 end (copy-marker (point-at-eol))))
20608 ;; Ensure inline tasks don't count as headings.
20609 (org-with-limited-levels
20610 (save-excursion
20611 (goto-char beg)
20612 (cond
20613 ;; Case 1. Started at an heading: de-star headings.
20614 ((org-at-heading-p)
20615 (while (< (point) end)
20616 (when (org-at-heading-p t)
20617 (looking-at org-outline-regexp) (replace-match "")
20618 (setq toggled t))
20619 (forward-line)))
20620 ;; Case 2. Started at an item: change items into headlines.
20621 ;; One star will be added by `org-list-to-subtree'.
20622 ((org-at-item-p)
20623 (while (< (point) end)
20624 (when (org-at-item-p)
20625 ;; Pay attention to cases when region ends before list.
20626 (let* ((struct (org-list-struct))
20627 (list-end
20628 (min (org-list-get-bottom-point struct) (1+ end))))
20629 (save-restriction
20630 (narrow-to-region (point) list-end)
20631 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20632 (setq toggled t))
20633 (forward-line)))
20634 ;; Case 3. Started at normal text: make every line an heading,
20635 ;; skipping headlines and items.
20636 (t (let* ((stars
20637 (make-string
20638 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20639 (add-stars
20640 (cond (nstars "") ; stars from prefix only
20641 ((equal stars "") "*") ; before first heading
20642 (org-odd-levels-only "**") ; inside heading, odd
20643 (t "*"))) ; inside heading, oddeven
20644 (rpl (concat stars add-stars " "))
20645 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20646 (while (< (point) (if (equal nstars '(4)) lend end))
20647 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20648 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20649 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20650 (forward-line)))))))
20651 (unless toggled (message "Cannot toggle heading from here"))))
20653 (defun org-meta-return (&optional arg)
20654 "Insert a new heading or wrap a region in a table.
20655 Calls `org-insert-heading', `org-insert-item' or
20656 `org-table-wrap-region', depending on context. When called with
20657 an argument, unconditionally call `org-insert-heading'."
20658 (interactive "P")
20659 (org-check-before-invisible-edit 'insert)
20660 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20661 (call-interactively (cond (arg #'org-insert-heading)
20662 ((org-at-table-p) #'org-table-wrap-region)
20663 ((org-in-item-p) #'org-insert-item)
20664 (t #'org-insert-heading)))))
20666 ;;; Menu entries
20668 (defsubst org-in-subtree-not-table-p ()
20669 "Are we in a subtree and not in a table?"
20670 (and (not (org-before-first-heading-p))
20671 (not (org-at-table-p))))
20673 ;; Define the Org mode menus
20674 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20675 '("Tbl"
20676 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20677 ["Next Field" org-cycle (org-at-table-p)]
20678 ["Previous Field" org-shifttab (org-at-table-p)]
20679 ["Next Row" org-return (org-at-table-p)]
20680 "--"
20681 ["Blank Field" org-table-blank-field (org-at-table-p)]
20682 ["Edit Field" org-table-edit-field (org-at-table-p)]
20683 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20684 "--"
20685 ("Column"
20686 ["Move Column Left" org-metaleft (org-at-table-p)]
20687 ["Move Column Right" org-metaright (org-at-table-p)]
20688 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20689 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20690 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20691 ("Row"
20692 ["Move Row Up" org-metaup (org-at-table-p)]
20693 ["Move Row Down" org-metadown (org-at-table-p)]
20694 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20695 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20696 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20697 "--"
20698 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20699 ("Rectangle"
20700 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20701 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20702 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20703 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20704 "--"
20705 ("Calculate"
20706 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20707 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20708 ["Edit Formulas" org-edit-special (org-at-table-p)]
20709 "--"
20710 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20711 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20712 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20713 "--"
20714 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20715 "--"
20716 ["Sum Column/Rectangle" org-table-sum
20717 (or (org-at-table-p) (org-region-active-p))]
20718 ["Which Column?" org-table-current-column (org-at-table-p)])
20719 ["Debug Formulas"
20720 org-table-toggle-formula-debugger
20721 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20722 ["Show Col/Row Numbers"
20723 org-table-toggle-coordinate-overlays
20724 :style toggle
20725 :selected (bound-and-true-p org-table-overlay-coordinates)]
20726 "--"
20727 ["Create" org-table-create (not (org-at-table-p))]
20728 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20729 ["Import from File" org-table-import (not (org-at-table-p))]
20730 ["Export to File" org-table-export (org-at-table-p)]
20731 "--"
20732 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20733 "--"
20734 ("Plot"
20735 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20736 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20738 (easy-menu-define org-org-menu org-mode-map "Org menu"
20739 '("Org"
20740 ("Show/Hide"
20741 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20742 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20743 ["Sparse Tree..." org-sparse-tree t]
20744 ["Reveal Context" org-reveal t]
20745 ["Show All" org-show-all t]
20746 "--"
20747 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20748 "--"
20749 ["New Heading" org-insert-heading t]
20750 ("Navigate Headings"
20751 ["Up" outline-up-heading t]
20752 ["Next" outline-next-visible-heading t]
20753 ["Previous" outline-previous-visible-heading t]
20754 ["Next Same Level" outline-forward-same-level t]
20755 ["Previous Same Level" outline-backward-same-level t]
20756 "--"
20757 ["Jump" org-goto t])
20758 ("Edit Structure"
20759 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20760 "--"
20761 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20762 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20763 "--"
20764 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20765 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20766 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20767 "--"
20768 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20769 "--"
20770 ["Copy visible text" org-copy-visible t]
20771 "--"
20772 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20773 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20774 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20775 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20776 "--"
20777 ["Sort Region/Children" org-sort t]
20778 "--"
20779 ["Convert to odd levels" org-convert-to-odd-levels t]
20780 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20781 ("Editing"
20782 ["Emphasis..." org-emphasize t]
20783 ["Edit Source Example" org-edit-special t]
20784 "--"
20785 ["Footnote new/jump" org-footnote-action t]
20786 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20787 ("Archive"
20788 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20789 "--"
20790 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20791 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20792 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20794 "--"
20795 ("Hyperlinks"
20796 ["Store Link (Global)" org-store-link t]
20797 ["Find existing link to here" org-occur-link-in-agenda-files t]
20798 ["Insert Link" org-insert-link t]
20799 ["Follow Link" org-open-at-point t]
20800 "--"
20801 ["Next link" org-next-link t]
20802 ["Previous link" org-previous-link t]
20803 "--"
20804 ["Descriptive Links"
20805 org-toggle-link-display
20806 :style radio
20807 :selected org-descriptive-links
20809 ["Literal Links"
20810 org-toggle-link-display
20811 :style radio
20812 :selected (not org-descriptive-links)])
20813 "--"
20814 ("TODO Lists"
20815 ["TODO/DONE/-" org-todo t]
20816 ("Select keyword"
20817 ["Next keyword" org-shiftright (org-at-heading-p)]
20818 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20819 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20820 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20821 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20822 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20823 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20824 "--"
20825 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20826 :selected org-enforce-todo-dependencies :style toggle :active t]
20827 "Settings for tree at point"
20828 ["Do Children sequentially" org-toggle-ordered-property :style radio
20829 :selected (org-entry-get nil "ORDERED")
20830 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20831 ["Do Children parallel" org-toggle-ordered-property :style radio
20832 :selected (not (org-entry-get nil "ORDERED"))
20833 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20834 "--"
20835 ["Set Priority" org-priority t]
20836 ["Priority Up" org-shiftup t]
20837 ["Priority Down" org-shiftdown t]
20838 "--"
20839 ["Get news from all feeds" org-feed-update-all t]
20840 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20841 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20842 ("TAGS and Properties"
20843 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20844 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20845 "--"
20846 ["Set property" org-set-property (not (org-before-first-heading-p))]
20847 ["Column view of properties" org-columns t]
20848 ["Insert Column View DBlock" org-columns-insert-dblock t])
20849 ("Dates and Scheduling"
20850 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20851 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20852 ("Change Date"
20853 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20854 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20855 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20856 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20857 ["Compute Time Range" org-evaluate-time-range t]
20858 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20859 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20860 "--"
20861 ["Custom time format" org-toggle-time-stamp-overlays
20862 :style radio :selected org-display-custom-times]
20863 "--"
20864 ["Goto Calendar" org-goto-calendar t]
20865 ["Date from Calendar" org-date-from-calendar t]
20866 "--"
20867 ["Start/Restart Timer" org-timer-start t]
20868 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20869 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20870 ["Insert Timer String" org-timer t]
20871 ["Insert Timer Item" org-timer-item t])
20872 ("Logging work"
20873 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20874 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20875 ["Clock out" org-clock-out t]
20876 ["Clock cancel" org-clock-cancel t]
20877 "--"
20878 ["Mark as default task" org-clock-mark-default-task t]
20879 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20880 ["Goto running clock" org-clock-goto t]
20881 "--"
20882 ["Display times" org-clock-display t]
20883 ["Create clock table" org-clock-report t]
20884 "--"
20885 ["Record DONE time"
20886 (progn (setq org-log-done (not org-log-done))
20887 (message "Switching to %s will %s record a timestamp"
20888 (car org-done-keywords)
20889 (if org-log-done "automatically" "not")))
20890 :style toggle :selected org-log-done])
20891 "--"
20892 ["Agenda Command..." org-agenda t]
20893 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20894 ("File List for Agenda")
20895 ("Special views current file"
20896 ["TODO Tree" org-show-todo-tree t]
20897 ["Check Deadlines" org-check-deadlines t]
20898 ["Tags/Property tree" org-match-sparse-tree t])
20899 "--"
20900 ["Export/Publish..." org-export-dispatch t]
20901 ("LaTeX"
20902 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20903 :style toggle :selected org-cdlatex-mode]
20904 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20905 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20906 ["Modify math symbol" org-cdlatex-math-modify
20907 (org-inside-LaTeX-fragment-p)]
20908 ["Insert citation" org-reftex-citation t])
20909 "--"
20910 ("MobileOrg"
20911 ["Push Files and Views" org-mobile-push t]
20912 ["Get Captured and Flagged" org-mobile-pull t]
20913 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20914 "--"
20915 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20916 "--"
20917 ("Documentation"
20918 ["Show Version" org-version t]
20919 ["Info Documentation" org-info t])
20920 ("Customize"
20921 ["Browse Org Group" org-customize t]
20922 "--"
20923 ["Expand This Menu" org-create-customize-menu
20924 (fboundp 'customize-menu-create)])
20925 ["Send bug report" org-submit-bug-report t]
20926 "--"
20927 ("Refresh/Reload"
20928 ["Refresh setup current buffer" org-mode-restart t]
20929 ["Reload Org (after update)" org-reload t]
20930 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20933 (defun org-info (&optional node)
20934 "Read documentation for Org in the info system.
20935 With optional NODE, go directly to that node."
20936 (interactive)
20937 (info (format "(org)%s" (or node ""))))
20939 ;;;###autoload
20940 (defun org-submit-bug-report ()
20941 "Submit a bug report on Org via mail.
20943 Don't hesitate to report any problems or inaccurate documentation.
20945 If you don't have setup sending mail from (X)Emacs, please copy the
20946 output buffer into your mail program, as it gives us important
20947 information about your Org version and configuration."
20948 (interactive)
20949 (require 'reporter)
20950 (defvar reporter-prompt-for-summary-p)
20951 (org-load-modules-maybe)
20952 (org-require-autoloaded-modules)
20953 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20954 (reporter-submit-bug-report
20955 "emacs-orgmode@gnu.org"
20956 (org-version nil 'full)
20957 (let (list)
20958 (save-window-excursion
20959 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20960 (delete-other-windows)
20961 (erase-buffer)
20962 (insert "You are about to submit a bug report to the Org mailing list.
20964 We would like to add your full Org and Outline configuration to the
20965 bug report. This greatly simplifies the work of the maintainer and
20966 other experts on the mailing list.
20968 HOWEVER, some variables you have customized may contain private
20969 information. The names of customers, colleagues, or friends, might
20970 appear in the form of file names, tags, todo states, or search strings.
20971 If you answer yes to the prompt, you might want to check and remove
20972 such private information before sending the email.")
20973 (add-text-properties (point-min) (point-max) '(face org-warning))
20974 (when (yes-or-no-p "Include your Org configuration ")
20975 (mapatoms
20976 (lambda (v)
20977 (and (boundp v)
20978 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20979 (or (and (symbol-value v)
20980 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20981 (and
20982 (get v 'custom-type) (get v 'standard-value)
20983 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20984 (push v list)))))
20985 (kill-buffer (get-buffer "*Warn about privacy*"))
20986 list))
20987 nil nil
20988 "Remember to cover the basics, that is, what you expected to happen and
20989 what in fact did happen. You don't know how to make a good report? See
20991 https://orgmode.org/manual/Feedback.html#Feedback
20993 Your bug report will be posted to the Org mailing list.
20994 ------------------------------------------------------------------------")
20995 (save-excursion
20996 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20997 (replace-match "\\1Bug: \\3 [\\2]")))))
21000 (defun org-install-agenda-files-menu ()
21001 (let ((bl (buffer-list)))
21002 (save-excursion
21003 (while bl
21004 (set-buffer (pop bl))
21005 (when (derived-mode-p 'org-mode) (setq bl nil)))
21006 (when (derived-mode-p 'org-mode)
21007 (easy-menu-change
21008 '("Org") "File List for Agenda"
21009 (append
21010 (list
21011 ["Edit File List" (org-edit-agenda-file-list) t]
21012 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21013 ["Remove Current File from List" org-remove-file t]
21014 ["Cycle through agenda files" org-cycle-agenda-files t]
21015 ["Occur in all agenda files" org-occur-in-agenda-files t]
21016 "--")
21017 (mapcar 'org-file-menu-entry
21018 ;; Prevent initialization from failing.
21019 (ignore-errors (org-agenda-files t)))))))))
21021 ;;;; Documentation
21023 (defun org-require-autoloaded-modules ()
21024 (interactive)
21025 (mapc #'require
21026 '(org-agenda org-archive org-attach org-clock org-colview org-id
21027 org-table org-timer)))
21029 ;;;###autoload
21030 (defun org-reload (&optional uncompiled)
21031 "Reload all Org Lisp files.
21032 With prefix arg UNCOMPILED, load the uncompiled versions."
21033 (interactive "P")
21034 (require 'loadhist)
21035 (let* ((org-dir (org-find-library-dir "org"))
21036 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21037 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21038 (remove-re (format "\\`%s\\'"
21039 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21040 (feats (delete-dups
21041 (mapcar 'file-name-sans-extension
21042 (mapcar 'file-name-nondirectory
21043 (delq nil
21044 (mapcar 'feature-file
21045 features))))))
21046 (lfeat (append
21047 (sort
21048 (setq feats
21049 (delq nil (mapcar
21050 (lambda (f)
21051 (if (and (string-match feature-re f)
21052 (not (string-match remove-re f)))
21053 f nil))
21054 feats)))
21055 'string-lessp)
21056 (list "org-version" "org")))
21057 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21058 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21059 load-uncore load-misses)
21060 (setq load-misses
21061 (delq 't
21062 (mapcar (lambda (f)
21063 (or (org-load-noerror-mustsuffix (concat org-dir f))
21064 (and (string= org-dir contrib-dir)
21065 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21066 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21067 (add-to-list 'load-uncore f 'append)
21070 lfeat)))
21071 (when load-uncore
21072 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21073 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21074 (if load-misses
21075 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21076 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21077 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21079 ;;;###autoload
21080 (defun org-customize ()
21081 "Call the customize function with org as argument."
21082 (interactive)
21083 (org-load-modules-maybe)
21084 (org-require-autoloaded-modules)
21085 (customize-browse 'org))
21087 (defun org-create-customize-menu ()
21088 "Create a full customization menu for Org mode, insert it into the menu."
21089 (interactive)
21090 (org-load-modules-maybe)
21091 (org-require-autoloaded-modules)
21092 (if (fboundp 'customize-menu-create)
21093 (progn
21094 (easy-menu-change
21095 '("Org") "Customize"
21096 `(["Browse Org group" org-customize t]
21097 "--"
21098 ,(customize-menu-create 'org)
21099 ["Set" Custom-set t]
21100 ["Save" Custom-save t]
21101 ["Reset to Current" Custom-reset-current t]
21102 ["Reset to Saved" Custom-reset-saved t]
21103 ["Reset to Standard Settings" Custom-reset-standard t]))
21104 (message "\"Org\"-menu now contains full customization menu"))
21105 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21107 ;;;; Miscellaneous stuff
21109 ;;; Generally useful functions
21111 (defun org-link-display-format (s)
21112 "Replace links in string S with their description.
21113 If there is no description, use the link target."
21114 (save-match-data
21115 (replace-regexp-in-string
21116 org-bracket-link-analytic-regexp
21117 (lambda (m)
21118 (if (match-end 5) (match-string 5 m)
21119 (concat (match-string 1 m) (match-string 3 m))))
21120 s nil t)))
21122 (defun org-toggle-link-display ()
21123 "Toggle the literal or descriptive display of links."
21124 (interactive)
21125 (if org-descriptive-links
21126 (progn (org-remove-from-invisibility-spec '(org-link))
21127 (org-restart-font-lock)
21128 (setq org-descriptive-links nil))
21129 (progn (add-to-invisibility-spec '(org-link))
21130 (org-restart-font-lock)
21131 (setq org-descriptive-links t))))
21133 (defun org-in-clocktable-p ()
21134 "Check if the cursor is in a clocktable."
21135 (let ((pos (point)) start)
21136 (save-excursion
21137 (end-of-line 1)
21138 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21139 (setq start (match-beginning 0))
21140 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21141 (>= (match-end 0) pos)
21142 start))))
21144 (defun org-in-verbatim-emphasis ()
21145 (save-match-data
21146 (and (org-in-regexp org-verbatim-re 2)
21147 (>= (point) (match-beginning 3))
21148 (<= (point) (match-end 4)))))
21150 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21151 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21152 (if (and marker (marker-buffer marker)
21153 (buffer-live-p (marker-buffer marker)))
21154 (progn
21155 (pop-to-buffer-same-window (marker-buffer marker))
21156 (when (or (> marker (point-max)) (< marker (point-min)))
21157 (widen))
21158 (goto-char marker)
21159 (org-show-context 'org-goto))
21160 (if bookmark
21161 (bookmark-jump bookmark)
21162 (error "Cannot find location"))))
21164 (defun org-quote-csv-field (s)
21165 "Quote field for inclusion in CSV material."
21166 (if (string-match "[\",]" s)
21167 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21170 (defun org-force-self-insert (N)
21171 "Needed to enforce self-insert under remapping."
21172 (interactive "p")
21173 (self-insert-command N))
21175 (defun org-fill-template (template alist)
21176 "Find each %key of ALIST in TEMPLATE and replace it."
21177 (let ((case-fold-search nil))
21178 (dolist (entry (sort (copy-sequence alist)
21179 (lambda (a b) (< (length (car a)) (length (car b))))))
21180 (setq template
21181 (replace-regexp-in-string
21182 (concat "%" (regexp-quote (car entry)))
21183 (or (cdr entry) "") template t t)))
21184 template))
21186 (defun org-quote-vert (s)
21187 "Replace \"|\" with \"\\vert\"."
21188 (while (string-match "|" s)
21189 (setq s (replace-match "\\vert" t t s)))
21192 (defun org-uuidgen-p (s)
21193 "Is S an ID created by UUIDGEN?"
21194 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21196 (defun org-in-src-block-p (&optional inside)
21197 "Whether point is in a code source block.
21198 When INSIDE is non-nil, don't consider we are within a src block
21199 when point is at #+BEGIN_SRC or #+END_SRC."
21200 (let ((case-fold-search t))
21201 (or (and (eq (get-char-property (point) 'src-block) t))
21202 (and (not inside)
21203 (save-match-data
21204 (save-excursion
21205 (beginning-of-line)
21206 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21208 (defun org-context ()
21209 "Return a list of contexts of the current cursor position.
21210 If several contexts apply, all are returned.
21211 Each context entry is a list with a symbol naming the context, and
21212 two positions indicating start and end of the context. Possible
21213 contexts are:
21215 :headline anywhere in a headline
21216 :headline-stars on the leading stars in a headline
21217 :todo-keyword on a TODO keyword (including DONE) in a headline
21218 :tags on the TAGS in a headline
21219 :priority on the priority cookie in a headline
21220 :item on the first line of a plain list item
21221 :item-bullet on the bullet/number of a plain list item
21222 :checkbox on the checkbox in a plain list item
21223 :table in an Org table
21224 :table-special on a special filed in a table
21225 :table-table in a table.el table
21226 :clocktable in a clocktable
21227 :src-block in a source block
21228 :link on a hyperlink
21229 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21230 :target on a <<target>>
21231 :radio-target on a <<<radio-target>>>
21232 :latex-fragment on a LaTeX fragment
21233 :latex-preview on a LaTeX fragment with overlaid preview image
21235 This function expects the position to be visible because it uses font-lock
21236 faces as a help to recognize the following contexts: :table-special, :link,
21237 and :keyword."
21238 (let* ((f (get-text-property (point) 'face))
21239 (faces (if (listp f) f (list f)))
21240 (case-fold-search t)
21241 (p (point)) clist o)
21242 ;; First the large context
21243 (cond
21244 ((org-at-heading-p t)
21245 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21246 (when (progn
21247 (beginning-of-line 1)
21248 (looking-at org-todo-line-tags-regexp))
21249 (push (org-point-in-group p 1 :headline-stars) clist)
21250 (push (org-point-in-group p 2 :todo-keyword) clist)
21251 (push (org-point-in-group p 4 :tags) clist))
21252 (goto-char p)
21253 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21254 (when (looking-at "\\[#[A-Z0-9]\\]")
21255 (push (org-point-in-group p 0 :priority) clist)))
21257 ((org-at-item-p)
21258 (push (org-point-in-group p 2 :item-bullet) clist)
21259 (push (list :item (point-at-bol)
21260 (save-excursion (org-end-of-item) (point)))
21261 clist)
21262 (and (org-at-item-checkbox-p)
21263 (push (org-point-in-group p 0 :checkbox) clist)))
21265 ((org-at-table-p)
21266 (push (list :table (org-table-begin) (org-table-end)) clist)
21267 (when (memq 'org-formula faces)
21268 (push (list :table-special
21269 (previous-single-property-change p 'face)
21270 (next-single-property-change p 'face)) clist)))
21271 ((org-at-table-p 'any)
21272 (push (list :table-table) clist)))
21273 (goto-char p)
21275 (let ((case-fold-search t))
21276 ;; New the "medium" contexts: clocktables, source blocks
21277 (cond ((org-in-clocktable-p)
21278 (push (list :clocktable
21279 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21280 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21281 (match-beginning 1))
21282 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21283 (match-end 0))) clist))
21284 ((org-in-src-block-p)
21285 (push (list :src-block
21286 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21287 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21288 (match-beginning 1))
21289 (and (search-forward "#+END_SRC" nil t)
21290 (match-beginning 0))) clist))))
21291 (goto-char p)
21293 ;; Now the small context
21294 (cond
21295 ((org-at-timestamp-p)
21296 (push (org-point-in-group p 0 :timestamp) clist))
21297 ((memq 'org-link faces)
21298 (push (list :link
21299 (previous-single-property-change p 'face)
21300 (next-single-property-change p 'face)) clist))
21301 ((memq 'org-special-keyword faces)
21302 (push (list :keyword
21303 (previous-single-property-change p 'face)
21304 (next-single-property-change p 'face)) clist))
21305 ((org-at-target-p)
21306 (push (org-point-in-group p 0 :target) clist)
21307 (goto-char (1- (match-beginning 0)))
21308 (when (looking-at org-radio-target-regexp)
21309 (push (org-point-in-group p 0 :radio-target) clist))
21310 (goto-char p))
21311 ((setq o (cl-some
21312 (lambda (o)
21313 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21315 (overlays-at (point))))
21316 (push (list :latex-fragment
21317 (overlay-start o) (overlay-end o)) clist)
21318 (push (list :latex-preview
21319 (overlay-start o) (overlay-end o)) clist))
21320 ((org-inside-LaTeX-fragment-p)
21321 ;; FIXME: positions wrong.
21322 (push (list :latex-fragment (point) (point)) clist)))
21324 (setq clist (nreverse (delq nil clist)))
21325 clist))
21327 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21328 "Non-nil when point is between matches of START-RE and END-RE.
21330 Also return a non-nil value when point is on one of the matches.
21332 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21333 buffer positions. Default values are the positions of headlines
21334 surrounding the point.
21336 The functions returns a cons cell whose car (resp. cdr) is the
21337 position before START-RE (resp. after END-RE)."
21338 (save-match-data
21339 (let ((pos (point))
21340 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21341 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21342 beg end)
21343 (save-excursion
21344 ;; Point is on a block when on START-RE or if START-RE can be
21345 ;; found before it...
21346 (and (or (org-in-regexp start-re)
21347 (re-search-backward start-re limit-up t))
21348 (setq beg (match-beginning 0))
21349 ;; ... and END-RE after it...
21350 (goto-char (match-end 0))
21351 (re-search-forward end-re limit-down t)
21352 (> (setq end (match-end 0)) pos)
21353 ;; ... without another START-RE in-between.
21354 (goto-char (match-beginning 0))
21355 (not (re-search-backward start-re (1+ beg) t))
21356 ;; Return value.
21357 (cons beg end))))))
21359 (defun org-in-block-p (names)
21360 "Non-nil when point belongs to a block whose name belongs to NAMES.
21362 NAMES is a list of strings containing names of blocks.
21364 Return first block name matched, or nil. Beware that in case of
21365 nested blocks, the returned name may not belong to the closest
21366 block from point."
21367 (save-match-data
21368 (catch 'exit
21369 (let ((case-fold-search t)
21370 (lim-up (save-excursion (outline-previous-heading)))
21371 (lim-down (save-excursion (outline-next-heading))))
21372 (dolist (name names)
21373 (let ((n (regexp-quote name)))
21374 (when (org-between-regexps-p
21375 (concat "^[ \t]*#\\+begin_" n)
21376 (concat "^[ \t]*#\\+end_" n)
21377 lim-up lim-down)
21378 (throw 'exit n)))))
21379 nil)))
21381 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21382 "Call `multi-occur' with buffers for all agenda files."
21383 (interactive "sOrg-files matching: ")
21384 (let* ((files (org-agenda-files))
21385 (tnames (mapcar #'file-truename files))
21386 (extra org-agenda-text-search-extra-files))
21387 (when (eq (car extra) 'agenda-archives)
21388 (setq extra (cdr extra))
21389 (setq files (org-add-archive-files files)))
21390 (dolist (f extra)
21391 (unless (member (file-truename f) tnames)
21392 (unless (member f files) (setq files (append files (list f))))
21393 (setq tnames (append tnames (list (file-truename f))))))
21394 (multi-occur
21395 (mapcar (lambda (x)
21396 (with-current-buffer
21397 ;; FIXME: Why not just (find-file-noselect x)?
21398 ;; Is it to avoid the "revert buffer" prompt?
21399 (or (get-file-buffer x) (find-file-noselect x))
21400 (widen)
21401 (current-buffer)))
21402 files)
21403 regexp)))
21405 (add-hook 'occur-mode-find-occurrence-hook
21406 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21408 (defun org-occur-link-in-agenda-files ()
21409 "Create a link and search for it in the agendas.
21410 The link is not stored in `org-stored-links', it is just created
21411 for the search purpose."
21412 (interactive)
21413 (let ((link (condition-case nil
21414 (org-store-link nil)
21415 (error "Unable to create a link to here"))))
21416 (org-occur-in-agenda-files (regexp-quote link))))
21418 (defun org-back-over-empty-lines ()
21419 "Move backwards over whitespace, to the beginning of the first empty line.
21420 Returns the number of empty lines passed."
21421 (let ((pos (point)))
21422 (if (cdr (assq 'heading org-blank-before-new-entry))
21423 (skip-chars-backward " \t\n\r")
21424 (unless (eobp)
21425 (forward-line -1)))
21426 (beginning-of-line 2)
21427 (goto-char (min (point) pos))
21428 (count-lines (point) pos)))
21430 (defun org-switch-to-buffer-other-window (&rest args)
21431 "Switch to buffer in a second window on the current frame.
21432 In particular, do not allow pop-up frames.
21433 Returns the newly created buffer."
21434 (org-no-popups
21435 (apply 'switch-to-buffer-other-window args)))
21437 (defun org-replace-escapes (string table)
21438 "Replace %-escapes in STRING with values in TABLE.
21439 TABLE is an association list with keys like \"%a\" and string values.
21440 The sequences in STRING may contain normal field width and padding information,
21441 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21442 so values can contain further %-escapes if they are define later in TABLE."
21443 (let ((tbl (copy-alist table))
21444 (case-fold-search nil)
21445 (pchg 0)
21446 re rpl)
21447 (dolist (e tbl)
21448 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21449 (when (and (cdr e) (string-match re (cdr e)))
21450 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21451 (safe "SREF"))
21452 (add-text-properties 0 3 (list 'sref sref) safe)
21453 (setcdr e (replace-match safe t t (cdr e)))))
21454 (while (string-match re string)
21455 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21456 (cdr e)))
21457 (setq string (replace-match rpl t t string))))
21458 (while (setq pchg (next-property-change pchg string))
21459 (let ((sref (get-text-property pchg 'sref string)))
21460 (when (and sref (string-match "SREF" string pchg))
21461 (setq string (replace-match sref t t string)))))
21462 string))
21464 ;;; TODO: Only called once, from ox-odt which should probably use
21465 ;;; org-export-inline-image-p or something.
21466 (defun org-file-image-p (file)
21467 "Return non-nil if FILE is an image."
21468 (save-match-data
21469 (string-match (image-file-name-regexp) file)))
21471 (defun org-get-cursor-date (&optional with-time)
21472 "Return the date at cursor in as a time.
21473 This works in the calendar and in the agenda, anywhere else it just
21474 returns the current time.
21475 If WITH-TIME is non-nil, returns the time of the event at point (in
21476 the agenda) or the current time of the day."
21477 (let (date day defd tp hod mod)
21478 (when with-time
21479 (setq tp (get-text-property (point) 'time))
21480 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21481 (setq hod (string-to-number (match-string 1 tp))
21482 mod (string-to-number (match-string 2 tp))))
21483 (or tp (let ((now (decode-time)))
21484 (setq hod (nth 2 now)
21485 mod (nth 1 now)))))
21486 (cond
21487 ((eq major-mode 'calendar-mode)
21488 (setq date (calendar-cursor-to-date)
21489 defd (encode-time 0 (or mod 0) (or hod 0)
21490 (nth 1 date) (nth 0 date) (nth 2 date))))
21491 ((eq major-mode 'org-agenda-mode)
21492 (setq day (get-text-property (point) 'day))
21493 (when day
21494 (setq date (calendar-gregorian-from-absolute day)
21495 defd (encode-time 0 (or mod 0) (or hod 0)
21496 (nth 1 date) (nth 0 date) (nth 2 date))))))
21497 (or defd (current-time))))
21499 (defun org-mark-subtree (&optional up)
21500 "Mark the current subtree.
21501 This puts point at the start of the current subtree, and mark at
21502 the end. If a numeric prefix UP is given, move up into the
21503 hierarchy of headlines by UP levels before marking the subtree."
21504 (interactive "P")
21505 (org-with-limited-levels
21506 (cond ((org-at-heading-p) (beginning-of-line))
21507 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21508 (t (outline-previous-visible-heading 1))))
21509 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21510 (if (called-interactively-p 'any)
21511 (call-interactively 'org-mark-element)
21512 (org-mark-element)))
21514 ;;; Indentation
21516 (defvar org-element-greater-elements)
21517 (defun org--get-expected-indentation (element contentsp)
21518 "Expected indentation column for current line, according to ELEMENT.
21519 ELEMENT is an element containing point. CONTENTSP is non-nil
21520 when indentation is to be computed according to contents of
21521 ELEMENT."
21522 (let ((type (org-element-type element))
21523 (start (org-element-property :begin element))
21524 (post-affiliated (org-element-property :post-affiliated element)))
21525 (org-with-wide-buffer
21526 (cond
21527 (contentsp
21528 (cl-case type
21529 ((diary-sexp footnote-definition) 0)
21530 ((headline inlinetask nil)
21531 (if (not org-adapt-indentation) 0
21532 (let ((level (org-current-level)))
21533 (if level (1+ level) 0))))
21534 ((item plain-list) (org-list-item-body-column post-affiliated))
21536 (goto-char start)
21537 (org-get-indentation))))
21538 ((memq type '(headline inlinetask nil))
21539 (if (org-match-line "[ \t]*$")
21540 (org--get-expected-indentation element t)
21542 ((memq type '(diary-sexp footnote-definition)) 0)
21543 ;; First paragraph of a footnote definition or an item.
21544 ;; Indent like parent.
21545 ((< (line-beginning-position) start)
21546 (org--get-expected-indentation
21547 (org-element-property :parent element) t))
21548 ;; At first line: indent according to previous sibling, if any,
21549 ;; ignoring footnote definitions and inline tasks, or parent's
21550 ;; contents.
21551 ((= (line-beginning-position) start)
21552 (catch 'exit
21553 (while t
21554 (if (= (point-min) start) (throw 'exit 0)
21555 (goto-char (1- start))
21556 (let* ((previous (org-element-at-point))
21557 (parent previous))
21558 (while (and parent (<= (org-element-property :end parent) start))
21559 (setq previous parent
21560 parent (org-element-property :parent parent)))
21561 (cond
21562 ((not previous) (throw 'exit 0))
21563 ((> (org-element-property :end previous) start)
21564 (throw 'exit (org--get-expected-indentation previous t)))
21565 ((memq (org-element-type previous)
21566 '(footnote-definition inlinetask))
21567 (setq start (org-element-property :begin previous)))
21568 (t (goto-char (org-element-property :begin previous))
21569 (throw 'exit
21570 (if (bolp) (org-get-indentation)
21571 ;; At first paragraph in an item or
21572 ;; a footnote definition.
21573 (org--get-expected-indentation
21574 (org-element-property :parent previous) t))))))))))
21575 ;; Otherwise, move to the first non-blank line above.
21577 (beginning-of-line)
21578 (let ((pos (point)))
21579 (skip-chars-backward " \r\t\n")
21580 (cond
21581 ;; Two blank lines end a footnote definition or a plain
21582 ;; list. When we indent an empty line after them, the
21583 ;; containing list or footnote definition is over, so it
21584 ;; qualifies as a previous sibling. Therefore, we indent
21585 ;; like its first line.
21586 ((and (memq type '(footnote-definition plain-list))
21587 (> (count-lines (point) pos) 2))
21588 (goto-char start)
21589 (org-get-indentation))
21590 ;; Line above is the first one of a paragraph at the
21591 ;; beginning of an item or a footnote definition. Indent
21592 ;; like parent.
21593 ((< (line-beginning-position) start)
21594 (org--get-expected-indentation
21595 (org-element-property :parent element) t))
21596 ;; Line above is the beginning of an element, i.e., point
21597 ;; was originally on the blank lines between element's start
21598 ;; and contents.
21599 ((= (line-beginning-position) post-affiliated)
21600 (org--get-expected-indentation element t))
21601 ;; POS is after contents in a greater element. Indent like
21602 ;; the beginning of the element.
21603 ((and (memq type org-element-greater-elements)
21604 (let ((cend (org-element-property :contents-end element)))
21605 (and cend (<= cend pos))))
21606 ;; As a special case, if point is at the end of a footnote
21607 ;; definition or an item, indent like the very last element
21608 ;; within. If that last element is an item, indent like
21609 ;; its contents.
21610 (if (memq type '(footnote-definition item plain-list))
21611 (let ((last (org-element-at-point)))
21612 (goto-char pos)
21613 (org--get-expected-indentation
21614 last (eq (org-element-type last) 'item)))
21615 (goto-char start)
21616 (org-get-indentation)))
21617 ;; In any other case, indent like the current line.
21618 (t (org-get-indentation)))))))))
21620 (defun org--align-node-property ()
21621 "Align node property at point.
21622 Alignment is done according to `org-property-format', which see."
21623 (when (save-excursion
21624 (beginning-of-line)
21625 (looking-at org-property-re))
21626 (replace-match
21627 (concat (match-string 4)
21628 (org-trim
21629 (format org-property-format (match-string 1) (match-string 3))))
21630 t t)))
21632 (defun org-indent-line ()
21633 "Indent line depending on context.
21635 Indentation is done according to the following rules:
21637 - Footnote definitions, diary sexps, headlines and inline tasks
21638 have to start at column 0.
21640 - On the very first line of an element, consider, in order, the
21641 next rules until one matches:
21643 1. If there's a sibling element before, ignoring footnote
21644 definitions and inline tasks, indent like its first line.
21646 2. If element has a parent, indent like its contents. More
21647 precisely, if parent is an item, indent after the
21648 description part, if any, or the bullet (see
21649 `org-list-description-max-indent'). Else, indent like
21650 parent's first line.
21652 3. Otherwise, indent relatively to current level, if
21653 `org-adapt-indentation' is non-nil, or to left margin.
21655 - On a blank line at the end of an element, indent according to
21656 the type of the element. More precisely
21658 1. If element is a plain list, an item, or a footnote
21659 definition, indent like the very last element within.
21661 2. If element is a paragraph, indent like its last non blank
21662 line.
21664 3. Otherwise, indent like its very first line.
21666 - In the code part of a source block, use language major mode
21667 to indent current line if `org-src-tab-acts-natively' is
21668 non-nil. If it is nil, do nothing.
21670 - Otherwise, indent like the first non-blank line above.
21672 The function doesn't indent an item as it could break the whole
21673 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21674 `\\[org-shiftmetaright]'.
21676 Also align node properties according to `org-property-format'."
21677 (interactive)
21678 (cond
21679 ((org-at-heading-p) 'noindent)
21681 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21682 (type (org-element-type element)))
21683 (cond ((and (memq type '(plain-list item))
21684 (= (line-beginning-position)
21685 (org-element-property :post-affiliated element)))
21686 'noindent)
21687 ((and (eq type 'latex-environment)
21688 (>= (point) (org-element-property :post-affiliated element))
21689 (< (point) (org-with-wide-buffer
21690 (goto-char (org-element-property :end element))
21691 (skip-chars-backward " \r\t\n")
21692 (line-beginning-position 2))))
21693 'noindent)
21694 ((and (eq type 'src-block)
21695 org-src-tab-acts-natively
21696 (> (line-beginning-position)
21697 (org-element-property :post-affiliated element))
21698 (< (line-beginning-position)
21699 (org-with-wide-buffer
21700 (goto-char (org-element-property :end element))
21701 (skip-chars-backward " \r\t\n")
21702 (line-beginning-position))))
21703 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21705 (let ((column (org--get-expected-indentation element nil)))
21706 ;; Preserve current column.
21707 (if (<= (current-column) (current-indentation))
21708 (indent-line-to column)
21709 (save-excursion (indent-line-to column))))
21710 ;; Align node property. Also preserve current column.
21711 (when (eq type 'node-property)
21712 (let ((column (current-column)))
21713 (org--align-node-property)
21714 (org-move-to-column column)))))))))
21716 (defun org-indent-region (start end)
21717 "Indent each non-blank line in the region.
21718 Called from a program, START and END specify the region to
21719 indent. The function will not indent contents of example blocks,
21720 verse blocks and export blocks as leading white spaces are
21721 assumed to be significant there."
21722 (interactive "r")
21723 (save-excursion
21724 (goto-char start)
21725 (skip-chars-forward " \r\t\n")
21726 (unless (eobp) (beginning-of-line))
21727 (let ((indent-to
21728 (lambda (ind pos)
21729 ;; Set IND as indentation for all lines between point and
21730 ;; POS. Blank lines are ignored. Leave point after POS
21731 ;; once done.
21732 (let ((limit (copy-marker pos)))
21733 (while (< (point) limit)
21734 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21735 (forward-line))
21736 (set-marker limit nil))))
21737 (end (copy-marker end)))
21738 (while (< (point) end)
21739 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21740 (let* ((element (org-element-at-point))
21741 (type (org-element-type element))
21742 (element-end (copy-marker (org-element-property :end element)))
21743 (ind (org--get-expected-indentation element nil)))
21744 (cond
21745 ;; Element indented as a single block. Example blocks
21746 ;; preserving indentation are a special case since the
21747 ;; "contents" must not be indented whereas the block
21748 ;; boundaries can.
21749 ((or (memq type '(export-block latex-environment))
21750 (and (eq type 'example-block)
21751 (not
21752 (or org-src-preserve-indentation
21753 (org-element-property :preserve-indent element)))))
21754 (let ((offset (- ind (org-get-indentation))))
21755 (unless (zerop offset)
21756 (indent-rigidly (org-element-property :begin element)
21757 (org-element-property :end element)
21758 offset)))
21759 (goto-char element-end))
21760 ;; Elements indented line wise. Be sure to exclude
21761 ;; example blocks (preserving indentation) and source
21762 ;; blocks from this category as they are treated
21763 ;; specially later.
21764 ((or (memq type '(paragraph table table-row))
21765 (not (or (org-element-property :contents-begin element)
21766 (memq type '(example-block src-block)))))
21767 (when (eq type 'node-property)
21768 (org--align-node-property)
21769 (beginning-of-line))
21770 (funcall indent-to ind (min element-end end)))
21771 ;; Elements consisting of three parts: before the
21772 ;; contents, the contents, and after the contents. The
21773 ;; contents are treated specially, according to the
21774 ;; element type, or not indented at all. Other parts are
21775 ;; indented as a single block.
21777 (let* ((post (copy-marker
21778 (org-element-property :post-affiliated element)))
21779 (cbeg
21780 (copy-marker
21781 (cond
21782 ((not (org-element-property :contents-begin element))
21783 ;; Fake contents for source blocks.
21784 (org-with-wide-buffer
21785 (goto-char post)
21786 (line-beginning-position 2)))
21787 ((memq type '(footnote-definition item plain-list))
21788 ;; Contents in these elements could start on
21789 ;; the same line as the beginning of the
21790 ;; element. Make sure we start indenting
21791 ;; from the second line.
21792 (org-with-wide-buffer
21793 (goto-char post)
21794 (end-of-line)
21795 (skip-chars-forward " \r\t\n")
21796 (if (eobp) (point) (line-beginning-position))))
21797 (t (org-element-property :contents-begin element)))))
21798 (cend (copy-marker
21799 (or (org-element-property :contents-end element)
21800 ;; Fake contents for source blocks.
21801 (org-with-wide-buffer
21802 (goto-char element-end)
21803 (skip-chars-backward " \r\t\n")
21804 (line-beginning-position)))
21805 t)))
21806 ;; Do not change items indentation individually as it
21807 ;; might break the list as a whole. On the other
21808 ;; hand, when at a plain list, indent it as a whole.
21809 (cond ((eq type 'plain-list)
21810 (let ((offset (- ind (org-get-indentation))))
21811 (unless (zerop offset)
21812 (indent-rigidly (org-element-property :begin element)
21813 (org-element-property :end element)
21814 offset))
21815 (goto-char cbeg)))
21816 ((eq type 'item) (goto-char cbeg))
21817 (t (funcall indent-to ind (min cbeg end))))
21818 (when (< (point) end)
21819 (cl-case type
21820 ((example-block verse-block))
21821 (src-block
21822 ;; In a source block, indent source code
21823 ;; according to language major mode, but only if
21824 ;; `org-src-tab-acts-natively' is non-nil.
21825 (when (and (< (point) end) org-src-tab-acts-natively)
21826 (ignore-errors
21827 (org-babel-do-in-edit-buffer
21828 (indent-region (point-min) (point-max))))))
21829 (t (org-indent-region (point) (min cend end))))
21830 (goto-char (min cend end))
21831 (when (< (point) end)
21832 (funcall indent-to ind (min element-end end))))
21833 (set-marker post nil)
21834 (set-marker cbeg nil)
21835 (set-marker cend nil))))
21836 (set-marker element-end nil))))
21837 (set-marker end nil))))
21839 (defun org-indent-drawer ()
21840 "Indent the drawer at point."
21841 (interactive)
21842 (unless (save-excursion
21843 (beginning-of-line)
21844 (looking-at-p org-drawer-regexp))
21845 (user-error "Not at a drawer"))
21846 (let ((element (org-element-at-point)))
21847 (unless (memq (org-element-type element) '(drawer property-drawer))
21848 (user-error "Not at a drawer"))
21849 (org-with-wide-buffer
21850 (org-indent-region (org-element-property :begin element)
21851 (org-element-property :end element))))
21852 (message "Drawer at point indented"))
21854 (defun org-indent-block ()
21855 "Indent the block at point."
21856 (interactive)
21857 (unless (save-excursion
21858 (beginning-of-line)
21859 (let ((case-fold-search t))
21860 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21861 (user-error "Not at a block"))
21862 (let ((element (org-element-at-point)))
21863 (unless (memq (org-element-type element)
21864 '(comment-block center-block dynamic-block example-block
21865 export-block quote-block special-block
21866 src-block verse-block))
21867 (user-error "Not at a block"))
21868 (org-with-wide-buffer
21869 (org-indent-region (org-element-property :begin element)
21870 (org-element-property :end element))))
21871 (message "Block at point indented"))
21874 ;;; Filling
21876 ;; We use our own fill-paragraph and auto-fill functions.
21878 ;; `org-fill-paragraph' relies on adaptive filling and context
21879 ;; checking. Appropriate `fill-prefix' is computed with
21880 ;; `org-adaptive-fill-function'.
21882 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21883 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21884 ;; `org-adaptive-fill-function' value. Internally,
21885 ;; `org-comment-line-break-function' breaks the line.
21887 ;; `org-setup-filling' installs filling and auto-filling related
21888 ;; variables during `org-mode' initialization.
21890 (defun org-setup-filling ()
21891 (require 'org-element)
21892 ;; Prevent auto-fill from inserting unwanted new items.
21893 (when (boundp 'fill-nobreak-predicate)
21894 (setq-local
21895 fill-nobreak-predicate
21896 (org-uniquify
21897 (append fill-nobreak-predicate
21898 '(org-fill-line-break-nobreak-p
21899 org-fill-n-macro-as-item-nobreak-p
21900 org-fill-paragraph-with-timestamp-nobreak-p)))))
21901 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21902 (setq-local paragraph-start paragraph-ending)
21903 (setq-local paragraph-separate paragraph-ending))
21904 (setq-local fill-paragraph-function 'org-fill-paragraph)
21905 (setq-local auto-fill-inhibit-regexp nil)
21906 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21907 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21908 (setq-local comment-line-break-function 'org-comment-line-break-function))
21910 (defun org-fill-line-break-nobreak-p ()
21911 "Non-nil when a new line at point would create an Org line break."
21912 (save-excursion
21913 (skip-chars-backward "[ \t]")
21914 (skip-chars-backward "\\\\")
21915 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21917 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21918 "Non-nil when a new line at point would split a timestamp."
21919 (and (org-at-timestamp-p 'lax)
21920 (not (looking-at org-ts-regexp-both))))
21922 (defun org-fill-n-macro-as-item-nobreak-p ()
21923 "Non-nil when a new line at point would create a new list."
21924 ;; During export, a "n" macro followed by a dot or a closing
21925 ;; parenthesis can end up being parsed as a new list item.
21926 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21928 (defvar orgtbl-line-start-regexp) ; From org-table.el
21929 (defun org-adaptive-fill-function ()
21930 "Compute a fill prefix for the current line.
21931 Return fill prefix, as a string, or nil if current line isn't
21932 meant to be filled. For convenience, if `adaptive-fill-regexp'
21933 matches in paragraphs or comments, use it."
21934 (org-with-wide-buffer
21935 (unless (org-at-heading-p)
21936 (let* ((p (line-beginning-position))
21937 (element (save-excursion
21938 (beginning-of-line)
21939 (org-element-at-point)))
21940 (type (org-element-type element))
21941 (post-affiliated (org-element-property :post-affiliated element)))
21942 (unless (< p post-affiliated)
21943 (cl-case type
21944 (comment
21945 (save-excursion
21946 (beginning-of-line)
21947 (looking-at "[ \t]*")
21948 (concat (match-string 0) "# ")))
21949 (footnote-definition "")
21950 ((item plain-list)
21951 (make-string (org-list-item-body-column post-affiliated) ?\s))
21952 (paragraph
21953 ;; Fill prefix is usually the same as the current line,
21954 ;; unless the paragraph is at the beginning of an item.
21955 (let ((parent (org-element-property :parent element)))
21956 (save-excursion
21957 (beginning-of-line)
21958 (cond ((eq (org-element-type parent) 'item)
21959 (make-string (org-list-item-body-column
21960 (org-element-property :begin parent))
21961 ?\s))
21962 ((and adaptive-fill-regexp
21963 ;; Locally disable
21964 ;; `adaptive-fill-function' to let
21965 ;; `fill-context-prefix' handle
21966 ;; `adaptive-fill-regexp' variable.
21967 (let (adaptive-fill-function)
21968 (fill-context-prefix
21969 post-affiliated
21970 (org-element-property :end element)))))
21971 ((looking-at "[ \t]+") (match-string 0))
21972 (t "")))))
21973 (comment-block
21974 ;; Only fill contents if P is within block boundaries.
21975 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21976 (forward-line)
21977 (point)))
21978 (cend (save-excursion
21979 (goto-char (org-element-property :end element))
21980 (skip-chars-backward " \r\t\n")
21981 (line-beginning-position))))
21982 (when (and (>= p cbeg) (< p cend))
21983 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21984 (match-string 0)
21985 ""))))))))))
21987 (defun org-fill-element (&optional justify)
21988 "Fill element at point, when applicable.
21990 This function only applies to comment blocks, comments, example
21991 blocks and paragraphs. Also, as a special case, re-align table
21992 when point is at one.
21994 If JUSTIFY is non-nil (interactively, with prefix argument),
21995 justify as well. If `sentence-end-double-space' is non-nil, then
21996 period followed by one space does not end a sentence, so don't
21997 break a line there. The variable `fill-column' controls the
21998 width for filling.
22000 For convenience, when point is at a plain list, an item or
22001 a footnote definition, try to fill the first paragraph within."
22002 (with-syntax-table org-mode-transpose-word-syntax-table
22003 ;; Move to end of line in order to get the first paragraph within
22004 ;; a plain list or a footnote definition.
22005 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22006 ;; First check if point is in a blank line at the beginning of
22007 ;; the buffer. In that case, ignore filling.
22008 (cl-case (org-element-type element)
22009 ;; Use major mode filling function is src blocks.
22010 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22011 ;; Align Org tables, leave table.el tables as-is.
22012 (table-row (org-table-align) t)
22013 (table
22014 (when (eq (org-element-property :type element) 'org)
22015 (save-excursion
22016 (goto-char (org-element-property :post-affiliated element))
22017 (org-table-align)))
22019 (paragraph
22020 ;; Paragraphs may contain `line-break' type objects.
22021 (let ((beg (max (point-min)
22022 (org-element-property :contents-begin element)))
22023 (end (min (point-max)
22024 (org-element-property :contents-end element))))
22025 ;; Do nothing if point is at an affiliated keyword.
22026 (if (< (line-end-position) beg) t
22027 ;; Fill paragraph, taking line breaks into account.
22028 (save-excursion
22029 (goto-char beg)
22030 (let ((cuts (list beg)))
22031 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22032 (when (eq 'line-break
22033 (org-element-type
22034 (save-excursion (backward-char)
22035 (org-element-context))))
22036 (push (point) cuts)))
22037 (dolist (c (delq end cuts))
22038 (fill-region-as-paragraph c end justify)
22039 (setq end c))))
22040 t)))
22041 ;; Contents of `comment-block' type elements should be
22042 ;; filled as plain text, but only if point is within block
22043 ;; markers.
22044 (comment-block
22045 (let* ((case-fold-search t)
22046 (beg (save-excursion
22047 (goto-char (org-element-property :begin element))
22048 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22049 (forward-line)
22050 (point)))
22051 (end (save-excursion
22052 (goto-char (org-element-property :end element))
22053 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22054 (line-beginning-position))))
22055 (if (or (< (point) beg) (> (point) end)) t
22056 (fill-region-as-paragraph
22057 (save-excursion (end-of-line)
22058 (re-search-backward "^[ \t]*$" beg 'move)
22059 (line-beginning-position))
22060 (save-excursion (beginning-of-line)
22061 (re-search-forward "^[ \t]*$" end 'move)
22062 (line-beginning-position))
22063 justify))))
22064 ;; Fill comments.
22065 (comment
22066 (let ((begin (org-element-property :post-affiliated element))
22067 (end (org-element-property :end element)))
22068 (when (and (>= (point) begin) (<= (point) end))
22069 (let ((begin (save-excursion
22070 (end-of-line)
22071 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22072 (progn (forward-line) (point))
22073 begin)))
22074 (end (save-excursion
22075 (end-of-line)
22076 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22077 (1- (line-beginning-position))
22078 (skip-chars-backward " \r\t\n")
22079 (line-end-position)))))
22080 ;; Do not fill comments when at a blank line.
22081 (when (> end begin)
22082 (let ((fill-prefix
22083 (save-excursion
22084 (beginning-of-line)
22085 (looking-at "[ \t]*#")
22086 (let ((comment-prefix (match-string 0)))
22087 (goto-char (match-end 0))
22088 (if (looking-at adaptive-fill-regexp)
22089 (concat comment-prefix (match-string 0))
22090 (concat comment-prefix " "))))))
22091 (save-excursion
22092 (fill-region-as-paragraph begin end justify))))))
22094 ;; Ignore every other element.
22095 (otherwise t)))))
22097 (defun org-fill-paragraph (&optional justify region)
22098 "Fill element at point, when applicable.
22100 This function only applies to comment blocks, comments, example
22101 blocks and paragraphs. Also, as a special case, re-align table
22102 when point is at one.
22104 For convenience, when point is at a plain list, an item or
22105 a footnote definition, try to fill the first paragraph within.
22107 If JUSTIFY is non-nil (interactively, with prefix argument),
22108 justify as well. If `sentence-end-double-space' is non-nil, then
22109 period followed by one space does not end a sentence, so don't
22110 break a line there. The variable `fill-column' controls the
22111 width for filling.
22113 The REGION argument is non-nil if called interactively; in that
22114 case, if Transient Mark mode is enabled and the mark is active,
22115 fill each of the elements in the active region, instead of just
22116 filling the current element."
22117 (interactive (progn
22118 (barf-if-buffer-read-only)
22119 (list (if current-prefix-arg 'full) t)))
22120 (cond
22121 ((and region transient-mark-mode mark-active
22122 (not (eq (region-beginning) (region-end))))
22123 (let ((origin (point-marker))
22124 (start (region-beginning)))
22125 (unwind-protect
22126 (progn
22127 (goto-char (region-end))
22128 (while (> (point) start)
22129 (org-backward-paragraph)
22130 (org-fill-element justify)))
22131 (goto-char origin)
22132 (set-marker origin nil))))
22133 (t (org-fill-element justify))))
22135 (defun org-auto-fill-function ()
22136 "Auto-fill function."
22137 ;; Check if auto-filling is meaningful.
22138 (let ((fc (current-fill-column)))
22139 (when (and fc (> (current-column) fc))
22140 (let* ((fill-prefix (org-adaptive-fill-function))
22141 ;; Enforce empty fill prefix, if required. Otherwise, it
22142 ;; will be computed again.
22143 (adaptive-fill-mode (not (equal fill-prefix ""))))
22144 (when fill-prefix (do-auto-fill))))))
22146 (defun org-comment-line-break-function (&optional soft)
22147 "Break line at point and indent, continuing comment if within one.
22148 The inserted newline is marked hard if variable
22149 `use-hard-newlines' is true, unless optional argument SOFT is
22150 non-nil."
22151 (if soft (insert-and-inherit ?\n) (newline 1))
22152 (save-excursion (forward-char -1) (delete-horizontal-space))
22153 (delete-horizontal-space)
22154 (indent-to-left-margin)
22155 (insert-before-markers-and-inherit fill-prefix))
22158 ;;; Fixed Width Areas
22160 (defun org-toggle-fixed-width ()
22161 "Toggle fixed-width markup.
22163 Add or remove fixed-width markup on current line, whenever it
22164 makes sense. Return an error otherwise.
22166 If a region is active and if it contains only fixed-width areas
22167 or blank lines, remove all fixed-width markup in it. If the
22168 region contains anything else, convert all non-fixed-width lines
22169 to fixed-width ones.
22171 Blank lines at the end of the region are ignored unless the
22172 region only contains such lines."
22173 (interactive)
22174 (if (not (org-region-active-p))
22175 ;; No region:
22177 ;; Remove fixed width marker only in a fixed-with element.
22179 ;; Add fixed width maker in paragraphs, in blank lines after
22180 ;; elements or at the beginning of a headline or an inlinetask,
22181 ;; and before any one-line elements (e.g., a clock).
22182 (progn
22183 (beginning-of-line)
22184 (let* ((element (org-element-at-point))
22185 (type (org-element-type element)))
22186 (cond
22187 ((and (eq type 'fixed-width)
22188 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22189 (replace-match
22190 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22191 ((and (memq type '(babel-call clock comment diary-sexp headline
22192 horizontal-rule keyword paragraph
22193 planning))
22194 (<= (org-element-property :post-affiliated element) (point)))
22195 (skip-chars-forward " \t")
22196 (insert ": "))
22197 ((and (looking-at-p "[ \t]*$")
22198 (or (eq type 'inlinetask)
22199 (save-excursion
22200 (skip-chars-forward " \r\t\n")
22201 (<= (org-element-property :end element) (point)))))
22202 (delete-region (point) (line-end-position))
22203 (org-indent-line)
22204 (insert ": "))
22205 (t (user-error "Cannot insert a fixed-width line here")))))
22206 ;; Region active.
22207 (let* ((begin (save-excursion
22208 (goto-char (region-beginning))
22209 (line-beginning-position)))
22210 (end (copy-marker
22211 (save-excursion
22212 (goto-char (region-end))
22213 (unless (eolp) (beginning-of-line))
22214 (if (save-excursion (re-search-backward "\\S-" begin t))
22215 (progn (skip-chars-backward " \r\t\n") (point))
22216 (point)))))
22217 (all-fixed-width-p
22218 (catch 'not-all-p
22219 (save-excursion
22220 (goto-char begin)
22221 (skip-chars-forward " \r\t\n")
22222 (when (eobp) (throw 'not-all-p nil))
22223 (while (< (point) end)
22224 (let ((element (org-element-at-point)))
22225 (if (eq (org-element-type element) 'fixed-width)
22226 (goto-char (org-element-property :end element))
22227 (throw 'not-all-p nil))))
22228 t))))
22229 (if all-fixed-width-p
22230 (save-excursion
22231 (goto-char begin)
22232 (while (< (point) end)
22233 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22234 (replace-match
22235 "" nil nil nil
22236 (if (= (line-end-position) (match-end 0)) 0 1)))
22237 (forward-line)))
22238 (let ((min-ind (point-max)))
22239 ;; Find minimum indentation across all lines.
22240 (save-excursion
22241 (goto-char begin)
22242 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22243 (setq min-ind 0)
22244 (catch 'zerop
22245 (while (< (point) end)
22246 (unless (looking-at-p "[ \t]*$")
22247 (let ((ind (org-get-indentation)))
22248 (setq min-ind (min min-ind ind))
22249 (when (zerop ind) (throw 'zerop t))))
22250 (forward-line)))))
22251 ;; Loop over all lines and add fixed-width markup everywhere
22252 ;; but in fixed-width lines.
22253 (save-excursion
22254 (goto-char begin)
22255 (while (< (point) end)
22256 (cond
22257 ((org-at-heading-p)
22258 (insert ": ")
22259 (forward-line)
22260 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22261 (insert ":")
22262 (forward-line)))
22263 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22264 (let* ((element (org-element-at-point))
22265 (element-end (org-element-property :end element)))
22266 (if (eq (org-element-type element) 'fixed-width)
22267 (progn (goto-char element-end)
22268 (skip-chars-backward " \r\t\n")
22269 (forward-line))
22270 (let ((limit (min end element-end)))
22271 (while (< (point) limit)
22272 (org-move-to-column min-ind t)
22273 (insert ": ")
22274 (forward-line))))))
22276 (org-move-to-column min-ind t)
22277 (insert ": ")
22278 (forward-line)))))))
22279 (set-marker end nil))))
22282 ;;; Blocks
22284 (defun org-block-map (function &optional start end)
22285 "Call FUNCTION at the head of all source blocks in the current buffer.
22286 Optional arguments START and END can be used to limit the range."
22287 (let ((start (or start (point-min)))
22288 (end (or end (point-max))))
22289 (save-excursion
22290 (goto-char start)
22291 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22292 (save-excursion
22293 (save-match-data
22294 (goto-char (match-beginning 0))
22295 (funcall function)))))))
22297 (defun org-next-block (arg &optional backward block-regexp)
22298 "Jump to the next block.
22300 With a prefix argument ARG, jump forward ARG many blocks.
22302 When BACKWARD is non-nil, jump to the previous block.
22304 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22305 Match data is set according to this regexp when the function
22306 returns.
22308 Return point at beginning of the opening line of found block.
22309 Throw an error if no block is found."
22310 (interactive "p")
22311 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22312 (case-fold-search t)
22313 (search-fn (if backward #'re-search-backward #'re-search-forward))
22314 (count (or arg 1))
22315 (origin (point))
22316 last-element)
22317 (if backward (beginning-of-line) (end-of-line))
22318 (while (and (> count 0) (funcall search-fn re nil t))
22319 (let ((element (save-excursion
22320 (goto-char (match-beginning 0))
22321 (save-match-data (org-element-at-point)))))
22322 (when (and (memq (org-element-type element)
22323 '(center-block comment-block dynamic-block
22324 example-block export-block quote-block
22325 special-block src-block verse-block))
22326 (<= (match-beginning 0)
22327 (org-element-property :post-affiliated element)))
22328 (setq last-element element)
22329 (cl-decf count))))
22330 (if (= count 0)
22331 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22332 (save-match-data (org-show-context)))
22333 (goto-char origin)
22334 (user-error "No %s code blocks" (if backward "previous" "further")))))
22336 (defun org-previous-block (arg &optional block-regexp)
22337 "Jump to the previous block.
22338 With a prefix argument ARG, jump backward ARG many source blocks.
22339 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22340 (interactive "p")
22341 (org-next-block arg t block-regexp))
22344 ;;; Comments
22346 ;; Org comments syntax is quite complex. It requires the entire line
22347 ;; to be just a comment. Also, even with the right syntax at the
22348 ;; beginning of line, some elements (e.g., verse-block or
22349 ;; example-block) don't accept comments. Usual Emacs comment commands
22350 ;; cannot cope with those requirements. Therefore, Org replaces them.
22352 ;; Org still relies on `comment-dwim', but cannot trust
22353 ;; `comment-only-p'. So, `comment-region-function' and
22354 ;; `uncomment-region-function' both point
22355 ;; to`org-comment-or-uncomment-region'. Eventually,
22356 ;; `org-insert-comment' takes care of insertion of comments at the
22357 ;; beginning of line.
22359 ;; `org-setup-comments-handling' install comments related variables
22360 ;; during `org-mode' initialization.
22362 (defun org-setup-comments-handling ()
22363 (interactive)
22364 (setq-local comment-use-syntax nil)
22365 (setq-local comment-start "# ")
22366 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22367 (setq-local comment-insert-comment-function 'org-insert-comment)
22368 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22369 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22371 (defun org-insert-comment ()
22372 "Insert an empty comment above current line.
22373 If the line is empty, insert comment at its beginning. When
22374 point is within a source block, comment according to the related
22375 major mode."
22376 (if (let ((element (org-element-at-point)))
22377 (and (eq (org-element-type element) 'src-block)
22378 (< (save-excursion
22379 (goto-char (org-element-property :post-affiliated element))
22380 (line-end-position))
22381 (point))
22382 (> (save-excursion
22383 (goto-char (org-element-property :end element))
22384 (skip-chars-backward " \r\t\n")
22385 (line-beginning-position))
22386 (point))))
22387 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22388 (beginning-of-line)
22389 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22390 (open-line 1))
22391 (org-indent-line)
22392 (insert "# ")))
22394 (defvar comment-empty-lines) ; From newcomment.el.
22395 (defun org-comment-or-uncomment-region (beg end &rest _)
22396 "Comment or uncomment each non-blank line in the region.
22397 Uncomment each non-blank line between BEG and END if it only
22398 contains commented lines. Otherwise, comment them. If region is
22399 strictly within a source block, use appropriate comment syntax."
22400 (if (let ((element (org-element-at-point)))
22401 (and (eq (org-element-type element) 'src-block)
22402 (< (save-excursion
22403 (goto-char (org-element-property :post-affiliated element))
22404 (line-end-position))
22405 beg)
22406 (>= (save-excursion
22407 (goto-char (org-element-property :end element))
22408 (skip-chars-backward " \r\t\n")
22409 (line-beginning-position))
22410 end)))
22411 ;; Translate region boundaries for the Org buffer to the source
22412 ;; buffer.
22413 (let ((offset (- end beg)))
22414 (save-excursion
22415 (goto-char beg)
22416 (org-babel-do-in-edit-buffer
22417 (comment-or-uncomment-region (point) (+ offset (point))))))
22418 (save-restriction
22419 ;; Restrict region
22420 (narrow-to-region (save-excursion (goto-char beg)
22421 (skip-chars-forward " \r\t\n" end)
22422 (line-beginning-position))
22423 (save-excursion (goto-char end)
22424 (skip-chars-backward " \r\t\n" beg)
22425 (line-end-position)))
22426 (let ((uncommentp
22427 ;; UNCOMMENTP is non-nil when every non blank line between
22428 ;; BEG and END is a comment.
22429 (save-excursion
22430 (goto-char (point-min))
22431 (while (and (not (eobp))
22432 (let ((element (org-element-at-point)))
22433 (and (eq (org-element-type element) 'comment)
22434 (goto-char (min (point-max)
22435 (org-element-property
22436 :end element)))))))
22437 (eobp))))
22438 (if uncommentp
22439 ;; Only blank lines and comments in region: uncomment it.
22440 (save-excursion
22441 (goto-char (point-min))
22442 (while (not (eobp))
22443 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22444 (replace-match "" nil nil nil 1))
22445 (forward-line)))
22446 ;; Comment each line in region.
22447 (let ((min-indent (point-max)))
22448 ;; First find the minimum indentation across all lines.
22449 (save-excursion
22450 (goto-char (point-min))
22451 (while (and (not (eobp)) (not (zerop min-indent)))
22452 (unless (looking-at "[ \t]*$")
22453 (setq min-indent (min min-indent (current-indentation))))
22454 (forward-line)))
22455 ;; Then loop over all lines.
22456 (save-excursion
22457 (goto-char (point-min))
22458 (while (not (eobp))
22459 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22460 ;; Don't get fooled by invisible text (e.g. link path)
22461 ;; when moving to column MIN-INDENT.
22462 (let ((buffer-invisibility-spec nil))
22463 (org-move-to-column min-indent t))
22464 (insert comment-start))
22465 (forward-line)))))))))
22467 (defun org-comment-dwim (_arg)
22468 "Call the comment command you mean.
22469 Call `org-toggle-comment' if on a heading, otherwise call
22470 `comment-dwim', within a source edit buffer if needed."
22471 (interactive "*P")
22472 (cond ((org-at-heading-p)
22473 (call-interactively #'org-toggle-comment))
22474 ((org-in-src-block-p)
22475 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22476 (t (call-interactively #'comment-dwim))))
22479 ;;; Timestamps API
22481 ;; This section contains tools to operate on, or create, timestamp
22482 ;; objects, as returned by, e.g. `org-element-context'.
22484 (defun org-timestamp-from-string (s)
22485 "Convert Org timestamp S, as a string, into a timestamp object.
22486 Return nil if S is not a valid timestamp string."
22487 (when (org-string-nw-p s)
22488 (with-temp-buffer
22489 (save-excursion (insert s))
22490 (org-element-timestamp-parser))))
22492 (defun org-timestamp-from-time (time &optional with-time inactive)
22493 "Convert a time value into a timestamp object.
22495 TIME is an Emacs internal time representation, as returned, e.g.,
22496 by `current-time'.
22498 When optional argument WITH-TIME is non-nil, return a timestamp
22499 object with a time part, i.e., with hours and minutes.
22501 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22502 return an active timestamp."
22503 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22504 (org-element-create 'timestamp
22505 (list :type (if inactive 'inactive 'active)
22506 :year-start year
22507 :month-start month
22508 :day-start day
22509 :hour-start (and with-time hour)
22510 :minute-start (and with-time minute)))))
22512 (defun org-timestamp-to-time (timestamp &optional end)
22513 "Convert TIMESTAMP object into an Emacs internal time value.
22514 Use end of date range or time range when END is non-nil.
22515 Otherwise, use its start."
22516 (apply #'encode-time
22517 (cons 0
22518 (mapcar
22519 (lambda (prop) (or (org-element-property prop timestamp) 0))
22520 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22521 '(:minute-start :hour-start :day-start :month-start
22522 :year-start))))))
22524 (defun org-timestamp-has-time-p (timestamp)
22525 "Non-nil when TIMESTAMP has a time specified."
22526 (org-element-property :hour-start timestamp))
22528 (defun org-timestamp-format (timestamp format &optional end utc)
22529 "Format a TIMESTAMP object into a string.
22531 FORMAT is a format specifier to be passed to
22532 `format-time-string'.
22534 When optional argument END is non-nil, use end of date-range or
22535 time-range, if possible.
22537 When optional argument UTC is non-nil, time is be expressed as
22538 Universal Time."
22539 (format-time-string format (org-timestamp-to-time timestamp end)
22540 (and utc t)))
22542 (defun org-timestamp-split-range (timestamp &optional end)
22543 "Extract a TIMESTAMP object from a date or time range.
22545 END, when non-nil, means extract the end of the range.
22546 Otherwise, extract its start.
22548 Return a new timestamp object."
22549 (let ((type (org-element-property :type timestamp)))
22550 (if (memq type '(active inactive diary)) timestamp
22551 (let ((split-ts (org-element-copy timestamp)))
22552 ;; Set new type.
22553 (org-element-put-property
22554 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22555 ;; Copy start properties over end properties if END is
22556 ;; non-nil. Otherwise, copy end properties over `start' ones.
22557 (let ((p-alist '((:minute-start . :minute-end)
22558 (:hour-start . :hour-end)
22559 (:day-start . :day-end)
22560 (:month-start . :month-end)
22561 (:year-start . :year-end))))
22562 (dolist (p-cell p-alist)
22563 (org-element-put-property
22564 split-ts
22565 (funcall (if end #'car #'cdr) p-cell)
22566 (org-element-property
22567 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22568 ;; Eventually refresh `:raw-value'.
22569 (org-element-put-property split-ts :raw-value nil)
22570 (org-element-put-property
22571 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22573 (defun org-timestamp-translate (timestamp &optional boundary)
22574 "Translate TIMESTAMP object to custom format.
22576 Format string is defined in `org-time-stamp-custom-formats',
22577 which see.
22579 When optional argument BOUNDARY is non-nil, it is either the
22580 symbol `start' or `end'. In this case, only translate the
22581 starting or ending part of TIMESTAMP if it is a date or time
22582 range. Otherwise, translate both parts.
22584 Return timestamp as-is if `org-display-custom-times' is nil or if
22585 it has a `diary' type."
22586 (let ((type (org-element-property :type timestamp)))
22587 (if (or (not org-display-custom-times) (eq type 'diary))
22588 (org-element-interpret-data timestamp)
22589 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22590 org-time-stamp-custom-formats)))
22591 (if (and (not boundary) (memq type '(active-range inactive-range)))
22592 (concat (org-timestamp-format timestamp fmt)
22593 "--"
22594 (org-timestamp-format timestamp fmt t))
22595 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22597 ;;; Other stuff
22599 (defvar reftex-docstruct-symbol)
22600 (defvar org--rds)
22602 (defun org-reftex-citation ()
22603 "Use reftex-citation to insert a citation into the buffer.
22604 This looks for a line like
22606 #+BIBLIOGRAPHY: foo plain option:-d
22608 and derives from it that foo.bib is the bibliography file relevant
22609 for this document. It then installs the necessary environment for RefTeX
22610 to work in this buffer and calls `reftex-citation' to insert a citation
22611 into the buffer.
22613 Export of such citations to both LaTeX and HTML is handled by the contributed
22614 package ox-bibtex by Taru Karttunen."
22615 (interactive)
22616 (let ((reftex-docstruct-symbol 'org--rds)
22617 org--rds bib)
22618 (org-with-wide-buffer
22619 (let ((case-fold-search t)
22620 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22621 (if (not (save-excursion
22622 (or (re-search-forward re nil t)
22623 (re-search-backward re nil t))))
22624 (user-error "No bibliography defined in file")
22625 (setq bib (concat (match-string 1) ".bib")
22626 org--rds (list (list 'bib bib))))))
22627 (call-interactively 'reftex-citation)))
22629 ;;;; Functions extending outline functionality
22631 (defun org-beginning-of-line (&optional n)
22632 "Go to the beginning of the current visible line.
22634 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22635 symbol `reversed', on the first attempt move to where the
22636 headline text starts, and only move to beginning of line when the
22637 cursor is already before the start of the text of the headline.
22639 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22640 start of the text on the second attempt.
22642 With argument N not nil or 1, move forward N - 1 lines first."
22643 (interactive "^p")
22644 (let ((origin (point))
22645 (special (pcase org-special-ctrl-a/e
22646 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22647 deactivate-mark)
22648 ;; First move to a visible line.
22649 (if (bound-and-true-p visual-line-mode)
22650 (beginning-of-visual-line n)
22651 (move-beginning-of-line n)
22652 ;; `move-beginning-of-line' may leave point after invisible
22653 ;; characters if line starts with such of these (e.g., with
22654 ;; a link at column 0). Really move to the beginning of the
22655 ;; current visible line.
22656 (beginning-of-line))
22657 (cond
22658 ;; No special behavior. Point is already at the beginning of
22659 ;; a line, logical or visual.
22660 ((not special))
22661 ;; `beginning-of-visual-line' left point before logical beginning
22662 ;; of line: point is at the beginning of a visual line. Bail
22663 ;; out.
22664 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22665 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22666 ;; At a headline, special position is before the title, but
22667 ;; after any TODO keyword or priority cookie.
22668 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22669 (line-end-position)))
22670 (bol (point)))
22671 (if (eq special 'reversed)
22672 (when (and (= origin bol) (eq last-command this-command))
22673 (goto-char refpos))
22674 (when (or (> origin refpos) (= origin bol))
22675 (goto-char refpos)))))
22676 ((and (looking-at org-list-full-item-re)
22677 (memq (org-element-type (save-match-data (org-element-at-point)))
22678 '(item plain-list)))
22679 ;; Set special position at first white space character after
22680 ;; bullet, and check-box, if any.
22681 (let ((after-bullet
22682 (let ((box (match-end 3)))
22683 (cond ((not box) (match-end 1))
22684 ((eq (char-after box) ?\s) (1+ box))
22685 (t box)))))
22686 (if (eq special 'reversed)
22687 (when (and (= (point) origin) (eq last-command this-command))
22688 (goto-char after-bullet))
22689 (when (or (> origin after-bullet) (= (point) origin))
22690 (goto-char after-bullet)))))
22691 ;; No special context. Point is already at beginning of line.
22692 (t nil))))
22694 (defun org-end-of-line (&optional n)
22695 "Go to the end of the line, but before ellipsis, if any.
22697 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22698 symbol `reversed', ignore tags on the first attempt, and only
22699 move to after the tags when the cursor is already beyond the end
22700 of the headline.
22702 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22703 on the second attempt.
22705 With argument N not nil or 1, move forward N - 1 lines first."
22706 (interactive "^p")
22707 (let ((origin (point))
22708 (special (pcase org-special-ctrl-a/e
22709 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22710 deactivate-mark)
22711 ;; First move to a visible line.
22712 (if (bound-and-true-p visual-line-mode)
22713 (beginning-of-visual-line n)
22714 (move-beginning-of-line n))
22715 (cond
22716 ;; At a headline, with tags.
22717 ((and special
22718 (save-excursion
22719 (beginning-of-line)
22720 (let ((case-fold-search nil))
22721 (looking-at org-complex-heading-regexp)))
22722 (match-end 5))
22723 (let ((tags (save-excursion
22724 (goto-char (match-beginning 5))
22725 (skip-chars-backward " \t")
22726 (point)))
22727 (visual-end (and (bound-and-true-p visual-line-mode)
22728 (save-excursion
22729 (end-of-visual-line)
22730 (point)))))
22731 ;; If `end-of-visual-line' brings us before end of line or
22732 ;; even tags, i.e., the headline spans over multiple visual
22733 ;; lines, move there.
22734 (cond ((and visual-end
22735 (< visual-end tags)
22736 (<= origin visual-end))
22737 (goto-char visual-end))
22738 ((eq special 'reversed)
22739 (if (and (= origin (line-end-position))
22740 (eq this-command last-command))
22741 (goto-char tags)
22742 (end-of-line)))
22744 (if (or (< origin tags) (= origin (line-end-position)))
22745 (goto-char tags)
22746 (end-of-line))))))
22747 ((bound-and-true-p visual-line-mode)
22748 (let ((bol (line-beginning-position)))
22749 (end-of-visual-line)
22750 ;; If `end-of-visual-line' gets us past the ellipsis at the
22751 ;; end of a line, backtrack and use `end-of-line' instead.
22752 (when (/= bol (line-beginning-position))
22753 (goto-char bol)
22754 (end-of-line))))
22755 (t (end-of-line)))))
22757 (defun org-backward-sentence (&optional _arg)
22758 "Go to beginning of sentence, or beginning of table field.
22759 This will call `backward-sentence' or `org-table-beginning-of-field',
22760 depending on context."
22761 (interactive)
22762 (let* ((element (org-element-at-point))
22763 (contents-begin (org-element-property :contents-begin element))
22764 (table (org-element-lineage element '(table) t)))
22765 (if (and table
22766 (> (point) contents-begin)
22767 (<= (point) (org-element-property :contents-end table)))
22768 (call-interactively #'org-table-beginning-of-field)
22769 (save-restriction
22770 (when (and contents-begin
22771 (< (point-min) contents-begin)
22772 (> (point) contents-begin))
22773 (narrow-to-region contents-begin
22774 (org-element-property :contents-end element)))
22775 (call-interactively #'backward-sentence)))))
22777 (defun org-forward-sentence (&optional _arg)
22778 "Go to end of sentence, or end of table field.
22779 This will call `forward-sentence' or `org-table-end-of-field',
22780 depending on context."
22781 (interactive)
22782 (if (and (org-at-heading-p)
22783 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22784 (save-restriction
22785 (narrow-to-region (line-beginning-position) (line-end-position))
22786 (call-interactively #'forward-sentence))
22787 (let* ((element (org-element-at-point))
22788 (contents-end (org-element-property :contents-end element))
22789 (table (org-element-lineage element '(table) t)))
22790 (if (and table
22791 (>= (point) (org-element-property :contents-begin table))
22792 (< (point) contents-end))
22793 (call-interactively #'org-table-end-of-field)
22794 (save-restriction
22795 (when (and contents-end
22796 (> (point-max) contents-end)
22797 ;; Skip blank lines between elements.
22798 (< (org-element-property :end element)
22799 (save-excursion (goto-char contents-end)
22800 (skip-chars-forward " \r\t\n"))))
22801 (narrow-to-region (org-element-property :contents-begin element)
22802 contents-end))
22803 ;; End of heading is considered as the end of a sentence.
22804 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22805 (call-interactively #'forward-sentence)))))))
22807 (defun org-kill-line (&optional _arg)
22808 "Kill line, to tags or end of line."
22809 (interactive)
22810 (cond
22811 ((or (not org-special-ctrl-k)
22812 (bolp)
22813 (not (org-at-heading-p)))
22814 (when (and (get-char-property (line-end-position) 'invisible)
22815 org-ctrl-k-protect-subtree
22816 (or (eq org-ctrl-k-protect-subtree 'error)
22817 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22818 (user-error
22819 (substitute-command-keys
22820 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22821 (call-interactively
22822 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22823 ((looking-at org-tag-line-re)
22824 (let ((end (save-excursion
22825 (goto-char (match-beginning 1))
22826 (skip-chars-backward " \t"))))
22827 (if (<= end (point)) ;on tags part
22828 (kill-region (point) (line-end-position))
22829 (kill-region (point) end)))
22830 (org-set-tags nil t))
22831 (t (kill-region (point) (line-end-position)))))
22833 (defun org-yank (&optional arg)
22834 "Yank. If the kill is a subtree, treat it specially.
22835 This command will look at the current kill and check if is a single
22836 subtree, or a series of subtrees[1]. If it passes the test, and if the
22837 cursor is at the beginning of a line or after the stars of a currently
22838 empty headline, then the yank is handled specially. How exactly depends
22839 on the value of the following variables.
22841 `org-yank-folded-subtrees'
22842 By default, this variable is non-nil, which results in
22843 subtree(s) being folded after insertion, except if doing so
22844 would swallow text after the yanked text.
22846 `org-yank-adjusted-subtrees'
22847 When non-nil (the default value is nil), the subtree will be
22848 promoted or demoted in order to fit into the local outline tree
22849 structure, which means that the level will be adjusted so that it
22850 becomes the smaller one of the two *visible* surrounding headings.
22852 Any prefix to this command will cause `yank' to be called directly with
22853 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22854 will just
22855 plainly yank the text as it is.
22857 \[1] The test checks if the first non-white line is a heading
22858 and if there are no other headings with fewer stars."
22859 (interactive "P")
22860 (org-yank-generic 'yank arg))
22862 (defun org-yank-generic (command arg)
22863 "Perform some yank-like command.
22865 This function implements the behavior described in the `org-yank'
22866 documentation. However, it has been generalized to work for any
22867 interactive command with similar behavior."
22869 ;; pretend to be command COMMAND
22870 (setq this-command command)
22872 (if arg
22873 (call-interactively command)
22875 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22876 (and (org-kill-is-subtree-p)
22877 (or (bolp)
22878 (and (looking-at "[ \t]*$")
22879 (string-match
22880 "\\`\\*+\\'"
22881 (buffer-substring (point-at-bol) (point)))))))
22882 swallowp)
22883 (cond
22884 ((and subtreep org-yank-folded-subtrees)
22885 (let ((beg (point))
22886 end)
22887 (if (and subtreep org-yank-adjusted-subtrees)
22888 (org-paste-subtree nil nil 'for-yank)
22889 (call-interactively command))
22891 (setq end (point))
22892 (goto-char beg)
22893 (when (and (bolp) subtreep
22894 (not (setq swallowp
22895 (org-yank-folding-would-swallow-text beg end))))
22896 (org-with-limited-levels
22897 (or (looking-at org-outline-regexp)
22898 (re-search-forward org-outline-regexp-bol end t))
22899 (while (and (< (point) end) (looking-at org-outline-regexp))
22900 (outline-hide-subtree)
22901 (org-cycle-show-empty-lines 'folded)
22902 (condition-case nil
22903 (outline-forward-same-level 1)
22904 (error (goto-char end))))))
22905 (when swallowp
22906 (message
22907 "Inserted text not folded because that would swallow text"))
22909 (goto-char end)
22910 (skip-chars-forward " \t\n\r")
22911 (beginning-of-line 1)
22912 (push-mark beg 'nomsg)))
22913 ((and subtreep org-yank-adjusted-subtrees)
22914 (let ((beg (point-at-bol)))
22915 (org-paste-subtree nil nil 'for-yank)
22916 (push-mark beg 'nomsg)))
22918 (call-interactively command))))))
22920 (defun org-yank-folding-would-swallow-text (beg end)
22921 "Would hide-subtree at BEG swallow any text after END?"
22922 (let (level)
22923 (org-with-limited-levels
22924 (save-excursion
22925 (goto-char beg)
22926 (when (or (looking-at org-outline-regexp)
22927 (re-search-forward org-outline-regexp-bol end t))
22928 (setq level (org-outline-level)))
22929 (goto-char end)
22930 (skip-chars-forward " \t\r\n\v\f")
22931 (not (or (eobp)
22932 (and (bolp) (looking-at-p org-outline-regexp)
22933 (<= (org-outline-level) level))))))))
22935 (defun org-back-to-heading (&optional invisible-ok)
22936 "Call `outline-back-to-heading', but provide a better error message."
22937 (condition-case nil
22938 (outline-back-to-heading invisible-ok)
22939 (error (error "Before first headline at position %d in buffer %s"
22940 (point) (current-buffer)))))
22942 (defun org-before-first-heading-p ()
22943 "Before first heading?"
22944 (save-excursion
22945 (end-of-line)
22946 (null (re-search-backward org-outline-regexp-bol nil t))))
22948 (defun org-at-heading-p (&optional ignored)
22949 (outline-on-heading-p t))
22951 (defun org-in-commented-heading-p (&optional no-inheritance)
22952 "Non-nil if point is under a commented heading.
22953 This function also checks ancestors of the current headline,
22954 unless optional argument NO-INHERITANCE is non-nil."
22955 (cond
22956 ((org-before-first-heading-p) nil)
22957 ((let ((headline (nth 4 (org-heading-components))))
22958 (and headline
22959 (let ((case-fold-search nil))
22960 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22961 headline)))))
22962 (no-inheritance nil)
22964 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22966 (defun org-at-comment-p nil
22967 "Is cursor in a commented line?"
22968 (save-excursion
22969 (save-match-data
22970 (beginning-of-line)
22971 (looking-at "^[ \t]*# "))))
22973 (defun org-at-drawer-p nil
22974 "Is cursor at a drawer keyword?"
22975 (save-excursion
22976 (move-beginning-of-line 1)
22977 (looking-at org-drawer-regexp)))
22979 (defun org-at-block-p nil
22980 "Is cursor at a block keyword?"
22981 (save-excursion
22982 (move-beginning-of-line 1)
22983 (looking-at org-block-regexp)))
22985 (defun org-point-at-end-of-empty-headline ()
22986 "If point is at the end of an empty headline, return t, else nil.
22987 If the heading only contains a TODO keyword, it is still still considered
22988 empty."
22989 (let ((case-fold-search nil))
22990 (and (looking-at "[ \t]*$")
22991 org-todo-line-regexp
22992 (save-excursion
22993 (beginning-of-line)
22994 (looking-at org-todo-line-regexp)
22995 (string= (match-string 3) "")))))
22997 (defun org-at-heading-or-item-p ()
22998 (or (org-at-heading-p) (org-at-item-p)))
23000 (defun org-at-target-p ()
23001 (or (org-in-regexp org-radio-target-regexp)
23002 (org-in-regexp org-target-regexp)))
23003 ;; Compatibility alias with Org versions < 7.8.03
23004 (defalias 'org-on-target-p 'org-at-target-p)
23006 (defun org-up-heading-all (arg)
23007 "Move to the heading line of which the present line is a subheading.
23008 This function considers both visible and invisible heading lines.
23009 With argument, move up ARG levels."
23010 (outline-up-heading arg t))
23012 (defun org-up-heading-safe ()
23013 "Move to the heading line of which the present line is a subheading.
23014 This version will not throw an error. It will return the level of the
23015 headline found, or nil if no higher level is found.
23017 Also, this function will be a lot faster than `outline-up-heading',
23018 because it relies on stars being the outline starters. This can really
23019 make a significant difference in outlines with very many siblings."
23020 (when (ignore-errors (org-back-to-heading t))
23021 (let ((level-up (1- (funcall outline-level))))
23022 (and (> level-up 0)
23023 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23024 (funcall outline-level)))))
23026 (defun org-first-sibling-p ()
23027 "Is this heading the first child of its parents?"
23028 (interactive)
23029 (let ((re org-outline-regexp-bol)
23030 level l)
23031 (unless (org-at-heading-p t)
23032 (user-error "Not at a heading"))
23033 (setq level (funcall outline-level))
23034 (save-excursion
23035 (if (not (re-search-backward re nil t))
23037 (setq l (funcall outline-level))
23038 (< l level)))))
23040 (defun org-goto-sibling (&optional previous)
23041 "Goto the next sibling, even if it is invisible.
23042 When PREVIOUS is set, go to the previous sibling instead. Returns t
23043 when a sibling was found. When none is found, return nil and don't
23044 move point."
23045 (let ((fun (if previous 're-search-backward 're-search-forward))
23046 (pos (point))
23047 (re org-outline-regexp-bol)
23048 level l)
23049 (when (ignore-errors (org-back-to-heading t))
23050 (setq level (funcall outline-level))
23051 (catch 'exit
23052 (or previous (forward-char 1))
23053 (while (funcall fun re nil t)
23054 (setq l (funcall outline-level))
23055 (when (< l level) (goto-char pos) (throw 'exit nil))
23056 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23057 (goto-char pos)
23058 nil))))
23060 (defun org-show-siblings ()
23061 "Show all siblings of the current headline."
23062 (save-excursion
23063 (while (org-goto-sibling) (org-flag-heading nil)))
23064 (save-excursion
23065 (while (org-goto-sibling 'previous)
23066 (org-flag-heading nil))))
23068 (defun org-goto-first-child ()
23069 "Goto the first child, even if it is invisible.
23070 Return t when a child was found. Otherwise don't move point and
23071 return nil."
23072 (let (level (pos (point)) (re org-outline-regexp-bol))
23073 (when (ignore-errors (org-back-to-heading t))
23074 (setq level (outline-level))
23075 (forward-char 1)
23076 (if (and (re-search-forward re nil t) (> (outline-level) level))
23077 (progn (goto-char (match-beginning 0)) t)
23078 (goto-char pos) nil))))
23080 (defun org-show-hidden-entry ()
23081 "Show an entry where even the heading is hidden."
23082 (save-excursion
23083 (org-show-entry)))
23085 (defun org-flag-heading (flag &optional entry)
23086 "Flag the current heading. FLAG non-nil means make invisible.
23087 When ENTRY is non-nil, show the entire entry."
23088 (save-excursion
23089 (org-back-to-heading t)
23090 ;; Check if we should show the entire entry
23091 (if (not entry)
23092 (org-flag-region
23093 (line-end-position 0) (line-end-position) flag 'outline)
23094 (org-show-entry)
23095 (save-excursion
23096 (and (outline-next-heading)
23097 (org-flag-heading nil))))))
23099 (defun org-get-next-sibling ()
23100 "Move to next heading of the same level, and return point.
23101 If there is no such heading, return nil.
23102 This is like outline-next-sibling, but invisible headings are ok."
23103 (let ((level (funcall outline-level)))
23104 (outline-next-heading)
23105 (while (and (not (eobp)) (> (funcall outline-level) level))
23106 (outline-next-heading))
23107 (unless (or (eobp) (< (funcall outline-level) level))
23108 (point))))
23110 (defun org-get-last-sibling ()
23111 "Move to previous heading of the same level, and return point.
23112 If there is no such heading, return nil."
23113 (let ((opoint (point))
23114 (level (funcall outline-level)))
23115 (outline-previous-heading)
23116 (when (and (/= (point) opoint) (outline-on-heading-p t))
23117 (while (and (> (funcall outline-level) level)
23118 (not (bobp)))
23119 (outline-previous-heading))
23120 (unless (< (funcall outline-level) level)
23121 (point)))))
23123 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23124 "Goto to the end of a subtree."
23125 ;; This contains an exact copy of the original function, but it uses
23126 ;; `org-back-to-heading', to make it work also in invisible
23127 ;; trees. And is uses an invisible-ok argument.
23128 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23129 ;; Furthermore, when used inside Org, finding the end of a large subtree
23130 ;; with many children and grandchildren etc, this can be much faster
23131 ;; than the outline version.
23132 (org-back-to-heading invisible-ok)
23133 (let ((first t)
23134 (level (funcall outline-level)))
23135 (if (and (derived-mode-p 'org-mode) (< level 1000))
23136 ;; A true heading (not a plain list item), in Org
23137 ;; This means we can easily find the end by looking
23138 ;; only for the right number of stars. Using a regexp to do
23139 ;; this is so much faster than using a Lisp loop.
23140 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23141 (forward-char 1)
23142 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23143 ;; something else, do it the slow way
23144 (while (and (not (eobp))
23145 (or first (> (funcall outline-level) level)))
23146 (setq first nil)
23147 (outline-next-heading)))
23148 (unless to-heading
23149 (when (memq (preceding-char) '(?\n ?\^M))
23150 ;; Go to end of line before heading
23151 (forward-char -1)
23152 (when (memq (preceding-char) '(?\n ?\^M))
23153 ;; leave blank line before heading
23154 (forward-char -1)))))
23155 (point))
23157 (defun org-end-of-meta-data (&optional full)
23158 "Skip planning line and properties drawer in current entry.
23159 When optional argument FULL is non-nil, also skip empty lines,
23160 clocking lines and regular drawers at the beginning of the
23161 entry."
23162 (org-back-to-heading t)
23163 (forward-line)
23164 (when (looking-at-p org-planning-line-re) (forward-line))
23165 (when (looking-at org-property-drawer-re)
23166 (goto-char (match-end 0))
23167 (forward-line))
23168 (when (and full (not (org-at-heading-p)))
23169 (catch 'exit
23170 (let ((end (save-excursion (outline-next-heading) (point)))
23171 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23172 (while (not (eobp))
23173 (cond ((looking-at-p org-drawer-regexp)
23174 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23175 (forward-line)
23176 (throw 'exit t)))
23177 ((looking-at-p re) (forward-line))
23178 (t (throw 'exit t))))))))
23180 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23181 "Move forward to the ARG'th subheading at same level as this one.
23182 Stop at the first and last subheadings of a superior heading.
23183 Normally this only looks at visible headings, but when INVISIBLE-OK is
23184 non-nil it will also look at invisible ones."
23185 (interactive "p")
23186 (let ((backward? (and arg (< arg 0))))
23187 (if (org-before-first-heading-p)
23188 (if backward? (goto-char (point-min)) (outline-next-heading))
23189 (org-back-to-heading invisible-ok)
23190 (unless backward? (end-of-line)) ;do not match current headline
23191 (let ((level (- (match-end 0) (match-beginning 0) 1))
23192 (f (if backward? #'re-search-backward #'re-search-forward))
23193 (count (if arg (abs arg) 1))
23194 (result (point)))
23195 (while (and (> count 0)
23196 (funcall f org-outline-regexp-bol nil 'move))
23197 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23198 (cond ((< l level) (setq count 0))
23199 ((and (= l level)
23200 (or invisible-ok
23201 (not (org-invisible-p
23202 (line-beginning-position)))))
23203 (cl-decf count)
23204 (when (= l level) (setq result (point)))))))
23205 (goto-char result))
23206 (beginning-of-line))))
23208 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23209 "Move backward to the ARG'th subheading at same level as this one.
23210 Stop at the first and last subheadings of a superior heading."
23211 (interactive "p")
23212 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23214 (defun org-next-visible-heading (arg)
23215 "Move to the next visible heading.
23217 This function wraps `outline-next-visible-heading' with
23218 `org-with-limited-levels' in order to skip over inline tasks and
23219 respect customization of `org-odd-levels-only'."
23220 (interactive "p")
23221 (org-with-limited-levels
23222 (outline-next-visible-heading arg)))
23224 (defun org-previous-visible-heading (arg)
23225 "Move to the previous visible heading.
23227 This function wraps `outline-previous-visible-heading' with
23228 `org-with-limited-levels' in order to skip over inline tasks and
23229 respect customization of `org-odd-levels-only'."
23230 (interactive "p")
23231 (org-with-limited-levels
23232 (outline-previous-visible-heading arg)))
23234 (defun org-forward-paragraph ()
23235 "Move forward to beginning of next paragraph or equivalent.
23237 The function moves point to the beginning of the next visible
23238 structural element, which can be a paragraph, a table, a list
23239 item, etc. It also provides some special moves for convenience:
23241 - On an affiliated keyword, jump to the beginning of the
23242 relative element.
23243 - On an item or a footnote definition, move to the second
23244 element inside, if any.
23245 - On a table or a property drawer, jump after it.
23246 - On a verse or source block, stop after blank lines."
23247 (interactive)
23248 (unless (eobp)
23249 (let* ((deactivate-mark nil)
23250 (element (org-element-at-point))
23251 (type (org-element-type element))
23252 (post-affiliated (org-element-property :post-affiliated element))
23253 (contents-begin (org-element-property :contents-begin element))
23254 (contents-end (org-element-property :contents-end element))
23255 (end (let ((end (org-element-property :end element)) (parent element))
23256 (while (and (setq parent (org-element-property :parent parent))
23257 (= (org-element-property :contents-end parent) end))
23258 (setq end (org-element-property :end parent)))
23259 end)))
23260 (cond ((not element)
23261 (skip-chars-forward " \r\t\n")
23262 (or (eobp) (beginning-of-line)))
23263 ;; On affiliated keywords, move to element's beginning.
23264 ((< (point) post-affiliated)
23265 (goto-char post-affiliated))
23266 ;; At a table row, move to the end of the table. Similarly,
23267 ;; at a node property, move to the end of the property
23268 ;; drawer.
23269 ((memq type '(node-property table-row))
23270 (goto-char (org-element-property
23271 :end (org-element-property :parent element))))
23272 ((memq type '(property-drawer table)) (goto-char end))
23273 ;; Consider blank lines as separators in verse and source
23274 ;; blocks to ease editing.
23275 ((memq type '(src-block verse-block))
23276 (when (eq type 'src-block)
23277 (setq contents-end
23278 (save-excursion (goto-char end)
23279 (skip-chars-backward " \r\t\n")
23280 (line-beginning-position))))
23281 (beginning-of-line)
23282 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23283 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23284 (goto-char end)
23285 (skip-chars-forward " \r\t\n")
23286 (if (= (point) contents-end) (goto-char end)
23287 (beginning-of-line))))
23288 ;; With no contents, just skip element.
23289 ((not contents-begin) (goto-char end))
23290 ;; If contents are invisible, skip the element altogether.
23291 ((org-invisible-p (line-end-position))
23292 (cl-case type
23293 (headline
23294 (org-with-limited-levels (outline-next-visible-heading 1)))
23295 ;; At a plain list, make sure we move to the next item
23296 ;; instead of skipping the whole list.
23297 (plain-list (forward-char)
23298 (org-forward-paragraph))
23299 (otherwise (goto-char end))))
23300 ((>= (point) contents-end) (goto-char end))
23301 ((>= (point) contents-begin)
23302 ;; This can only happen on paragraphs and plain lists.
23303 (cl-case type
23304 (paragraph (goto-char end))
23305 ;; At a plain list, try to move to second element in
23306 ;; first item, if possible.
23307 (plain-list (end-of-line)
23308 (org-forward-paragraph))))
23309 ;; When contents start on the middle of a line (e.g. in
23310 ;; items and footnote definitions), try to reach first
23311 ;; element starting after current line.
23312 ((> (line-end-position) contents-begin)
23313 (end-of-line)
23314 (org-forward-paragraph))
23315 (t (goto-char contents-begin))))))
23317 (defun org-backward-paragraph ()
23318 "Move backward to start of previous paragraph or equivalent.
23320 The function moves point to the beginning of the current
23321 structural element, which can be a paragraph, a table, a list
23322 item, etc., or to the beginning of the previous visible one if
23323 point is already there. It also provides some special moves for
23324 convenience:
23326 - On an affiliated keyword, jump to the first one.
23327 - On a table or a property drawer, move to its beginning.
23328 - On comment, example, export, src and verse blocks, stop
23329 before blank lines."
23330 (interactive)
23331 (unless (bobp)
23332 (let* ((deactivate-mark nil)
23333 (element (org-element-at-point))
23334 (type (org-element-type element))
23335 (contents-end (org-element-property :contents-end element))
23336 (post-affiliated (org-element-property :post-affiliated element))
23337 (begin (org-element-property :begin element))
23338 (special? ;blocks handled specially
23339 (memq type '(comment-block example-block export-block src-block
23340 verse-block)))
23341 (contents-begin
23342 (if special?
23343 ;; These types have no proper contents. Fake line
23344 ;; below the block opening line as contents beginning.
23345 (save-excursion (goto-char begin) (line-beginning-position 2))
23346 (org-element-property :contents-begin element))))
23347 (cond
23348 ((not element) (goto-char (point-min)))
23349 ((= (point) begin)
23350 (backward-char)
23351 (org-backward-paragraph))
23352 ((<= (point) post-affiliated) (goto-char begin))
23353 ;; Special behavior: on a table or a property drawer, move to
23354 ;; its beginning.
23355 ((memq type '(node-property table-row))
23356 (goto-char (org-element-property
23357 :post-affiliated (org-element-property :parent element))))
23358 (special?
23359 (if (<= (point) contents-begin) (goto-char post-affiliated)
23360 ;; Inside a verse block, see blank lines as paragraph
23361 ;; separators.
23362 (let ((origin (point)))
23363 (skip-chars-backward " \r\t\n" contents-begin)
23364 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23365 (skip-chars-forward " \r\t\n" origin)
23366 (if (= (point) origin) (goto-char contents-begin)
23367 (beginning-of-line))))))
23368 ((eq type 'paragraph) (goto-char contents-begin)
23369 ;; When at first paragraph in an item or a footnote definition,
23370 ;; move directly to beginning of line.
23371 (let ((parent-contents
23372 (org-element-property
23373 :contents-begin (org-element-property :parent element))))
23374 (when (and parent-contents (= parent-contents contents-begin))
23375 (beginning-of-line))))
23376 ;; At the end of a greater element, move to the beginning of
23377 ;; the last element within.
23378 ((and contents-end (>= (point) contents-end))
23379 (goto-char (1- contents-end))
23380 (org-backward-paragraph))
23381 (t (goto-char (or post-affiliated begin))))
23382 ;; Ensure we never leave point invisible.
23383 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23385 (defun org-forward-element ()
23386 "Move forward by one element.
23387 Move to the next element at the same level, when possible."
23388 (interactive)
23389 (cond ((eobp) (user-error "Cannot move further down"))
23390 ((org-with-limited-levels (org-at-heading-p))
23391 (let ((origin (point)))
23392 (goto-char (org-end-of-subtree nil t))
23393 (unless (org-with-limited-levels (org-at-heading-p))
23394 (goto-char origin)
23395 (user-error "Cannot move further down"))))
23397 (let* ((elem (org-element-at-point))
23398 (end (org-element-property :end elem))
23399 (parent (org-element-property :parent elem)))
23400 (cond ((and parent (= (org-element-property :contents-end parent) end))
23401 (goto-char (org-element-property :end parent)))
23402 ((integer-or-marker-p end) (goto-char end))
23403 (t (message "No element at point")))))))
23405 (defun org-backward-element ()
23406 "Move backward by one element.
23407 Move to the previous element at the same level, when possible."
23408 (interactive)
23409 (cond ((bobp) (user-error "Cannot move further up"))
23410 ((org-with-limited-levels (org-at-heading-p))
23411 ;; At a headline, move to the previous one, if any, or stay
23412 ;; here.
23413 (let ((origin (point)))
23414 (org-with-limited-levels (org-backward-heading-same-level 1))
23415 ;; When current headline has no sibling above, move to its
23416 ;; parent.
23417 (when (= (point) origin)
23418 (or (org-with-limited-levels (org-up-heading-safe))
23419 (progn (goto-char origin)
23420 (user-error "Cannot move further up"))))))
23422 (let* ((elem (org-element-at-point))
23423 (beg (org-element-property :begin elem)))
23424 (cond
23425 ;; Move to beginning of current element if point isn't
23426 ;; there already.
23427 ((null beg) (message "No element at point"))
23428 ((/= (point) beg) (goto-char beg))
23429 (t (goto-char beg)
23430 (skip-chars-backward " \r\t\n")
23431 (unless (bobp)
23432 (let ((prev (org-element-at-point)))
23433 (goto-char (org-element-property :begin prev))
23434 (while (and (setq prev (org-element-property :parent prev))
23435 (<= (org-element-property :end prev) beg))
23436 (goto-char (org-element-property :begin prev)))))))))))
23438 (defun org-up-element ()
23439 "Move to upper element."
23440 (interactive)
23441 (if (org-with-limited-levels (org-at-heading-p))
23442 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23443 (let* ((elem (org-element-at-point))
23444 (parent (org-element-property :parent elem)))
23445 (if parent (goto-char (org-element-property :begin parent))
23446 (if (org-with-limited-levels (org-before-first-heading-p))
23447 (user-error "No surrounding element")
23448 (org-with-limited-levels (org-back-to-heading)))))))
23450 (defun org-down-element ()
23451 "Move to inner element."
23452 (interactive)
23453 (let ((element (org-element-at-point)))
23454 (cond
23455 ((memq (org-element-type element) '(plain-list table))
23456 (goto-char (org-element-property :contents-begin element))
23457 (forward-char))
23458 ((memq (org-element-type element) org-element-greater-elements)
23459 ;; If contents are hidden, first disclose them.
23460 (when (org-invisible-p (line-end-position)) (org-cycle))
23461 (goto-char (or (org-element-property :contents-begin element)
23462 (user-error "No content for this element"))))
23463 (t (user-error "No inner element")))))
23465 (defun org-drag-element-backward ()
23466 "Move backward element at point."
23467 (interactive)
23468 (let ((elem (or (org-element-at-point)
23469 (user-error "No element at point"))))
23470 (if (eq (org-element-type elem) 'headline)
23471 ;; Preserve point when moving a whole tree, even if point was
23472 ;; on blank lines below the headline.
23473 (let ((offset (skip-chars-backward " \t\n")))
23474 (unwind-protect (org-move-subtree-up)
23475 (forward-char (- offset))))
23476 (let ((prev-elem
23477 (save-excursion
23478 (goto-char (org-element-property :begin elem))
23479 (skip-chars-backward " \r\t\n")
23480 (unless (bobp)
23481 (let* ((beg (org-element-property :begin elem))
23482 (prev (org-element-at-point))
23483 (up prev))
23484 (while (and (setq up (org-element-property :parent up))
23485 (<= (org-element-property :end up) beg))
23486 (setq prev up))
23487 prev)))))
23488 ;; Error out if no previous element or previous element is
23489 ;; a parent of the current one.
23490 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23491 (user-error "Cannot drag element backward")
23492 (let ((pos (point)))
23493 (org-element-swap-A-B prev-elem elem)
23494 (goto-char (+ (org-element-property :begin prev-elem)
23495 (- pos (org-element-property :begin elem))))))))))
23497 (defun org-drag-element-forward ()
23498 "Move forward element at point."
23499 (interactive)
23500 (let* ((pos (point))
23501 (elem (or (org-element-at-point)
23502 (user-error "No element at point"))))
23503 (when (= (point-max) (org-element-property :end elem))
23504 (user-error "Cannot drag element forward"))
23505 (goto-char (org-element-property :end elem))
23506 (let ((next-elem (org-element-at-point)))
23507 (when (or (org-element-nested-p elem next-elem)
23508 (and (eq (org-element-type next-elem) 'headline)
23509 (not (eq (org-element-type elem) 'headline))))
23510 (goto-char pos)
23511 (user-error "Cannot drag element forward"))
23512 ;; Compute new position of point: it's shifted by NEXT-ELEM
23513 ;; body's length (without final blanks) and by the length of
23514 ;; blanks between ELEM and NEXT-ELEM.
23515 (let ((size-next (- (save-excursion
23516 (goto-char (org-element-property :end next-elem))
23517 (skip-chars-backward " \r\t\n")
23518 (forward-line)
23519 ;; Small correction if buffer doesn't end
23520 ;; with a newline character.
23521 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23522 (org-element-property :begin next-elem)))
23523 (size-blank (- (org-element-property :end elem)
23524 (save-excursion
23525 (goto-char (org-element-property :end elem))
23526 (skip-chars-backward " \r\t\n")
23527 (forward-line)
23528 (point)))))
23529 (org-element-swap-A-B elem next-elem)
23530 (goto-char (+ pos size-next size-blank))))))
23532 (defun org-drag-line-forward (arg)
23533 "Drag the line at point ARG lines forward."
23534 (interactive "p")
23535 (dotimes (_ (abs arg))
23536 (let ((c (current-column)))
23537 (if (< 0 arg)
23538 (progn
23539 (beginning-of-line 2)
23540 (transpose-lines 1)
23541 (beginning-of-line 0))
23542 (transpose-lines 1)
23543 (beginning-of-line -1))
23544 (org-move-to-column c))))
23546 (defun org-drag-line-backward (arg)
23547 "Drag the line at point ARG lines backward."
23548 (interactive "p")
23549 (org-drag-line-forward (- arg)))
23551 (defun org-mark-element ()
23552 "Put point at beginning of this element, mark at end.
23554 Interactively, if this command is repeated or (in Transient Mark
23555 mode) if the mark is active, it marks the next element after the
23556 ones already marked."
23557 (interactive)
23558 (let (deactivate-mark)
23559 (if (and (called-interactively-p 'any)
23560 (or (and (eq last-command this-command) (mark t))
23561 (and transient-mark-mode mark-active)))
23562 (set-mark
23563 (save-excursion
23564 (goto-char (mark))
23565 (goto-char (org-element-property :end (org-element-at-point)))))
23566 (let ((element (org-element-at-point)))
23567 (end-of-line)
23568 (push-mark (org-element-property :end element) t t)
23569 (goto-char (org-element-property :begin element))))))
23571 (defun org-narrow-to-element ()
23572 "Narrow buffer to current element."
23573 (interactive)
23574 (let ((elem (org-element-at-point)))
23575 (cond
23576 ((eq (car elem) 'headline)
23577 (narrow-to-region
23578 (org-element-property :begin elem)
23579 (org-element-property :end elem)))
23580 ((memq (car elem) org-element-greater-elements)
23581 (narrow-to-region
23582 (org-element-property :contents-begin elem)
23583 (org-element-property :contents-end elem)))
23585 (narrow-to-region
23586 (org-element-property :begin elem)
23587 (org-element-property :end elem))))))
23589 (defun org-transpose-element ()
23590 "Transpose current and previous elements, keeping blank lines between.
23591 Point is moved after both elements."
23592 (interactive)
23593 (org-skip-whitespace)
23594 (let ((end (org-element-property :end (org-element-at-point))))
23595 (org-drag-element-backward)
23596 (goto-char end)))
23598 (defun org-unindent-buffer ()
23599 "Un-indent the visible part of the buffer.
23600 Relative indentation (between items, inside blocks, etc.) isn't
23601 modified."
23602 (interactive)
23603 (unless (eq major-mode 'org-mode)
23604 (user-error "Cannot un-indent a buffer not in Org mode"))
23605 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23606 (unindent-tree
23607 (lambda (contents)
23608 (dolist (element (reverse contents))
23609 (if (memq (org-element-type element) '(headline section))
23610 (funcall unindent-tree (org-element-contents element))
23611 (save-excursion
23612 (save-restriction
23613 (narrow-to-region
23614 (org-element-property :begin element)
23615 (org-element-property :end element))
23616 (org-do-remove-indentation))))))))
23617 (funcall unindent-tree (org-element-contents parse-tree))))
23619 (defun org-make-options-regexp (kwds &optional extra)
23620 "Make a regular expression for keyword lines.
23621 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23622 when non-nil, is a regexp matching keywords names."
23623 (concat "^[ \t]*#\\+\\("
23624 (regexp-opt kwds)
23625 (and extra (concat (and kwds "\\|") extra))
23626 "\\):[ \t]*\\(.*\\)"))
23629 ;;; Finish up
23631 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23632 (lambda () (add-hook 'change-major-mode-hook
23633 'org-show-all 'append 'local)))
23635 (provide 'org)
23637 (run-hooks 'org-load-hook)
23639 ;;; org.el ends here