Move `org-flag-region' to "org-macs.el"
[org-mode/org-tableheadings.git] / lisp / org.el
blob672f85cd177759d3d7e6c243b20283ce2f97a3c4
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
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; https://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; https://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (defvar org-inlinetask-min-level)
71 ;;;; Require other packages
73 (require 'cl-lib)
75 (eval-when-compile (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (or (eq this-command 'eval-buffer)
82 (condition-case nil
83 (load (concat (file-name-directory load-file-name)
84 "org-loaddefs.el")
85 nil t t t)
86 (error
87 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
88 (sit-for 3)
89 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
90 (sit-for 3))))
92 (require 'org-macs)
93 (require 'org-compat)
95 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
96 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 (defvar org-outline-regexp "\\*+ "
98 "Regexp to match Org headlines.")
100 (defvar org-outline-regexp-bol "^\\*+ "
101 "Regexp to match Org headlines.
102 This is similar to `org-outline-regexp' but additionally makes
103 sure that we are at the beginning of the line.")
105 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
106 "Matches a headline, putting stars and text into groups.
107 Stars are put in group 1 and the trimmed body in group 2.")
109 (declare-function calendar-check-holidays "holidays" (date))
110 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
111 (declare-function cdlatex-math-symbol "ext:cdlatex")
112 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
113 (declare-function org-add-archive-files "org-archive" (files))
114 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
115 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
116 (declare-function org-agenda-redo "org-agenda" (&optional all))
117 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
118 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
119 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
122 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
123 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
126 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
127 (declare-function org-clock-update-time-maybe "org-clock" ())
128 (declare-function org-clocking-buffer "org-clock" ())
129 (declare-function org-clocktable-shift "org-clock" (dir n))
130 (declare-function
131 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-link-parser "org-element" ())
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-recalculate "org-table" (&optional all noalign))
171 (declare-function
172 org-table-sort-lines "org-table"
173 (&optional with-case sorting-type getkey-func compare-func interactive?))
174 (declare-function org-table-shrink "org-table" (&optional begin end))
175 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
180 (declare-function org-export-get-backend "ox" (name))
181 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
182 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
184 (defvar ffap-url-regexp)
185 (defvar org-element-paragraph-separate)
187 ;; load languages based on value of `org-babel-load-languages'
188 (defvar org-babel-load-languages)
190 ;;;###autoload
191 (defun org-babel-do-load-languages (sym value)
192 "Load the languages defined in `org-babel-load-languages'."
193 (set-default sym value)
194 (dolist (pair org-babel-load-languages)
195 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
196 (if active
197 (require (intern (concat "ob-" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-execute:" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-expand-body:" lang)))))))
203 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
204 ;;;###autoload
205 (defun org-babel-load-file (file &optional compile)
206 "Load Emacs Lisp source code blocks in the Org FILE.
207 This function exports the source code using `org-babel-tangle'
208 and then loads the resulting file using `load-file'. With prefix
209 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
210 file to byte-code before it is loaded."
211 (interactive "fFile to load: \nP")
212 (let* ((age (lambda (file)
213 (float-time
214 (time-subtract (current-time)
215 (nth 5 (or (file-attributes (file-truename file))
216 (file-attributes file)))))))
217 (base-name (file-name-sans-extension file))
218 (exported-file (concat base-name ".el")))
219 ;; tangle if the Org file is newer than the elisp file
220 (unless (and (file-exists-p exported-file)
221 (> (funcall age file) (funcall age exported-file)))
222 ;; Tangle-file traversal returns reversed list of tangled files
223 ;; and we want to evaluate the first target.
224 (setq exported-file
225 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
226 (message "%s %s"
227 (if compile
228 (progn (byte-compile-file exported-file 'load)
229 "Compiled and loaded")
230 (progn (load-file exported-file) "Loaded"))
231 exported-file)))
233 (defcustom org-babel-load-languages '((emacs-lisp . t))
234 "Languages which can be evaluated in Org buffers.
235 This list can be used to load support for any of the languages
236 below, note that each language will depend on a different set of
237 system executables and/or Emacs modes. When a language is
238 \"loaded\", then code blocks in that language can be evaluated
239 with `org-babel-execute-src-block' bound by default to C-c
240 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
241 be set to remove code block evaluation from the C-c C-c
242 keybinding. By default only Emacs Lisp (which has no
243 requirements) is loaded."
244 :group 'org-babel
245 :set 'org-babel-do-load-languages
246 :version "24.1"
247 :type '(alist :tag "Babel Languages"
248 :key-type
249 (choice
250 (const :tag "Awk" awk)
251 (const :tag "C" C)
252 (const :tag "R" R)
253 (const :tag "Asymptote" asymptote)
254 (const :tag "Calc" calc)
255 (const :tag "Clojure" clojure)
256 (const :tag "CSS" css)
257 (const :tag "Ditaa" ditaa)
258 (const :tag "Dot" dot)
259 (const :tag "Ebnf2ps" ebnf2ps)
260 (const :tag "Emacs Lisp" emacs-lisp)
261 (const :tag "Forth" forth)
262 (const :tag "Fortran" fortran)
263 (const :tag "Gnuplot" gnuplot)
264 (const :tag "Haskell" haskell)
265 (const :tag "hledger" hledger)
266 (const :tag "IO" io)
267 (const :tag "J" J)
268 (const :tag "Java" java)
269 (const :tag "Javascript" js)
270 (const :tag "LaTeX" latex)
271 (const :tag "Ledger" ledger)
272 (const :tag "Lilypond" lilypond)
273 (const :tag "Lisp" lisp)
274 (const :tag "Makefile" makefile)
275 (const :tag "Maxima" maxima)
276 (const :tag "Matlab" matlab)
277 (const :tag "Mscgen" mscgen)
278 (const :tag "Ocaml" ocaml)
279 (const :tag "Octave" octave)
280 (const :tag "Org" org)
281 (const :tag "Perl" perl)
282 (const :tag "Pico Lisp" picolisp)
283 (const :tag "PlantUML" plantuml)
284 (const :tag "Python" python)
285 (const :tag "Ruby" ruby)
286 (const :tag "Sass" sass)
287 (const :tag "Scala" scala)
288 (const :tag "Scheme" scheme)
289 (const :tag "Screen" screen)
290 (const :tag "Shell Script" shell)
291 (const :tag "Shen" shen)
292 (const :tag "Sql" sql)
293 (const :tag "Sqlite" sqlite)
294 (const :tag "Stan" stan)
295 (const :tag "Vala" vala))
296 :value-type (boolean :tag "Activate" :value t)))
298 ;;;; Customization variables
299 (defcustom org-clone-delete-id nil
300 "Remove ID property of clones of a subtree.
301 When non-nil, clones of a subtree don't inherit the ID property.
302 Otherwise they inherit the ID property with a new unique
303 identifier."
304 :type 'boolean
305 :version "24.1"
306 :group 'org-id)
308 ;;; Version
309 (org-check-version)
311 ;;;###autoload
312 (defun org-version (&optional here full message)
313 "Show the Org version.
314 Interactively, or when MESSAGE is non-nil, show it in echo area.
315 With prefix argument, or when HERE is non-nil, insert it at point.
316 In non-interactive uses, a reduced version string is output unless
317 FULL is given."
318 (interactive (list current-prefix-arg t (not current-prefix-arg)))
319 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
320 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
321 (load-suffixes (list ".el"))
322 (org-install-dir
323 (ignore-errors (org-find-library-dir "org-loaddefs"))))
324 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
325 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
326 (let* ((load-suffixes save-load-suffixes)
327 (release (org-release))
328 (git-version (org-git-version))
329 (version (format "Org mode version %s (%s @ %s)"
330 release
331 git-version
332 (if org-install-dir
333 (if (string= org-dir org-install-dir)
334 org-install-dir
335 (concat "mixed installation! "
336 org-install-dir
337 " and "
338 org-dir))
339 "org-loaddefs.el can not be found!")))
340 (version1 (if full version release)))
341 (when here (insert version1))
342 (when message (message "%s" version1))
343 version1)))
345 (defconst org-version (org-version))
348 ;;; Syntax Constants
350 ;;;; Block
352 (defconst org-block-regexp
353 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
354 "Regular expression for hiding blocks.")
356 (defconst org-dblock-start-re
357 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
358 "Matches the start line of a dynamic block, with parameters.")
360 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
361 "Matches the end of a dynamic block.")
363 ;;;; Clock and Planning
365 (defconst org-clock-string "CLOCK:"
366 "String used as prefix for timestamps clocking work hours on an item.")
368 (defvar org-closed-string "CLOSED:"
369 "String used as the prefix for timestamps logging closing a TODO entry.")
371 (defvar org-deadline-string "DEADLINE:"
372 "String to mark deadline entries.
373 \\<org-mode-map>
374 A deadline is this string, followed by a time stamp. It must be
375 a word, terminated by a colon. You can insert a schedule keyword
376 and a timestamp with `\\[org-deadline]'.")
378 (defvar org-scheduled-string "SCHEDULED:"
379 "String to mark scheduled TODO entries.
380 \\<org-mode-map>
381 A schedule is this string, followed by a time stamp. It must be
382 a word, terminated by a colon. You can insert a schedule keyword
383 and a timestamp with `\\[org-schedule]'.")
385 (defconst org-ds-keyword-length
386 (+ 2
387 (apply #'max
388 (mapcar #'length
389 (list org-deadline-string org-scheduled-string
390 org-clock-string org-closed-string))))
391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
393 (defconst org-planning-line-re
394 (concat "^[ \t]*"
395 (regexp-opt
396 (list org-closed-string org-deadline-string org-scheduled-string)
398 "Matches a line with planning info.
399 Matched keyword is in group 1.")
401 (defconst org-clock-line-re
402 (concat "^[ \t]*" org-clock-string)
403 "Matches a line with clock info.")
405 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
406 "Matches the DEADLINE keyword.")
408 (defconst org-deadline-time-regexp
409 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
410 "Matches the DEADLINE keyword together with a time stamp.")
412 (defconst org-deadline-time-hour-regexp
413 (concat "\\<" org-deadline-string
414 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
415 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
417 (defconst org-deadline-line-regexp
418 (concat "\\<\\(" org-deadline-string "\\).*")
419 "Matches the DEADLINE keyword and the rest of the line.")
421 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
422 "Matches the SCHEDULED keyword.")
424 (defconst org-scheduled-time-regexp
425 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
426 "Matches the SCHEDULED keyword together with a time stamp.")
428 (defconst org-scheduled-time-hour-regexp
429 (concat "\\<" org-scheduled-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
433 (defconst org-closed-time-regexp
434 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
435 "Matches the CLOSED keyword together with a time stamp.")
437 (defconst org-keyword-time-regexp
438 (concat "\\<"
439 (regexp-opt
440 (list org-scheduled-string org-deadline-string org-closed-string
441 org-clock-string)
443 " *[[<]\\([^]>]+\\)[]>]")
444 "Matches any of the 4 keywords, together with the time stamp.")
446 (defconst org-keyword-time-not-clock-regexp
447 (concat
448 "\\<"
449 (regexp-opt
450 (list org-scheduled-string org-deadline-string org-closed-string) t)
451 " *[[<]\\([^]>]+\\)[]>]")
452 "Matches any of the 3 keywords, together with the time stamp.")
454 (defconst org-maybe-keyword-time-regexp
455 (concat "\\(\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string
458 org-clock-string)
460 "\\)?"
461 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
462 "\\|"
463 "<%%([^\r\n>]*>\\)")
464 "Matches a timestamp, possibly preceded by a keyword.")
466 (defconst org-all-time-keywords
467 (mapcar (lambda (w) (substring w 0 -1))
468 (list org-scheduled-string org-deadline-string
469 org-clock-string org-closed-string))
470 "List of time keywords.")
472 ;;;; Drawer
474 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
475 "Matches first or last line of a hidden block.
476 Group 1 contains drawer's name or \"END\".")
478 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
479 "Regular expression matching the first line of a property drawer.")
481 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a property drawer.")
484 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
485 "Regular expression matching the first line of a clock drawer.")
487 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a clock drawer.")
490 (defconst org-property-drawer-re
491 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
492 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
493 "[ \t]*:END:[ \t]*$")
494 "Matches an entire property drawer.")
496 (defconst org-clock-drawer-re
497 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
498 org-clock-drawer-end-re "\\)\n?")
499 "Matches an entire clock drawer.")
501 ;;;; Headline
503 (defconst org-heading-keyword-regexp-format
504 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
505 "Printf format for a regexp matching a headline with some keyword.
506 This regexp will match the headline of any node which has the
507 exact keyword that is put into the format. The keyword isn't in
508 any group by default, but the stars and the body are.")
510 (defconst org-heading-keyword-maybe-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline, possibly with some keyword.
513 This regexp can match any headline with the specified keyword, or
514 without a keyword. The keyword isn't in any group by default,
515 but the stars and the body are.")
517 (defconst org-archive-tag "ARCHIVE"
518 "The tag that marks a subtree as archived.
519 An archived subtree does not open during visibility cycling, and does
520 not contribute to the agenda listings.")
522 (eval-and-compile
523 (defconst org-comment-string "COMMENT"
524 "Entries starting with this keyword will never be exported.
525 \\<org-mode-map>
526 An entry can be toggled between COMMENT and normal with
527 `\\[org-toggle-comment]'."))
530 ;;;; LaTeX Environments and Fragments
532 (defconst org-latex-regexps
533 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
534 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
535 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
536 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
537 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
538 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
539 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
540 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
541 "Regular expressions for matching embedded LaTeX.")
543 ;;;; Node Property
545 (defconst org-effort-property "Effort"
546 "The property that is being used to keep track of effort estimates.
547 Effort estimates given in this property need to have the format H:MM.")
549 ;;;; Table
551 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
552 "Detect an org-type or table-type table.")
554 (defconst org-table-line-regexp "^[ \t]*|"
555 "Detect an org-type table line.")
557 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
558 "Detect an org-type table line.")
560 (defconst org-table-hline-regexp "^[ \t]*|-"
561 "Detect an org-type table hline.")
563 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
564 "Detect a table-type table hline.")
566 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
567 "Detect the first line outside a table when searching from within it.
568 This works for both table types.")
570 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
571 "Detect a #+TBLFM line.")
573 ;;;; Timestamp
575 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
576 "Regular expression for fast time stamp matching.")
578 (defconst org-ts-regexp-inactive
579 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
580 "Regular expression for fast inactive time stamp matching.")
582 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
583 "Regular expression for fast time stamp matching.")
585 (defconst org-ts-regexp0
586 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
587 "Regular expression matching time strings for analysis.
588 This one does not require the space after the date, so it can be used
589 on a string that terminates immediately after the date.")
591 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.")
594 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
595 "Regular expression matching time stamps, with groups.")
597 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
598 "Regular expression matching time stamps (also [..]), with groups.")
600 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
601 "Regular expression matching a time stamp range.")
603 (defconst org-tr-regexp-both
604 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
608 org-ts-regexp "\\)?")
609 "Regular expression matching a time stamp or time stamp range.")
611 (defconst org-tsr-regexp-both
612 (concat org-ts-regexp-both "\\(--?-?"
613 org-ts-regexp-both "\\)?")
614 "Regular expression matching a time stamp or time stamp range.
615 The time stamps may be either active or inactive.")
617 (defconst org-repeat-re
618 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
619 "Regular expression for specifying repeated events.
620 After a match, group 1 contains the repeat expression.")
622 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
623 "Formats for `format-time-string' which are used for time stamps.")
626 ;;; The custom variables
628 (defgroup org nil
629 "Outline-based notes management and organizer."
630 :tag "Org"
631 :group 'outlines
632 :group 'calendar)
634 (defcustom org-mode-hook nil
635 "Mode hook for Org mode, run after the mode was turned on."
636 :group 'org
637 :type 'hook)
639 (defcustom org-load-hook nil
640 "Hook that is run after org.el has been loaded."
641 :group 'org
642 :type 'hook)
644 (defcustom org-log-buffer-setup-hook nil
645 "Hook that is run after an Org log buffer is created."
646 :group 'org
647 :version "24.1"
648 :type 'hook)
650 (defvar org-modules) ; defined below
651 (defvar org-modules-loaded nil
652 "Have the modules been loaded already?")
654 (defun org-load-modules-maybe (&optional force)
655 "Load all extensions listed in `org-modules'."
656 (when (or force (not org-modules-loaded))
657 (dolist (ext org-modules)
658 (condition-case nil (require ext)
659 (error (message "Problems while trying to load feature `%s'" ext))))
660 (setq org-modules-loaded t)))
662 (defun org-set-modules (var value)
663 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
664 (set var value)
665 (when (featurep 'org)
666 (org-load-modules-maybe 'force)
667 (org-element-cache-reset 'all)))
669 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
670 "Modules that should always be loaded together with org.el.
672 If a description starts with <C>, the file is not part of Emacs
673 and loading it will require that you have downloaded and properly
674 installed the Org mode distribution.
676 You can also use this system to load external packages (i.e. neither Org
677 core modules, nor modules from the CONTRIB directory). Just add symbols
678 to the end of the list. If the package is called org-xyz.el, then you need
679 to add the symbol `xyz', and the package must have a call to:
681 (provide \\='org-xyz)
683 For export specific modules, see also `org-export-backends'."
684 :group 'org
685 :set 'org-set-modules
686 :version "24.4"
687 :package-version '(Org . "8.0")
688 :type
689 '(set :greedy t
690 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
691 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
692 (const :tag " crypt: Encryption of subtrees" org-crypt)
693 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
694 (const :tag " docview: Links to doc-view buffers" org-docview)
695 (const :tag " eww: Store link to url of eww" org-eww)
696 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
697 (const :tag " habit: Track your consistency with habits" org-habit)
698 (const :tag " id: Global IDs for identifying entries" org-id)
699 (const :tag " info: Links to Info nodes" org-info)
700 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
701 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
702 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
703 (const :tag " mouse: Additional mouse support" org-mouse)
704 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
705 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
706 (const :tag " tempo: Fast completion for structures" org-tempo)
707 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
709 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
710 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
711 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
712 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
713 (const :tag "C collector: Collect properties into tables" org-collector)
714 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
715 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
716 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
717 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
718 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
719 (const :tag "C eval: Include command output as text" org-eval)
720 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
721 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
722 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
723 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
724 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
725 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
726 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
727 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
728 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
729 (const :tag "C man: Support for links to manpages in Org mode" org-man)
730 (const :tag "C mew: Links to Mew folders/messages" org-mew)
731 (const :tag "C mtags: Support for muse-like tags" org-mtags)
732 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
733 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
734 (const :tag "C registry: A registry for Org links" org-registry)
735 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
736 (const :tag "C secretary: Team management with Org" org-secretary)
737 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
738 (const :tag "C toc: Table of contents for Org buffer" org-toc)
739 (const :tag "C track: Keep up with Org mode development" org-track)
740 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
741 (const :tag "C vm: Links to VM folders/messages" org-vm)
742 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
743 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
744 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
746 (defvar org-export-registered-backends) ; From ox.el.
747 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
748 (declare-function org-export-backend-name "ox" (backend) t)
749 (defcustom org-export-backends '(ascii html icalendar latex odt)
750 "List of export back-ends that should be always available.
752 If a description starts with <C>, the file is not part of Emacs
753 and loading it will require that you have downloaded and properly
754 installed the Org mode distribution.
756 Unlike to `org-modules', libraries in this list will not be
757 loaded along with Org, but only once the export framework is
758 needed.
760 This variable needs to be set before org.el is loaded. If you
761 need to make a change while Emacs is running, use the customize
762 interface or run the following code, where VAL stands for the new
763 value of the variable, after updating it:
765 (progn
766 (setq org-export-registered-backends
767 (cl-remove-if-not
768 (lambda (backend)
769 (let ((name (org-export-backend-name backend)))
770 (or (memq name val)
771 (catch \\='parentp
772 (dolist (b val)
773 (and (org-export-derived-backend-p b name)
774 (throw \\='parentp t)))))))
775 org-export-registered-backends))
776 (let ((new-list (mapcar #\\='org-export-backend-name
777 org-export-registered-backends)))
778 (dolist (backend val)
779 (cond
780 ((not (load (format \"ox-%s\" backend) t t))
781 (message \"Problems while trying to load export back-end \\=`%s\\='\"
782 backend))
783 ((not (memq backend new-list)) (push backend new-list))))
784 (set-default \\='org-export-backends new-list)))
786 Adding a back-end to this list will also pull the back-end it
787 depends on, if any."
788 :group 'org
789 :group 'org-export
790 :version "26.1"
791 :package-version '(Org . "9.0")
792 :initialize 'custom-initialize-set
793 :set (lambda (var val)
794 (if (not (featurep 'ox)) (set-default var val)
795 ;; Any back-end not required anymore (not present in VAL and not
796 ;; a parent of any back-end in the new value) is removed from the
797 ;; list of registered back-ends.
798 (setq org-export-registered-backends
799 (cl-remove-if-not
800 (lambda (backend)
801 (let ((name (org-export-backend-name backend)))
802 (or (memq name val)
803 (catch 'parentp
804 (dolist (b val)
805 (and (org-export-derived-backend-p b name)
806 (throw 'parentp t)))))))
807 org-export-registered-backends))
808 ;; Now build NEW-LIST of both new back-ends and required
809 ;; parents.
810 (let ((new-list (mapcar #'org-export-backend-name
811 org-export-registered-backends)))
812 (dolist (backend val)
813 (cond
814 ((not (load (format "ox-%s" backend) t t))
815 (message "Problems while trying to load export back-end `%s'"
816 backend))
817 ((not (memq backend new-list)) (push backend new-list))))
818 ;; Set VAR to that list with fixed dependencies.
819 (set-default var new-list))))
820 :type '(set :greedy t
821 (const :tag " ascii Export buffer to ASCII format" ascii)
822 (const :tag " beamer Export buffer to Beamer presentation" beamer)
823 (const :tag " html Export buffer to HTML format" html)
824 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
825 (const :tag " latex Export buffer to LaTeX format" latex)
826 (const :tag " man Export buffer to MAN format" man)
827 (const :tag " md Export buffer to Markdown format" md)
828 (const :tag " odt Export buffer to ODT format" odt)
829 (const :tag " org Export buffer to Org format" org)
830 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
831 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
832 (const :tag "C deck Export buffer to deck.js presentations" deck)
833 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
834 (const :tag "C groff Export buffer to Groff format" groff)
835 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
836 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
837 (const :tag "C s5 Export buffer to s5 presentations" s5)
838 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
840 (eval-after-load 'ox
841 '(dolist (backend org-export-backends)
842 (condition-case nil (require (intern (format "ox-%s" backend)))
843 (error (message "Problems while trying to load export back-end `%s'"
844 backend)))))
846 (defcustom org-support-shift-select nil
847 "Non-nil means make shift-cursor commands select text when possible.
848 \\<org-mode-map>\
850 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
851 start selecting a region, or enlarge regions started in this way.
852 In Org mode, in special contexts, these same keys are used for
853 other purposes, important enough to compete with shift selection.
854 Org tries to balance these needs by supporting `shift-select-mode'
855 outside these special contexts, under control of this variable.
857 The default of this variable is nil, to avoid confusing behavior. Shifted
858 cursor keys will then execute Org commands in the following contexts:
859 - on a headline, changing TODO state (left/right) and priority (up/down)
860 - on a time stamp, changing the time
861 - in a plain list item, changing the bullet type
862 - in a property definition line, switching between allowed values
863 - in the BEGIN line of a clock table (changing the time block).
864 Outside these contexts, the commands will throw an error.
866 When this variable is t and the cursor is not in a special
867 context, Org mode will support shift-selection for making and
868 enlarging regions. To make this more effective, the bullet
869 cycling will no longer happen anywhere in an item line, but only
870 if the cursor is exactly on the bullet.
872 If you set this variable to the symbol `always', then the keys
873 will not be special in headlines, property lines, and item lines,
874 to make shift selection work there as well. If this is what you
875 want, you can use the following alternative commands:
876 `\\[org-todo]' and `\\[org-priority]' \
877 to change TODO state and priority,
878 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
879 can be used to switch TODO sets,
880 `\\[org-ctrl-c-minus]' to cycle item bullet types,
881 and properties can be edited by hand or in column view.
883 However, when the cursor is on a timestamp, shift-cursor commands
884 will still edit the time stamp - this is just too good to give up."
885 :group 'org
886 :type '(choice
887 (const :tag "Never" nil)
888 (const :tag "When outside special context" t)
889 (const :tag "Everywhere except timestamps" always)))
891 (defcustom org-loop-over-headlines-in-active-region nil
892 "Shall some commands act upon headlines in the active region?
894 When set to t, some commands will be performed in all headlines
895 within the active region.
897 When set to `start-level', some commands will be performed in all
898 headlines within the active region, provided that these headlines
899 are of the same level than the first one.
901 When set to a string, those commands will be performed on the
902 matching headlines within the active region. Such string must be
903 a tags/property/todo match as it is used in the agenda tags view.
905 The list of commands is: `org-schedule', `org-deadline',
906 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
907 `org-archive-to-archive-sibling'. The archiving commands skip
908 already archived entries."
909 :type '(choice (const :tag "Don't loop" nil)
910 (const :tag "All headlines in active region" t)
911 (const :tag "In active region, headlines at the same level than the first one" start-level)
912 (string :tag "Tags/Property/Todo matcher"))
913 :version "24.1"
914 :group 'org-todo
915 :group 'org-archive)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org mode will switch to OVERVIEW.
920 This can also be configured on a per-file basis by adding one of
921 the following lines anywhere in the buffer:
923 #+STARTUP: fold (or `overview', this is equivalent)
924 #+STARTUP: nofold (or `showall', this is equivalent)
925 #+STARTUP: content
926 #+STARTUP: showeverything
928 Set `org-agenda-inhibit-startup' to a non-nil value if you want
929 to ignore this option when Org opens agenda files for the first
930 time."
931 :group 'org-startup
932 :type '(choice
933 (const :tag "nofold: show all" nil)
934 (const :tag "fold: overview" t)
935 (const :tag "content: all headlines" content)
936 (const :tag "show everything, even drawers" showeverything)))
938 (defcustom org-startup-truncated t
939 "Non-nil means entering Org mode will set `truncate-lines'.
940 This is useful since some lines containing links can be very long and
941 uninteresting. Also tables look terrible when wrapped.
943 The variable `org-startup-truncated' allows to configure
944 truncation for Org mode different to the other modes that use the
945 variable `truncate-lines' and as a shortcut instead of putting
946 the variable `truncate-lines' into the `org-mode-hook'. If one
947 wants to configure truncation for Org mode not statically but
948 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
949 the variable `truncate-lines' has to be used because in such a
950 case it is too late to set the variable `org-startup-truncated'."
951 :group 'org-startup
952 :type 'boolean)
954 (defcustom org-startup-indented nil
955 "Non-nil means turn on `org-indent-mode' on startup.
956 This can also be configured on a per-file basis by adding one of
957 the following lines anywhere in the buffer:
959 #+STARTUP: indent
960 #+STARTUP: noindent"
961 :group 'org-structure
962 :type '(choice
963 (const :tag "Not" nil)
964 (const :tag "Globally (slow on startup in large files)" t)))
966 (defcustom org-use-sub-superscripts t
967 "Non-nil means interpret \"_\" and \"^\" for display.
969 If you want to control how Org exports those characters, see
970 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
971 used to be an alias for `org-export-with-sub-superscripts' in
972 Org <8.0, it is not anymore.
974 When this option is turned on, you can use TeX-like syntax for
975 sub- and superscripts within the buffer. Several characters after
976 \"_\" or \"^\" will be considered as a single item - so grouping
977 with {} is normally not needed. For example, the following things
978 will be parsed as single sub- or superscripts:
980 10^24 or 10^tau several digits will be considered 1 item.
981 10^-12 or 10^-tau a leading sign with digits or a word
982 x^2-y^3 will be read as x^2 - y^3, because items are
983 terminated by almost any nonword/nondigit char.
984 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
986 Still, ambiguity is possible. So when in doubt, use {} to enclose
987 the sub/superscript. If you set this variable to the symbol `{}',
988 the braces are *required* in order to trigger interpretations as
989 sub/superscript. This can be helpful in documents that need \"_\"
990 frequently in plain text."
991 :group 'org-startup
992 :version "24.4"
993 :package-version '(Org . "8.0")
994 :type '(choice
995 (const :tag "Always interpret" t)
996 (const :tag "Only with braces" {})
997 (const :tag "Never interpret" nil)))
999 (defcustom org-startup-with-beamer-mode nil
1000 "Non-nil means turn on `org-beamer-mode' on startup.
1001 This can also be configured on a per-file basis by adding one of
1002 the following lines anywhere in the buffer:
1004 #+STARTUP: beamer"
1005 :group 'org-startup
1006 :version "24.1"
1007 :type 'boolean)
1009 (defcustom org-startup-align-all-tables nil
1010 "Non-nil means align all tables when visiting a file.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1013 #+STARTUP: align
1014 #+STARTUP: noalign"
1015 :group 'org-startup
1016 :type 'boolean)
1018 (defcustom org-startup-shrink-all-tables nil
1019 "Non-nil means shrink all table columns with a width cookie.
1020 This can also be configured on a per-file basis by adding one of
1021 the following lines anywhere in the buffer:
1022 #+STARTUP: shrink"
1023 :group 'org-startup
1024 :type 'boolean
1025 :version "27.1"
1026 :package-version '(Org . "9.2")
1027 :safe #'booleanp)
1029 (defcustom org-startup-with-inline-images nil
1030 "Non-nil means show inline images when loading a new Org file.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: inlineimages
1034 #+STARTUP: noinlineimages"
1035 :group 'org-startup
1036 :version "24.1"
1037 :type 'boolean)
1039 (defcustom org-startup-with-latex-preview nil
1040 "Non-nil means preview LaTeX fragments when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: latexpreview
1045 #+STARTUP: nolatexpreview"
1046 :group 'org-startup
1047 :version "24.4"
1048 :package-version '(Org . "8.0")
1049 :type 'boolean)
1051 (defcustom org-insert-mode-line-in-empty-file nil
1052 "Non-nil means insert the first line setting Org mode in empty files.
1053 When the function `org-mode' is called interactively in an empty file, this
1054 normally means that the file name does not automatically trigger Org mode.
1055 To ensure that the file will always be in Org mode in the future, a
1056 line enforcing Org mode will be inserted into the buffer, if this option
1057 has been set."
1058 :group 'org-startup
1059 :type 'boolean)
1061 (defcustom org-replace-disputed-keys nil
1062 "Non-nil means use alternative key bindings for some keys.
1064 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1065 These keys are also used by other packages like Shift Select mode,
1066 CUA mode or Windmove. If you want to use Org mode together with
1067 one of these other modes, or more generally if you would like to
1068 move some Org mode commands to other keys, set this variable and
1069 configure the keys with the variable `org-disputed-keys'.
1071 This option is only relevant at load-time of Org mode, and must be set
1072 *before* org.el is loaded. Changing it requires a restart of Emacs to
1073 become effective."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-use-extra-keys nil
1078 "Non-nil means use extra key sequence definitions for certain commands.
1079 This happens automatically if `window-system' is nil. This
1080 variable lets you do the same manually. You must set it before
1081 loading Org."
1082 :group 'org-startup
1083 :type 'boolean)
1085 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1087 (defcustom org-disputed-keys
1088 '(([(shift up)] . [(meta p)])
1089 ([(shift down)] . [(meta n)])
1090 ([(shift left)] . [(meta -)])
1091 ([(shift right)] . [(meta +)])
1092 ([(control shift right)] . [(meta shift +)])
1093 ([(control shift left)] . [(meta shift -)]))
1094 "Keys for which Org mode and other modes compete.
1095 This is an alist, cars are the default keys, second element specifies
1096 the alternative to use when `org-replace-disputed-keys' is t.
1098 Keys can be specified in any syntax supported by `define-key'.
1099 The value of this option takes effect only at Org mode startup,
1100 therefore you'll have to restart Emacs to apply it after changing."
1101 :group 'org-startup
1102 :type 'alist)
1104 (defun org-key (key)
1105 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1106 Or return the original if not disputed."
1107 (when org-replace-disputed-keys
1108 (let* ((nkey (key-description key))
1109 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 key)
1114 (defun org-defkey (keymap key def)
1115 "Define a key, possibly translated, as returned by `org-key'."
1116 (define-key keymap (org-key key) def))
1118 (defcustom org-ellipsis nil
1119 "The ellipsis to use in the Org mode outline.
1121 When nil, just use the standard three dots. When a non-empty string,
1122 use that string instead.
1124 The change affects only Org mode (which will then use its own display table).
1125 Changing this requires executing `\\[org-mode]' in a buffer to become
1126 effective."
1127 :group 'org-startup
1128 :type '(choice (const :tag "Default" nil)
1129 (string :tag "String" :value "...#"))
1130 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1132 (defvar org-display-table nil
1133 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1135 (defgroup org-keywords nil
1136 "Keywords in Org mode."
1137 :tag "Org Keywords"
1138 :group 'org)
1140 (defcustom org-closed-keep-when-no-todo nil
1141 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1142 :group 'org-todo
1143 :group 'org-keywords
1144 :version "24.4"
1145 :package-version '(Org . "8.0")
1146 :type 'boolean)
1148 (defgroup org-structure nil
1149 "Options concerning the general structure of Org files."
1150 :tag "Org Structure"
1151 :group 'org)
1153 (defgroup org-reveal-location nil
1154 "Options about how to make context of a location visible."
1155 :tag "Org Reveal Location"
1156 :group 'org-structure)
1158 (defcustom org-show-context-detail '((agenda . local)
1159 (bookmark-jump . lineage)
1160 (isearch . lineage)
1161 (default . ancestors))
1162 "Alist between context and visibility span when revealing a location.
1164 \\<org-mode-map>Some actions may move point into invisible
1165 locations. As a consequence, Org always expose a neighborhood
1166 around point. How much is shown depends on the initial action,
1167 or context. Valid contexts are
1169 agenda when exposing an entry from the agenda
1170 org-goto when using the command `org-goto' (`\\[org-goto]')
1171 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1172 tags-tree when constructing a sparse tree based on tags matches
1173 link-search when exposing search matches associated with a link
1174 mark-goto when exposing the jump goal of a mark
1175 bookmark-jump when exposing a bookmark location
1176 isearch when exiting from an incremental search
1177 default default for all contexts not set explicitly
1179 Allowed visibility spans are
1181 minimal show current headline; if point is not on headline,
1182 also show entry
1184 local show current headline, entry and next headline
1186 ancestors show current headline and its direct ancestors; if
1187 point is not on headline, also show entry
1189 lineage show current headline, its direct ancestors and all
1190 their children; if point is not on headline, also show
1191 entry and first child
1193 tree show current headline, its direct ancestors and all
1194 their children; if point is not on headline, also show
1195 entry and all children
1197 canonical show current headline, its direct ancestors along with
1198 their entries and children; if point is not located on
1199 the headline, also show current entry and all children
1201 As special cases, a nil or t value means show all contexts in
1202 `minimal' or `canonical' view, respectively.
1204 Some views can make displayed information very compact, but also
1205 make it harder to edit the location of the match. In such
1206 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1207 more context."
1208 :group 'org-reveal-location
1209 :version "26.1"
1210 :package-version '(Org . "9.0")
1211 :type '(choice
1212 (const :tag "Canonical" t)
1213 (const :tag "Minimal" nil)
1214 (repeat :greedy t :tag "Individual contexts"
1215 (cons
1216 (choice :tag "Context"
1217 (const agenda)
1218 (const org-goto)
1219 (const occur-tree)
1220 (const tags-tree)
1221 (const link-search)
1222 (const mark-goto)
1223 (const bookmark-jump)
1224 (const isearch)
1225 (const default))
1226 (choice :tag "Detail level"
1227 (const minimal)
1228 (const local)
1229 (const ancestors)
1230 (const lineage)
1231 (const tree)
1232 (const canonical))))))
1234 (defcustom org-indirect-buffer-display 'other-window
1235 "How should indirect tree buffers be displayed?
1237 This applies to indirect buffers created with the commands
1238 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1240 Valid values are:
1241 current-window Display in the current window
1242 other-window Just display in another window.
1243 dedicated-frame Create one new frame, and re-use it each time.
1244 new-frame Make a new frame each time. Note that in this case
1245 previously-made indirect buffers are kept, and you need to
1246 kill these buffers yourself."
1247 :group 'org-structure
1248 :group 'org-agenda-windows
1249 :type '(choice
1250 (const :tag "In current window" current-window)
1251 (const :tag "In current frame, other window" other-window)
1252 (const :tag "Each time a new frame" new-frame)
1253 (const :tag "One dedicated frame" dedicated-frame)))
1255 (defcustom org-use-speed-commands nil
1256 "Non-nil means activate single letter commands at beginning of a headline.
1257 This may also be a function to test for appropriate locations where speed
1258 commands should be active.
1260 For example, to activate speed commands when the point is on any
1261 star at the beginning of the headline, you can do this:
1263 (setq org-use-speed-commands
1264 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1265 :group 'org-structure
1266 :type '(choice
1267 (const :tag "Never" nil)
1268 (const :tag "At beginning of headline stars" t)
1269 (function)))
1271 (defcustom org-speed-commands-user nil
1272 "Alist of additional speed commands.
1273 This list will be checked before `org-speed-commands-default'
1274 when the variable `org-use-speed-commands' is non-nil
1275 and when the cursor is at the beginning of a headline.
1276 The car of each entry is a string with a single letter, which must
1277 be assigned to `self-insert-command' in the global map.
1278 The cdr is either a command to be called interactively, a function
1279 to be called, or a form to be evaluated.
1280 An entry that is just a list with a single string will be interpreted
1281 as a descriptive headline that will be added when listing the speed
1282 commands in the Help buffer using the `?' speed command."
1283 :group 'org-structure
1284 :type '(repeat :value ("k" . ignore)
1285 (choice :value ("k" . ignore)
1286 (list :tag "Descriptive Headline" (string :tag "Headline"))
1287 (cons :tag "Letter and Command"
1288 (string :tag "Command letter")
1289 (choice
1290 (function)
1291 (sexp))))))
1293 (defcustom org-bookmark-names-plist
1294 '(:last-capture "org-capture-last-stored"
1295 :last-refile "org-refile-last-stored"
1296 :last-capture-marker "org-capture-last-stored-marker")
1297 "Names for bookmarks automatically set by some Org commands.
1298 This can provide strings as names for a number of bookmarks Org sets
1299 automatically. The following keys are currently implemented:
1300 :last-capture
1301 :last-capture-marker
1302 :last-refile
1303 When a key does not show up in the property list, the corresponding bookmark
1304 is not set."
1305 :group 'org-structure
1306 :type 'plist)
1308 (defgroup org-cycle nil
1309 "Options concerning visibility cycling in Org mode."
1310 :tag "Org Cycle"
1311 :group 'org-structure)
1313 (defcustom org-cycle-skip-children-state-if-no-children t
1314 "Non-nil means skip CHILDREN state in entries that don't have any."
1315 :group 'org-cycle
1316 :type 'boolean)
1318 (defcustom org-cycle-max-level nil
1319 "Maximum level which should still be subject to visibility cycling.
1320 Levels higher than this will, for cycling, be treated as text, not a headline.
1321 When `org-odd-levels-only' is set, a value of N in this variable actually
1322 means 2N-1 stars as the limiting headline.
1323 When nil, cycle all levels.
1324 Note that the limiting level of cycling is also influenced by
1325 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1326 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1327 than its value."
1328 :group 'org-cycle
1329 :type '(choice
1330 (const :tag "No limit" nil)
1331 (integer :tag "Maximum level")))
1333 (defcustom org-hide-block-startup nil
1334 "Non-nil means entering Org mode will fold all blocks.
1335 This can also be set in on a per-file basis with
1337 #+STARTUP: hideblocks
1338 #+STARTUP: showblocks"
1339 :group 'org-startup
1340 :group 'org-cycle
1341 :type 'boolean)
1343 (defcustom org-cycle-global-at-bob nil
1344 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1346 This makes it possible to do global cycling without having to use `S-TAB'
1347 or `\\[universal-argument] TAB'. For this special case to work, the first \
1348 line of the buffer
1349 must not be a headline -- it may be empty or some other text.
1351 When used in this way, `org-cycle-hook' is disabled temporarily to make
1352 sure the cursor stays at the beginning of the buffer.
1354 When this option is nil, don't do anything special at the beginning of
1355 the buffer."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-level-after-item/entry-creation t
1360 "Non-nil means cycle entry level or item indentation in new empty entries.
1362 When the cursor is at the end of an empty headline, i.e., with only stars
1363 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1364 and then all possible ancestor states, before returning to the original state.
1365 This makes data entry extremely fast: M-RET to create a new headline,
1366 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1368 When the cursor is at the end of an empty plain list item, one TAB will
1369 make it a subitem, two or more tabs will back up to make this an item
1370 higher up in the item hierarchy."
1371 :group 'org-cycle
1372 :type 'boolean)
1374 (defcustom org-cycle-emulate-tab t
1375 "Where should `org-cycle' emulate TAB.
1376 nil Never
1377 white Only in completely white lines
1378 whitestart Only at the beginning of lines, before the first non-white char
1379 t Everywhere except in headlines
1380 exc-hl-bol Everywhere except at the start of a headline
1381 If TAB is used in a place where it does not emulate TAB, the current subtree
1382 visibility is cycled."
1383 :group 'org-cycle
1384 :type '(choice (const :tag "Never" nil)
1385 (const :tag "Only in completely white lines" white)
1386 (const :tag "Before first char in a line" whitestart)
1387 (const :tag "Everywhere except in headlines" t)
1388 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1390 (defcustom org-cycle-separator-lines 2
1391 "Number of empty lines needed to keep an empty line between collapsed trees.
1392 If you leave an empty line between the end of a subtree and the following
1393 headline, this empty line is hidden when the subtree is folded.
1394 Org mode will leave (exactly) one empty line visible if the number of
1395 empty lines is equal or larger to the number given in this variable.
1396 So the default 2 means at least 2 empty lines after the end of a subtree
1397 are needed to produce free space between a collapsed subtree and the
1398 following headline.
1400 If the number is negative, and the number of empty lines is at least -N,
1401 all empty lines are shown.
1403 Special case: when 0, never leave empty lines in collapsed view."
1404 :group 'org-cycle
1405 :type 'integer)
1406 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1408 (defcustom org-pre-cycle-hook nil
1409 "Hook that is run before visibility cycling is happening.
1410 The function(s) in this hook must accept a single argument which indicates
1411 the new state that will be set right after running this hook. The
1412 argument is a symbol. Before a global state change, it can have the values
1413 `overview', `content', or `all'. Before a local state change, it can have
1414 the values `folded', `children', or `subtree'."
1415 :group 'org-cycle
1416 :type 'hook)
1418 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1419 org-cycle-show-empty-lines
1420 org-optimize-window-after-visibility-change)
1421 "Hook that is run after `org-cycle' has changed the buffer visibility.
1422 The function(s) in this hook must accept a single argument which indicates
1423 the new state that was set by the most recent `org-cycle' command. The
1424 argument is a symbol. After a global state change, it can have the values
1425 `overview', `contents', or `all'. After a local state change, it can have
1426 the values `folded', `children', or `subtree'."
1427 :group 'org-cycle
1428 :type 'hook
1429 :version "26.1"
1430 :package-version '(Org . "8.3"))
1432 (defgroup org-edit-structure nil
1433 "Options concerning structure editing in Org mode."
1434 :tag "Org Edit Structure"
1435 :group 'org-structure)
1437 (defcustom org-odd-levels-only nil
1438 "Non-nil means skip even levels and only use odd levels for the outline.
1439 This has the effect that two stars are being added/taken away in
1440 promotion/demotion commands. It also influences how levels are
1441 handled by the exporters.
1442 Changing it requires restart of `font-lock-mode' to become effective
1443 for fontification also in regions already fontified.
1444 You may also set this on a per-file basis by adding one of the following
1445 lines to the buffer:
1447 #+STARTUP: odd
1448 #+STARTUP: oddeven"
1449 :group 'org-edit-structure
1450 :group 'org-appearance
1451 :type 'boolean)
1453 (defcustom org-adapt-indentation t
1454 "Non-nil means adapt indentation to outline node level.
1456 When this variable is set, Org assumes that you write outlines by
1457 indenting text in each node to align with the headline (after the
1458 stars). The following issues are influenced by this variable:
1460 - The indentation is increased by one space in a demotion
1461 command, and decreased by one in a promotion command. However,
1462 in the latter case, if shifting some line in the entry body
1463 would alter document structure (e.g., insert a new headline),
1464 indentation is not changed at all.
1466 - Property drawers and planning information is inserted indented
1467 when this variable is set. When nil, they will not be indented.
1469 - TAB indents a line relative to current level. The lines below
1470 a headline will be indented when this variable is set.
1472 Note that this is all about true indentation, by adding and
1473 removing space characters. See also \"org-indent.el\" which does
1474 level-dependent indentation in a virtual way, i.e. at display
1475 time in Emacs."
1476 :group 'org-edit-structure
1477 :type 'boolean
1478 :safe #'booleanp)
1480 (defcustom org-special-ctrl-a/e nil
1481 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1483 When t, `C-a' will bring back the cursor to the beginning of the
1484 headline text, i.e. after the stars and after a possible TODO
1485 keyword. In an item, this will be the position after bullet and
1486 check-box, if any. When the cursor is already at that position,
1487 another `C-a' will bring it to the beginning of the line.
1489 `C-e' will jump to the end of the headline, ignoring the presence
1490 of tags in the headline. A second `C-e' will then jump to the
1491 true end of the line, after any tags. This also means that, when
1492 this variable is non-nil, `C-e' also will never jump beyond the
1493 end of the heading of a folded section, i.e. not after the
1494 ellipses.
1496 When set to the symbol `reversed', the first `C-a' or `C-e' works
1497 normally, going to the true line boundary first. Only a directly
1498 following, identical keypress will bring the cursor to the
1499 special positions.
1501 This may also be a cons cell where the behavior for `C-a' and
1502 `C-e' is set separately."
1503 :group 'org-edit-structure
1504 :type '(choice
1505 (const :tag "off" nil)
1506 (const :tag "on: after stars/bullet and before tags first" t)
1507 (const :tag "reversed: true line boundary first" reversed)
1508 (cons :tag "Set C-a and C-e separately"
1509 (choice :tag "Special C-a"
1510 (const :tag "off" nil)
1511 (const :tag "on: after stars/bullet first" t)
1512 (const :tag "reversed: before stars/bullet first" reversed))
1513 (choice :tag "Special C-e"
1514 (const :tag "off" nil)
1515 (const :tag "on: before tags first" t)
1516 (const :tag "reversed: after tags first" reversed)))))
1517 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1519 (defcustom org-special-ctrl-k nil
1520 "Non-nil means `C-k' will behave specially in headlines.
1521 When nil, `C-k' will call the default `kill-line' command.
1522 When t, the following will happen while the cursor is in the headline:
1524 - When the cursor is at the beginning of a headline, kill the entire
1525 line and possible the folded subtree below the line.
1526 - When in the middle of the headline text, kill the headline up to the tags.
1527 - When after the headline text, kill the tags."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-ctrl-k-protect-subtree nil
1532 "Non-nil means, do not delete a hidden subtree with C-k.
1533 When set to the symbol `error', simply throw an error when C-k is
1534 used to kill (part-of) a headline that has hidden text behind it.
1535 Any other non-nil value will result in a query to the user, if it is
1536 OK to kill that hidden subtree. When nil, kill without remorse."
1537 :group 'org-edit-structure
1538 :version "24.1"
1539 :type '(choice
1540 (const :tag "Do not protect hidden subtrees" nil)
1541 (const :tag "Protect hidden subtrees with a security query" t)
1542 (const :tag "Never kill a hidden subtree with C-k" error)))
1544 (defcustom org-special-ctrl-o t
1545 "Non-nil means, make `C-o' insert a row in tables."
1546 :group 'org-edit-structure
1547 :type 'boolean)
1549 (defcustom org-catch-invisible-edits nil
1550 "Check if in invisible region before inserting or deleting a character.
1551 Valid values are:
1553 nil Do not check, so just do invisible edits.
1554 error Throw an error and do nothing.
1555 show Make point visible, and do the requested edit.
1556 show-and-error Make point visible, then throw an error and abort the edit.
1557 smart Make point visible, and do insertion/deletion if it is
1558 adjacent to visible text and the change feels predictable.
1559 Never delete a previously invisible character or add in the
1560 middle or right after an invisible region. Basically, this
1561 allows insertion and backward-delete right before ellipses.
1562 FIXME: maybe in this case we should not even show?"
1563 :group 'org-edit-structure
1564 :version "24.1"
1565 :type '(choice
1566 (const :tag "Do not check" nil)
1567 (const :tag "Throw error when trying to edit" error)
1568 (const :tag "Unhide, but do not do the edit" show-and-error)
1569 (const :tag "Show invisible part and do the edit" show)
1570 (const :tag "Be smart and do the right thing" smart)))
1572 (defcustom org-yank-folded-subtrees t
1573 "Non-nil means when yanking subtrees, fold them.
1574 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1575 it starts with a heading and all other headings in it are either children
1576 or siblings, then fold all the subtrees. However, do this only if no
1577 text after the yank would be swallowed into a folded tree by this action."
1578 :group 'org-edit-structure
1579 :type 'boolean)
1581 (defcustom org-yank-adjusted-subtrees nil
1582 "Non-nil means when yanking subtrees, adjust the level.
1583 With this setting, `org-paste-subtree' is used to insert the subtree, see
1584 this function for details."
1585 :group 'org-edit-structure
1586 :type 'boolean)
1588 (defcustom org-M-RET-may-split-line '((default . t))
1589 "Non-nil means M-RET will split the line at the cursor position.
1590 When nil, it will go to the end of the line before making a
1591 new line.
1592 You may also set this option in a different way for different
1593 contexts. Valid contexts are:
1595 headline when creating a new headline
1596 item when creating a new item
1597 table in a table field
1598 default the value to be used for all contexts not explicitly
1599 customized"
1600 :group 'org-structure
1601 :group 'org-table
1602 :type '(choice
1603 (const :tag "Always" t)
1604 (const :tag "Never" nil)
1605 (repeat :greedy t :tag "Individual contexts"
1606 (cons
1607 (choice :tag "Context"
1608 (const headline)
1609 (const item)
1610 (const table)
1611 (const default))
1612 (boolean)))))
1615 (defcustom org-insert-heading-respect-content nil
1616 "Non-nil means insert new headings after the current subtree.
1617 \\<org-mode-map>
1618 When nil, the new heading is created directly after the current line.
1619 The commands `\\[org-insert-heading-respect-content]' and \
1620 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1621 for the duration of the command."
1622 :group 'org-structure
1623 :type 'boolean)
1625 (defcustom org-blank-before-new-entry '((heading . auto)
1626 (plain-list-item . auto))
1627 "Should `org-insert-heading' leave a blank line before new heading/item?
1628 The value is an alist, with `heading' and `plain-list-item' as CAR,
1629 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1630 which case Org will look at the surrounding headings/items and try to
1631 make an intelligent decision whether to insert a blank line or not."
1632 :group 'org-edit-structure
1633 :type '(list
1634 (cons (const heading)
1635 (choice (const :tag "Never" nil)
1636 (const :tag "Always" t)
1637 (const :tag "Auto" auto)))
1638 (cons (const plain-list-item)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))))
1643 (defcustom org-insert-heading-hook nil
1644 "Hook being run after inserting a new heading."
1645 :group 'org-edit-structure
1646 :type 'hook)
1648 (defcustom org-enable-fixed-width-editor t
1649 "Non-nil means lines starting with \":\" are treated as fixed-width.
1650 This currently only means they are never auto-wrapped.
1651 When nil, such lines will be treated like ordinary lines."
1652 :group 'org-edit-structure
1653 :type 'boolean)
1655 (defgroup org-sparse-trees nil
1656 "Options concerning sparse trees in Org mode."
1657 :tag "Org Sparse Trees"
1658 :group 'org-structure)
1660 (defcustom org-highlight-sparse-tree-matches t
1661 "Non-nil means highlight all matches that define a sparse tree.
1662 The highlights will automatically disappear the next time the buffer is
1663 changed by an edit command."
1664 :group 'org-sparse-trees
1665 :type 'boolean)
1667 (defcustom org-remove-highlights-with-change t
1668 "Non-nil means any change to the buffer will remove temporary highlights.
1669 \\<org-mode-map>\
1670 Such highlights are created by `org-occur' and `org-clock-display'.
1671 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1672 to get rid of the highlights.
1673 The highlights created by `org-toggle-latex-fragment' always need
1674 `\\[org-toggle-latex-fragment]' to be removed."
1675 :group 'org-sparse-trees
1676 :group 'org-time
1677 :type 'boolean)
1679 (defcustom org-occur-case-fold-search t
1680 "Non-nil means `org-occur' should be case-insensitive.
1681 If set to `smart' the search will be case-insensitive only if it
1682 doesn't specify any upper case character."
1683 :group 'org-sparse-trees
1684 :version "26.1"
1685 :type '(choice
1686 (const :tag "Case-sensitive" nil)
1687 (const :tag "Case-insensitive" t)
1688 (const :tag "Case-insensitive for lower case searches only" smart)))
1690 (defcustom org-occur-hook '(org-first-headline-recenter)
1691 "Hook that is run after `org-occur' has constructed a sparse tree.
1692 This can be used to recenter the window to show as much of the structure
1693 as possible."
1694 :group 'org-sparse-trees
1695 :type 'hook)
1697 (defgroup org-table nil
1698 "Options concerning tables in Org mode."
1699 :tag "Org Table"
1700 :group 'org)
1702 (defcustom org-self-insert-cluster-for-undo nil
1703 "Non-nil means cluster self-insert commands for undo when possible.
1704 If this is set, then, like in the Emacs command loop, 20 consecutive
1705 characters will be undone together.
1706 This is configurable, because there is some impact on typing performance."
1707 :group 'org-table
1708 :type 'boolean)
1710 (defcustom org-table-tab-recognizes-table.el t
1711 "Non-nil means TAB will automatically notice a table.el table.
1712 When it sees such a table, it moves point into it and - if necessary -
1713 calls `table-recognize-table'."
1714 :group 'org-table-editing
1715 :type 'boolean)
1717 (defgroup org-link nil
1718 "Options concerning links in Org mode."
1719 :tag "Org Link"
1720 :group 'org)
1722 (defvar-local org-link-abbrev-alist-local nil
1723 "Buffer-local version of `org-link-abbrev-alist', which see.
1724 The value of this is taken from the #+LINK lines.")
1726 (defcustom org-link-parameters
1727 '(("doi" :follow org--open-doi-link)
1728 ("elisp" :follow org--open-elisp-link)
1729 ("file" :complete org-file-complete-link)
1730 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1731 ("help" :follow org--open-help-link)
1732 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1733 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1734 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1735 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1736 ("shell" :follow org--open-shell-link))
1737 "An alist of properties that defines all the links in Org mode.
1738 The key in each association is a string of the link type.
1739 Subsequent optional elements make up a p-list of link properties.
1741 :follow - A function that takes the link path as an argument.
1743 :export - A function that takes the link path, description and
1744 export-backend as arguments.
1746 :store - A function responsible for storing the link. See the
1747 function `org-store-link-functions'.
1749 :complete - A function that inserts a link with completion. The
1750 function takes one optional prefix arg.
1752 :face - A face for the link, or a function that returns a face.
1753 The function takes one argument which is the link path. The
1754 default face is `org-link'.
1756 :mouse-face - The mouse-face. The default is `highlight'.
1758 :display - `full' will not fold the link in descriptive
1759 display. Default is `org-link'.
1761 :help-echo - A string or function that takes (window object position)
1762 as arguments and returns a string.
1764 :keymap - A keymap that is active on the link. The default is
1765 `org-mouse-map'.
1767 :htmlize-link - A function for the htmlize-link. Defaults
1768 to (list :uri \"type:path\")
1770 :activate-func - A function to run at the end of font-lock
1771 activation. The function must accept (link-start link-end path bracketp)
1772 as arguments."
1773 :group 'org-link
1774 :type '(alist :tag "Link display parameters"
1775 :value-type plist)
1776 :version "26.1"
1777 :package-version '(Org . "9.1"))
1779 (defun org-link-get-parameter (type key)
1780 "Get TYPE link property for KEY.
1781 TYPE is a string and KEY is a plist keyword."
1782 (plist-get
1783 (cdr (assoc type org-link-parameters))
1784 key))
1786 (defun org-link-set-parameters (type &rest parameters)
1787 "Set link TYPE properties to PARAMETERS.
1788 PARAMETERS should be :key val pairs."
1789 (let ((data (assoc type org-link-parameters)))
1790 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1791 (push (cons type parameters) org-link-parameters)
1792 (org-make-link-regexps)
1793 (org-element-update-syntax))))
1795 (defun org-link-types ()
1796 "Return a list of known link types."
1797 (mapcar #'car org-link-parameters))
1799 (defcustom org-link-abbrev-alist nil
1800 "Alist of link abbreviations.
1801 The car of each element is a string, to be replaced at the start of a link.
1802 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1803 links in Org buffers can have an optional tag after a double colon, e.g.,
1805 [[linkkey:tag][description]]
1807 The `linkkey' must be a single word, starting with a letter, followed
1808 by letters, numbers, `-' or `_'.
1810 If REPLACE is a string, the tag will simply be appended to create the link.
1811 If the string contains \"%s\", the tag will be inserted there. If the string
1812 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1813 at that point (see the function `url-hexify-string'). If the string contains
1814 the specifier \"%(my-function)\", then the custom function `my-function' will
1815 be invoked: this function takes the tag as its only argument and must return
1816 a string.
1818 REPLACE may also be a function that will be called with the tag as the
1819 only argument to create the link, which should be returned as a string.
1821 See the manual for examples."
1822 :group 'org-link
1823 :type '(repeat
1824 (cons
1825 (string :tag "Protocol")
1826 (choice
1827 (string :tag "Format")
1828 (function)))))
1830 (defcustom org-descriptive-links t
1831 "Non-nil means Org will display descriptive links.
1832 E.g. [[https://orgmode.org][Org website]] will be displayed as
1833 \"Org Website\", hiding the link itself and just displaying its
1834 description. When set to nil, Org will display the full links
1835 literally.
1837 You can interactively set the value of this variable by calling
1838 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1839 :group 'org-link
1840 :type 'boolean)
1842 (defcustom org-link-file-path-type 'adaptive
1843 "How the path name in file links should be stored.
1844 Valid values are:
1846 relative Relative to the current directory, i.e. the directory of the file
1847 into which the link is being inserted.
1848 absolute Absolute path, if possible with ~ for home directory.
1849 noabbrev Absolute path, no abbreviation of home directory.
1850 adaptive Use relative path for files in the current directory and sub-
1851 directories of it. For other files, use an absolute path."
1852 :group 'org-link
1853 :type '(choice
1854 (const relative)
1855 (const absolute)
1856 (const noabbrev)
1857 (const adaptive)))
1859 (defvaralias 'org-activate-links 'org-highlight-links)
1860 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1861 "Types of links that should be highlighted in Org files.
1863 This is a list of symbols, each one of them leading to the
1864 highlighting of a certain link type.
1866 You can still open links that are not highlighted.
1868 In principle, it does not hurt to turn on highlighting for all
1869 link types. There may be a small gain when turning off unused
1870 link types. The types are:
1872 bracket The recommended [[link][description]] or [[link]] links with hiding.
1873 angle Links in angular brackets that may contain whitespace like
1874 <bbdb:Carsten Dominik>.
1875 plain Plain links in normal text, no whitespace, like http://google.com.
1876 radio Text that is matched by a radio target, see manual for details.
1877 tag Tag settings in a headline (link to tag search).
1878 date Time stamps (link to calendar).
1879 footnote Footnote labels.
1881 If you set this variable during an Emacs session, use `org-mode-restart'
1882 in the Org buffer so that the change takes effect."
1883 :group 'org-link
1884 :group 'org-appearance
1885 :type '(set :greedy t
1886 (const :tag "Double bracket links" bracket)
1887 (const :tag "Angular bracket links" angle)
1888 (const :tag "Plain text links" plain)
1889 (const :tag "Radio target matches" radio)
1890 (const :tag "Tags" tag)
1891 (const :tag "Timestamps" date)
1892 (const :tag "Footnotes" footnote)))
1894 (defcustom org-make-link-description-function nil
1895 "Function to use for generating link descriptions from links.
1896 This function must take two parameters: the first one is the
1897 link, the second one is the description generated by
1898 `org-insert-link'. The function should return the description to
1899 use."
1900 :group 'org-link
1901 :type '(choice (const nil) (function)))
1903 (defgroup org-link-store nil
1904 "Options concerning storing links in Org mode."
1905 :tag "Org Store Link"
1906 :group 'org-link)
1908 (defcustom org-url-hexify-p t
1909 "When non-nil, hexify URL when creating a link."
1910 :type 'boolean
1911 :version "24.3"
1912 :group 'org-link-store)
1914 (defcustom org-email-link-description-format "Email %c: %.30s"
1915 "Format of the description part of a link to an email or usenet message.
1916 The following %-escapes will be replaced by corresponding information:
1918 %F full \"From\" field
1919 %f name, taken from \"From\" field, address if no name
1920 %T full \"To\" field
1921 %t first name in \"To\" field, address if no name
1922 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1923 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1924 %s subject
1925 %d date
1926 %m message-id.
1928 You may use normal field width specification between the % and the letter.
1929 This is for example useful to limit the length of the subject.
1931 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1932 :group 'org-link-store
1933 :type 'string)
1935 (defcustom org-from-is-user-regexp
1936 (let (r1 r2)
1937 (when (and user-mail-address (not (string= user-mail-address "")))
1938 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1939 (when (and user-full-name (not (string= user-full-name "")))
1940 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1941 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1942 "Regexp matched against the \"From:\" header of an email or usenet message.
1943 It should match if the message is from the user him/herself."
1944 :group 'org-link-store
1945 :type 'regexp)
1947 (defcustom org-context-in-file-links t
1948 "Non-nil means file links from `org-store-link' contain context.
1949 \\<org-mode-map>
1950 A search string will be added to the file name with :: as separator
1951 and used to find the context when the link is activated by the command
1952 `org-open-at-point'. When this option is t, the entire active region
1953 will be placed in the search string of the file link. If set to a
1954 positive integer, only the first n lines of context will be stored.
1956 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1957 \\[org-store-link]')
1958 negates this setting for the duration of the command."
1959 :group 'org-link-store
1960 :type '(choice boolean integer))
1962 (defcustom org-keep-stored-link-after-insertion nil
1963 "Non-nil means keep link in list for entire session.
1964 \\<org-mode-map>
1965 The command `org-store-link' adds a link pointing to the current
1966 location to an internal list. These links accumulate during a session.
1967 The command `org-insert-link' can be used to insert links into any
1968 Org file (offering completion for all stored links).
1970 When this option is nil, every link which has been inserted once using
1971 `\\[org-insert-link]' will be removed from the list, to make completing the \
1972 unused
1973 links more efficient."
1974 :group 'org-link-store
1975 :type 'boolean)
1977 (defgroup org-link-follow nil
1978 "Options concerning following links in Org mode."
1979 :tag "Org Follow Link"
1980 :group 'org-link)
1982 (defcustom org-link-translation-function nil
1983 "Function to translate links with different syntax to Org syntax.
1984 This can be used to translate links created for example by the Planner
1985 or emacs-wiki packages to Org syntax.
1986 The function must accept two parameters, a TYPE containing the link
1987 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1988 which is everything after the link protocol. It should return a cons
1989 with possibly modified values of type and path.
1990 Org contains a function for this, so if you set this variable to
1991 `org-translate-link-from-planner', you should be able follow many
1992 links created by planner."
1993 :group 'org-link-follow
1994 :type '(choice (const nil) (function)))
1996 (defcustom org-follow-link-hook nil
1997 "Hook that is run after a link has been followed."
1998 :group 'org-link-follow
1999 :type 'hook)
2001 (defcustom org-tab-follows-link nil
2002 "Non-nil means on links TAB will follow the link.
2003 Needs to be set before org.el is loaded.
2004 This really should not be used, it does not make sense, and the
2005 implementation is bad."
2006 :group 'org-link-follow
2007 :type 'boolean)
2009 (defcustom org-return-follows-link nil
2010 "Non-nil means on links RET will follow the link.
2011 In tables, the special behavior of RET has precedence."
2012 :group 'org-link-follow
2013 :type 'boolean)
2015 (defcustom org-mouse-1-follows-link
2016 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2017 "Non-nil means mouse-1 on a link will follow the link.
2018 A longer mouse click will still set point. Needs to be set
2019 before org.el is loaded."
2020 :group 'org-link-follow
2021 :version "26.1"
2022 :package-version '(Org . "8.3")
2023 :type '(choice
2024 (const :tag "A double click follows the link" double)
2025 (const :tag "Unconditionally follow the link with mouse-1" t)
2026 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2028 (defcustom org-mark-ring-length 4
2029 "Number of different positions to be recorded in the ring.
2030 Changing this requires a restart of Emacs to work correctly."
2031 :group 'org-link-follow
2032 :type 'integer)
2034 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2035 "Non-nil means internal fuzzy links can only match headlines.
2037 When nil, the a fuzzy link may point to a target or a named
2038 construct in the document. When set to the special value
2039 `query-to-create', offer to create a new headline when none
2040 matched.
2042 Spaces and statistics cookies are ignored during heading searches."
2043 :group 'org-link-follow
2044 :version "24.1"
2045 :type '(choice
2046 (const :tag "Use fuzzy text search" nil)
2047 (const :tag "Match only exact headline" t)
2048 (const :tag "Match exact headline or query to create it"
2049 query-to-create))
2050 :safe #'symbolp)
2052 (defcustom org-link-frame-setup
2053 '((vm . vm-visit-folder-other-frame)
2054 (vm-imap . vm-visit-imap-folder-other-frame)
2055 (gnus . org-gnus-no-new-news)
2056 (file . find-file-other-window)
2057 (wl . wl-other-frame))
2058 "Setup the frame configuration for following links.
2059 When following a link with Emacs, it may often be useful to display
2060 this link in another window or frame. This variable can be used to
2061 set this up for the different types of links.
2062 For VM, use any of
2063 `vm-visit-folder'
2064 `vm-visit-folder-other-window'
2065 `vm-visit-folder-other-frame'
2066 For Gnus, use any of
2067 `gnus'
2068 `gnus-other-frame'
2069 `org-gnus-no-new-news'
2070 For FILE, use any of
2071 `find-file'
2072 `find-file-other-window'
2073 `find-file-other-frame'
2074 For Wanderlust use any of
2075 `wl'
2076 `wl-other-frame'
2077 For the calendar, use the variable `calendar-setup'.
2078 For BBDB, it is currently only possible to display the matches in
2079 another window."
2080 :group 'org-link-follow
2081 :type '(list
2082 (cons (const vm)
2083 (choice
2084 (const vm-visit-folder)
2085 (const vm-visit-folder-other-window)
2086 (const vm-visit-folder-other-frame)))
2087 (cons (const vm-imap)
2088 (choice
2089 (const vm-visit-imap-folder)
2090 (const vm-visit-imap-folder-other-window)
2091 (const vm-visit-imap-folder-other-frame)))
2092 (cons (const gnus)
2093 (choice
2094 (const gnus)
2095 (const gnus-other-frame)
2096 (const org-gnus-no-new-news)))
2097 (cons (const file)
2098 (choice
2099 (const find-file)
2100 (const find-file-other-window)
2101 (const find-file-other-frame)))
2102 (cons (const wl)
2103 (choice
2104 (const wl)
2105 (const wl-other-frame)))))
2107 (defcustom org-display-internal-link-with-indirect-buffer nil
2108 "Non-nil means use indirect buffer to display infile links.
2109 Activating internal links (from one location in a file to another location
2110 in the same file) normally just jumps to the location. When the link is
2111 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2112 is displayed in
2113 another window. When this option is set, the other window actually displays
2114 an indirect buffer clone of the current buffer, to avoid any visibility
2115 changes to the current buffer."
2116 :group 'org-link-follow
2117 :type 'boolean)
2119 (defcustom org-open-non-existing-files nil
2120 "Non-nil means `org-open-file' will open non-existing files.
2121 When nil, an error will be generated.
2122 This variable applies only to external applications because they
2123 might choke on non-existing files. If the link is to a file that
2124 will be opened in Emacs, the variable is ignored."
2125 :group 'org-link-follow
2126 :type 'boolean)
2128 (defcustom org-open-directory-means-index-dot-org nil
2129 "Non-nil means a link to a directory really means to index.org.
2130 When nil, following a directory link will run dired or open a finder/explorer
2131 window on that directory."
2132 :group 'org-link-follow
2133 :type 'boolean)
2135 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2136 "Non-nil means ask for confirmation before executing shell links.
2137 Shell links can be dangerous: just think about a link
2139 [[shell:rm -rf ~/*][Google Search]]
2141 This link would show up in your Org document as \"Google Search\",
2142 but really it would remove your entire home directory.
2143 Therefore we advise against setting this variable to nil.
2144 Just change it to `y-or-n-p' if you want to confirm with a
2145 single keystroke rather than having to type \"yes\"."
2146 :group 'org-link-follow
2147 :type '(choice
2148 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2149 (const :tag "with y-or-n (faster)" y-or-n-p)
2150 (const :tag "no confirmation (dangerous)" nil)))
2151 (put 'org-confirm-shell-link-function
2152 'safe-local-variable
2153 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2155 (defcustom org-confirm-shell-link-not-regexp ""
2156 "A regexp to skip confirmation for shell links."
2157 :group 'org-link-follow
2158 :version "24.1"
2159 :type 'regexp)
2161 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2162 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2163 Elisp links can be dangerous: just think about a link
2165 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2167 This link would show up in your Org document as \"Google Search\",
2168 but really it would remove your entire home directory.
2169 Therefore we advise against setting this variable to nil.
2170 Just change it to `y-or-n-p' if you want to confirm with a
2171 single keystroke rather than having to type \"yes\"."
2172 :group 'org-link-follow
2173 :type '(choice
2174 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2175 (const :tag "with y-or-n (faster)" y-or-n-p)
2176 (const :tag "no confirmation (dangerous)" nil)))
2177 (put 'org-confirm-shell-link-function
2178 'safe-local-variable
2179 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2181 (defcustom org-confirm-elisp-link-not-regexp ""
2182 "A regexp to skip confirmation for Elisp links."
2183 :group 'org-link-follow
2184 :version "24.1"
2185 :type 'regexp)
2187 (defconst org-file-apps-defaults-gnu
2188 '((remote . emacs)
2189 (system . mailcap)
2190 (t . mailcap))
2191 "Default file applications on a UNIX or GNU/Linux system.
2192 See `org-file-apps'.")
2194 (defconst org-file-apps-defaults-macosx
2195 '((remote . emacs)
2196 (system . "open %s")
2197 ("ps.gz" . "gv %s")
2198 ("eps.gz" . "gv %s")
2199 ("dvi" . "xdvi %s")
2200 ("fig" . "xfig %s")
2201 (t . "open %s"))
2202 "Default file applications on a macOS system.
2203 The system \"open\" is known as a default, but we use X11 applications
2204 for some files for which the OS does not have a good default.
2205 See `org-file-apps'.")
2207 (defconst org-file-apps-defaults-windowsnt
2208 (list '(remote . emacs)
2209 (cons 'system (lambda (file _path)
2210 (with-no-warnings (w32-shell-execute "open" file))))
2211 (cons t (lambda (file _path)
2212 (with-no-warnings (w32-shell-execute "open" file)))))
2213 "Default file applications on a Windows NT system.
2214 The system \"open\" is used for most files.
2215 See `org-file-apps'.")
2217 (defcustom org-file-apps
2218 '((auto-mode . emacs)
2219 ("\\.mm\\'" . default)
2220 ("\\.x?html?\\'" . default)
2221 ("\\.pdf\\'" . default))
2222 "External applications for opening `file:path' items in a document.
2223 \\<org-mode-map>\
2225 Org mode uses system defaults for different file types, but
2226 you can use this variable to set the application for a given file
2227 extension. The entries in this list are cons cells where the car identifies
2228 files and the cdr the corresponding command.
2230 Possible values for the file identifier are:
2232 \"string\" A string as a file identifier can be interpreted in different
2233 ways, depending on its contents:
2235 - Alphanumeric characters only:
2236 Match links with this file extension.
2237 Example: (\"pdf\" . \"evince %s\")
2238 to open PDFs with evince.
2240 - Regular expression: Match links where the
2241 filename matches the regexp. If you want to
2242 use groups here, use shy groups.
2244 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2245 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2246 to open *.html and *.xhtml with firefox.
2248 - Regular expression which contains (non-shy) groups:
2249 Match links where the whole link, including \"::\", and
2250 anything after that, matches the regexp.
2251 In a custom command string, %1, %2, etc. are replaced with
2252 the parts of the link that were matched by the groups.
2253 For backwards compatibility, if a command string is given
2254 that does not use any of the group matches, this case is
2255 handled identically to the second one (i.e. match against
2256 file name only).
2257 In a custom function, you can access the group matches with
2258 (match-string n link).
2260 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2261 \"evince -p %1 %s\")
2262 to open [[file:document.pdf::5]] with evince at page 5.
2264 `directory' Matches a directory
2265 `remote' Matches a remote file, accessible through tramp or efs.
2266 Remote files most likely should be visited through Emacs
2267 because external applications cannot handle such paths.
2268 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2269 so all files Emacs knows how to handle. Using this with
2270 command `emacs' will open most files in Emacs. Beware that this
2271 will also open html files inside Emacs, unless you add
2272 (\"html\" . default) to the list as well.
2273 `system' The system command to open files, like `open' on Windows
2274 and macOS, and mailcap under GNU/Linux. This is the command
2275 that will be selected if you call `org-open-at-point' with a
2276 double prefix argument (`\\[universal-argument] \
2277 \\[universal-argument] \\[org-open-at-point]').
2278 t Default for files not matched by any of the other options.
2280 Possible values for the command are:
2282 `emacs' The file will be visited by the current Emacs process.
2283 `default' Use the default application for this file type, which is the
2284 association for t in the list, most likely in the system-specific
2285 part. This can be used to overrule an unwanted setting in the
2286 system-specific variable.
2287 `system' Use the system command for opening files, like \"open\".
2288 This command is specified by the entry whose car is `system'.
2289 Most likely, the system-specific version of this variable
2290 does define this command, but you can overrule/replace it
2291 here.
2292 `mailcap' Use command specified in the mailcaps.
2293 string A command to be executed by a shell; %s will be replaced
2294 by the path to the file.
2295 function A Lisp function, which will be called with two arguments:
2296 the file path and the original link string, without the
2297 \"file:\" prefix.
2299 For more examples, see the system specific constants
2300 `org-file-apps-defaults-macosx'
2301 `org-file-apps-defaults-windowsnt'
2302 `org-file-apps-defaults-gnu'."
2303 :group 'org-link-follow
2304 :type '(repeat
2305 (cons (choice :value ""
2306 (string :tag "Extension")
2307 (const :tag "System command to open files" system)
2308 (const :tag "Default for unrecognized files" t)
2309 (const :tag "Remote file" remote)
2310 (const :tag "Links to a directory" directory)
2311 (const :tag "Any files that have Emacs modes"
2312 auto-mode))
2313 (choice :value ""
2314 (const :tag "Visit with Emacs" emacs)
2315 (const :tag "Use default" default)
2316 (const :tag "Use the system command" system)
2317 (string :tag "Command")
2318 (function :tag "Function")))))
2320 (defcustom org-doi-server-url "http://dx.doi.org/"
2321 "The URL of the DOI server."
2322 :type 'string
2323 :version "24.3"
2324 :group 'org-link-follow)
2326 (defgroup org-refile nil
2327 "Options concerning refiling entries in Org mode."
2328 :tag "Org Refile"
2329 :group 'org)
2331 (defcustom org-directory "~/org"
2332 "Directory with Org files.
2333 This is just a default location to look for Org files. There is no need
2334 at all to put your files into this directory. It is used in the
2335 following situations:
2337 1. When a capture template specifies a target file that is not an
2338 absolute path. The path will then be interpreted relative to
2339 `org-directory'
2340 2. When the value of variable `org-agenda-files' is a single file, any
2341 relative paths in this file will be taken as relative to
2342 `org-directory'."
2343 :group 'org-refile
2344 :group 'org-capture
2345 :type 'directory)
2347 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2348 "Default target for storing notes.
2349 Used as a fall back file for org-capture.el, for templates that
2350 do not specify a target file."
2351 :group 'org-refile
2352 :group 'org-capture
2353 :type 'file)
2355 (defcustom org-reverse-note-order nil
2356 "Non-nil means store new notes at the beginning of a file or entry.
2357 When nil, new notes will be filed to the end of a file or entry.
2358 This can also be a list with cons cells of regular expressions that
2359 are matched against file names, and values."
2360 :group 'org-capture
2361 :group 'org-refile
2362 :type '(choice
2363 (const :tag "Reverse always" t)
2364 (const :tag "Reverse never" nil)
2365 (repeat :tag "By file name regexp"
2366 (cons regexp boolean))))
2368 (defcustom org-log-refile nil
2369 "Information to record when a task is refiled.
2371 Possible values are:
2373 nil Don't add anything
2374 time Add a time stamp to the task
2375 note Prompt for a note and add it with template `org-log-note-headings'
2377 This option can also be set with on a per-file-basis with
2379 #+STARTUP: nologrefile
2380 #+STARTUP: logrefile
2381 #+STARTUP: lognoterefile
2383 You can have local logging settings for a subtree by setting the LOGGING
2384 property to one or more of these keywords.
2386 When bulk-refiling from the agenda, the value `note' is forbidden and
2387 will temporarily be changed to `time'."
2388 :group 'org-refile
2389 :group 'org-progress
2390 :version "24.1"
2391 :type '(choice
2392 (const :tag "No logging" nil)
2393 (const :tag "Record timestamp" time)
2394 (const :tag "Record timestamp with note." note)))
2396 (defcustom org-refile-targets nil
2397 "Targets for refiling entries with `\\[org-refile]'.
2398 This is a list of cons cells. Each cell contains:
2399 - a specification of the files to be considered, either a list of files,
2400 or a symbol whose function or variable value will be used to retrieve
2401 a file name or a list of file names. If you use `org-agenda-files' for
2402 that, all agenda files will be scanned for targets. Nil means consider
2403 headings in the current buffer.
2404 - A specification of how to find candidate refile targets. This may be
2405 any of:
2406 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2407 This tag has to be present in all target headlines, inheritance will
2408 not be considered.
2409 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2410 todo keyword.
2411 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2412 headlines that are refiling targets.
2413 - a cons cell (:level . N). Any headline of level N is considered a target.
2414 Note that, when `org-odd-levels-only' is set, level corresponds to
2415 order in hierarchy, not to the number of stars.
2416 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2417 Note that, when `org-odd-levels-only' is set, level corresponds to
2418 order in hierarchy, not to the number of stars.
2420 Each element of this list generates a set of possible targets.
2421 The union of these sets is presented (with completion) to
2422 the user by `org-refile'.
2424 You can set the variable `org-refile-target-verify-function' to a function
2425 to verify each headline found by the simple criteria above.
2427 When this variable is nil, all top-level headlines in the current buffer
2428 are used, equivalent to the value `((nil . (:level . 1))'."
2429 :group 'org-refile
2430 :type '(repeat
2431 (cons
2432 (choice :value org-agenda-files
2433 (const :tag "All agenda files" org-agenda-files)
2434 (const :tag "Current buffer" nil)
2435 (function) (variable) (file))
2436 (choice :tag "Identify target headline by"
2437 (cons :tag "Specific tag" (const :value :tag) (string))
2438 (cons :tag "TODO keyword" (const :value :todo) (string))
2439 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2440 (cons :tag "Level number" (const :value :level) (integer))
2441 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2443 (defcustom org-refile-target-verify-function nil
2444 "Function to verify if the headline at point should be a refile target.
2445 The function will be called without arguments, with point at the
2446 beginning of the headline. It should return t and leave point
2447 where it is if the headline is a valid target for refiling.
2449 If the target should not be selected, the function must return nil.
2450 In addition to this, it may move point to a place from where the search
2451 should be continued. For example, the function may decide that the entire
2452 subtree of the current entry should be excluded and move point to the end
2453 of the subtree."
2454 :group 'org-refile
2455 :type '(choice
2456 (const nil)
2457 (function)))
2459 (defcustom org-refile-use-cache nil
2460 "Non-nil means cache refile targets to speed up the process.
2461 \\<org-mode-map>\
2462 The cache for a particular file will be updated automatically when
2463 the buffer has been killed, or when any of the marker used for flagging
2464 refile targets no longer points at a live buffer.
2465 If you have added new entries to a buffer that might themselves be targets,
2466 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2467 if you find that easier, \
2468 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2469 \\[org-refile]'."
2470 :group 'org-refile
2471 :version "24.1"
2472 :type 'boolean)
2474 (defcustom org-refile-use-outline-path nil
2475 "Non-nil means provide refile targets as paths.
2476 So a level 3 headline will be available as level1/level2/level3.
2478 When the value is `file', also include the file name (without directory)
2479 into the path. In this case, you can also stop the completion after
2480 the file name, to get entries inserted as top level in the file.
2482 When `full-file-path', include the full file path.
2484 When `buffer-name', use the buffer name."
2485 :group 'org-refile
2486 :type '(choice
2487 (const :tag "Not" nil)
2488 (const :tag "Yes" t)
2489 (const :tag "Start with file name" file)
2490 (const :tag "Start with full file path" full-file-path)
2491 (const :tag "Start with buffer name" buffer-name)))
2493 (defcustom org-outline-path-complete-in-steps t
2494 "Non-nil means complete the outline path in hierarchical steps.
2495 When Org uses the refile interface to select an outline path (see
2496 `org-refile-use-outline-path'), the completion of the path can be
2497 done in a single go, or it can be done in steps down the headline
2498 hierarchy. Going in steps is probably the best if you do not use
2499 a special completion package like `ido' or `icicles'. However,
2500 when using these packages, going in one step can be very fast,
2501 while still showing the whole path to the entry."
2502 :group 'org-refile
2503 :type 'boolean)
2505 (defcustom org-refile-allow-creating-parent-nodes nil
2506 "Non-nil means allow the creation of new nodes as refile targets.
2507 New nodes are then created by adding \"/new node name\" to the completion
2508 of an existing node. When the value of this variable is `confirm',
2509 new node creation must be confirmed by the user (recommended).
2510 When nil, the completion must match an existing entry.
2512 Note that, if the new heading is not seen by the criteria
2513 listed in `org-refile-targets', multiple instances of the same
2514 heading would be created by trying again to file under the new
2515 heading."
2516 :group 'org-refile
2517 :type '(choice
2518 (const :tag "Never" nil)
2519 (const :tag "Always" t)
2520 (const :tag "Prompt for confirmation" confirm)))
2522 (defcustom org-refile-active-region-within-subtree nil
2523 "Non-nil means also refile active region within a subtree.
2525 By default `org-refile' doesn't allow refiling regions if they
2526 don't contain a set of subtrees, but it might be convenient to
2527 do so sometimes: in that case, the first line of the region is
2528 converted to a headline before refiling."
2529 :group 'org-refile
2530 :version "24.1"
2531 :type 'boolean)
2533 (defgroup org-todo nil
2534 "Options concerning TODO items in Org mode."
2535 :tag "Org TODO"
2536 :group 'org)
2538 (defgroup org-progress nil
2539 "Options concerning Progress logging in Org mode."
2540 :tag "Org Progress"
2541 :group 'org-time)
2543 (defvar org-todo-interpretation-widgets
2544 '((:tag "Sequence (cycling hits every state)" sequence)
2545 (:tag "Type (cycling directly to DONE)" type))
2546 "The available interpretation symbols for customizing `org-todo-keywords'.
2547 Interested libraries should add to this list.")
2549 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2550 "List of TODO entry keyword sequences and their interpretation.
2551 \\<org-mode-map>This is a list of sequences.
2553 Each sequence starts with a symbol, either `sequence' or `type',
2554 indicating if the keywords should be interpreted as a sequence of
2555 action steps, or as different types of TODO items. The first
2556 keywords are states requiring action - these states will select a headline
2557 for inclusion into the global TODO list Org produces. If one of the
2558 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2559 signify that no further action is necessary. If \"|\" is not found,
2560 the last keyword is treated as the only DONE state of the sequence.
2562 The command `\\[org-todo]' cycles an entry through these states, and one
2563 additional state where no keyword is present. For details about this
2564 cycling, see the manual.
2566 TODO keywords and interpretation can also be set on a per-file basis with
2567 the special #+SEQ_TODO and #+TYP_TODO lines.
2569 Each keyword can optionally specify a character for fast state selection
2570 \(in combination with the variable `org-use-fast-todo-selection')
2571 and specifiers for state change logging, using the same syntax that
2572 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2573 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2574 indicates to record a time stamp each time this state is selected.
2576 Each keyword may also specify if a timestamp or a note should be
2577 recorded when entering or leaving the state, by adding additional
2578 characters in the parenthesis after the keyword. This looks like this:
2579 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2580 record only the time of the state change. With X and Y being either
2581 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2582 Y when leaving the state if and only if the *target* state does not
2583 define X. You may omit any of the fast-selection key or X or /Y,
2584 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2586 For backward compatibility, this variable may also be just a list
2587 of keywords. In this case the interpretation (sequence or type) will be
2588 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2589 :group 'org-todo
2590 :group 'org-keywords
2591 :type '(choice
2592 (repeat :tag "Old syntax, just keywords"
2593 (string :tag "Keyword"))
2594 (repeat :tag "New syntax"
2595 (cons
2596 (choice
2597 :tag "Interpretation"
2598 ;;Quick and dirty way to see
2599 ;;`org-todo-interpretations'. This takes the
2600 ;;place of item arguments
2601 :convert-widget
2602 (lambda (widget)
2603 (widget-put widget
2604 :args (mapcar
2605 (lambda (x)
2606 (widget-convert
2607 (cons 'const x)))
2608 org-todo-interpretation-widgets))
2609 widget))
2610 (repeat
2611 (string :tag "Keyword"))))))
2613 (defvar-local org-todo-keywords-1 nil
2614 "All TODO and DONE keywords active in a buffer.")
2615 (defvar org-todo-keywords-for-agenda nil)
2616 (defvar org-done-keywords-for-agenda nil)
2617 (defvar org-todo-keyword-alist-for-agenda nil)
2618 (defvar org-tag-alist-for-agenda nil
2619 "Alist of all tags from all agenda files.")
2620 (defvar org-tag-groups-alist-for-agenda nil
2621 "Alist of all groups tags from all current agenda files.")
2622 (defvar-local org-tag-groups-alist nil)
2623 (defvar org-agenda-contributing-files nil)
2624 (defvar-local org-current-tag-alist nil
2625 "Alist of all tag groups in current buffer.
2626 This variable takes into consideration `org-tag-alist',
2627 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2628 (defvar-local org-not-done-keywords nil)
2629 (defvar-local org-done-keywords nil)
2630 (defvar-local org-todo-heads nil)
2631 (defvar-local org-todo-sets nil)
2632 (defvar-local org-todo-log-states nil)
2633 (defvar-local org-todo-kwd-alist nil)
2634 (defvar-local org-todo-key-alist nil)
2635 (defvar-local org-todo-key-trigger nil)
2637 (defcustom org-todo-interpretation 'sequence
2638 "Controls how TODO keywords are interpreted.
2639 This variable is in principle obsolete and is only used for
2640 backward compatibility, if the interpretation of todo keywords is
2641 not given already in `org-todo-keywords'. See that variable for
2642 more information."
2643 :group 'org-todo
2644 :group 'org-keywords
2645 :type '(choice (const sequence)
2646 (const type)))
2648 (defcustom org-use-fast-todo-selection t
2649 "\\<org-mode-map>\
2650 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2651 This variable describes if and under what circumstances the cycling
2652 mechanism for TODO keywords will be replaced by a single-key, direct
2653 selection scheme.
2655 When nil, fast selection is never used.
2657 When the symbol `prefix', it will be used when `org-todo' is called
2658 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2659 in an Org buffer, and
2660 `\\[universal-argument] t' in an agenda buffer.
2662 When t, fast selection is used by default. In this case, the prefix
2663 argument forces cycling instead.
2665 In all cases, the special interface is only used if access keys have
2666 actually been assigned by the user, i.e. if keywords in the configuration
2667 are followed by a letter in parenthesis, like TODO(t)."
2668 :group 'org-todo
2669 :type '(choice
2670 (const :tag "Never" nil)
2671 (const :tag "By default" t)
2672 (const :tag "Only with C-u C-c C-t" prefix)))
2674 (defcustom org-provide-todo-statistics t
2675 "Non-nil means update todo statistics after insert and toggle.
2676 ALL-HEADLINES means update todo statistics by including headlines
2677 with no TODO keyword as well, counting them as not done.
2678 A list of TODO keywords means the same, but skip keywords that are
2679 not in this list.
2680 When set to a list of two lists, the first list contains keywords
2681 to consider as TODO keywords, the second list contains keywords
2682 to consider as DONE keywords.
2684 When this is set, todo statistics is updated in the parent of the
2685 current entry each time a todo state is changed."
2686 :group 'org-todo
2687 :type '(choice
2688 (const :tag "Yes, only for TODO entries" t)
2689 (const :tag "Yes, including all entries" all-headlines)
2690 (repeat :tag "Yes, for TODOs in this list"
2691 (string :tag "TODO keyword"))
2692 (list :tag "Yes, for TODOs and DONEs in these lists"
2693 (repeat (string :tag "TODO keyword"))
2694 (repeat (string :tag "DONE keyword")))
2695 (other :tag "No TODO statistics" nil)))
2697 (defcustom org-hierarchical-todo-statistics t
2698 "Non-nil means TODO statistics covers just direct children.
2699 When nil, all entries in the subtree are considered.
2700 This has only an effect if `org-provide-todo-statistics' is set.
2701 To set this to nil for only a single subtree, use a COOKIE_DATA
2702 property and include the word \"recursive\" into the value."
2703 :group 'org-todo
2704 :type 'boolean)
2706 (defcustom org-after-todo-state-change-hook nil
2707 "Hook which is run after the state of a TODO item was changed.
2708 The new state (a string with a TODO keyword, or nil) is available in the
2709 Lisp variable `org-state'."
2710 :group 'org-todo
2711 :type 'hook)
2713 (defvar org-blocker-hook nil
2714 "Hook for functions that are allowed to block a state change.
2716 Functions in this hook should not modify the buffer.
2717 Each function gets as its single argument a property list,
2718 see `org-trigger-hook' for more information about this list.
2720 If any of the functions in this hook returns nil, the state change
2721 is blocked.")
2723 (defvar org-trigger-hook nil
2724 "Hook for functions that are triggered by a state change.
2726 Each function gets as its single argument a property list with at
2727 least the following elements:
2729 (:type type-of-change :position pos-at-entry-start
2730 :from old-state :to new-state)
2732 Depending on the type, more properties may be present.
2734 This mechanism is currently implemented for:
2736 TODO state changes
2737 ------------------
2738 :type todo-state-change
2739 :from previous state (keyword as a string), or nil, or a symbol
2740 `todo' or `done', to indicate the general type of state.
2741 :to new state, like in :from")
2743 (defcustom org-enforce-todo-dependencies nil
2744 "Non-nil means undone TODO entries will block switching the parent to DONE.
2745 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2746 be blocked if any prior sibling is not yet done.
2747 Finally, if the parent is blocked because of ordered siblings of its own,
2748 the child will also be blocked."
2749 :set (lambda (var val)
2750 (set var val)
2751 (if val
2752 (add-hook 'org-blocker-hook
2753 'org-block-todo-from-children-or-siblings-or-parent)
2754 (remove-hook 'org-blocker-hook
2755 'org-block-todo-from-children-or-siblings-or-parent)))
2756 :group 'org-todo
2757 :type 'boolean)
2759 (defcustom org-enforce-todo-checkbox-dependencies nil
2760 "Non-nil means unchecked boxes will block switching the parent to DONE.
2761 When this is nil, checkboxes have no influence on switching TODO states.
2762 When non-nil, you first need to check off all check boxes before the TODO
2763 entry can be switched to DONE.
2764 This variable needs to be set before org.el is loaded, and you need to
2765 restart Emacs after a change to make the change effective. The only way
2766 to change is while Emacs is running is through the customize interface."
2767 :set (lambda (var val)
2768 (set var val)
2769 (if val
2770 (add-hook 'org-blocker-hook
2771 'org-block-todo-from-checkboxes)
2772 (remove-hook 'org-blocker-hook
2773 'org-block-todo-from-checkboxes)))
2774 :group 'org-todo
2775 :type 'boolean)
2777 (defcustom org-treat-insert-todo-heading-as-state-change nil
2778 "Non-nil means inserting a TODO heading is treated as state change.
2779 So when the command `\\[org-insert-todo-heading]' is used, state change
2780 logging will apply if appropriate. When nil, the new TODO item will
2781 be inserted directly, and no logging will take place."
2782 :group 'org-todo
2783 :type 'boolean)
2785 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2786 "Non-nil means switching TODO states with S-cursor counts as state change.
2787 This is the default behavior. However, setting this to nil allows a
2788 convenient way to select a TODO state and bypass any logging associated
2789 with that."
2790 :group 'org-todo
2791 :type 'boolean)
2793 (defcustom org-todo-state-tags-triggers nil
2794 "Tag changes that should be triggered by TODO state changes.
2795 This is a list. Each entry is
2797 (state-change (tag . flag) .......)
2799 State-change can be a string with a state, and empty string to indicate the
2800 state that has no TODO keyword, or it can be one of the symbols `todo'
2801 or `done', meaning any not-done or done state, respectively."
2802 :group 'org-todo
2803 :group 'org-tags
2804 :type '(repeat
2805 (cons (choice :tag "When changing to"
2806 (const :tag "Not-done state" todo)
2807 (const :tag "Done state" done)
2808 (string :tag "State"))
2809 (repeat
2810 (cons :tag "Tag action"
2811 (string :tag "Tag")
2812 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2814 (defcustom org-log-done nil
2815 "Information to record when a task moves to the DONE state.
2817 Possible values are:
2819 nil Don't add anything, just change the keyword
2820 time Add a time stamp to the task
2821 note Prompt for a note and add it with template `org-log-note-headings'
2823 This option can also be set with on a per-file-basis with
2825 #+STARTUP: nologdone
2826 #+STARTUP: logdone
2827 #+STARTUP: lognotedone
2829 You can have local logging settings for a subtree by setting the LOGGING
2830 property to one or more of these keywords."
2831 :group 'org-todo
2832 :group 'org-progress
2833 :type '(choice
2834 (const :tag "No logging" nil)
2835 (const :tag "Record CLOSED timestamp" time)
2836 (const :tag "Record CLOSED timestamp with note." note)))
2838 ;; Normalize old uses of org-log-done.
2839 (cond
2840 ((eq org-log-done t) (setq org-log-done 'time))
2841 ((and (listp org-log-done) (memq 'done org-log-done))
2842 (setq org-log-done 'note)))
2844 (defcustom org-log-reschedule nil
2845 "Information to record when the scheduling date of a tasks is modified.
2847 Possible values are:
2849 nil Don't add anything, just change the date
2850 time Add a time stamp to the task
2851 note Prompt for a note and add it with template `org-log-note-headings'
2853 This option can also be set with on a per-file-basis with
2855 #+STARTUP: nologreschedule
2856 #+STARTUP: logreschedule
2857 #+STARTUP: lognotereschedule"
2858 :group 'org-todo
2859 :group 'org-progress
2860 :type '(choice
2861 (const :tag "No logging" nil)
2862 (const :tag "Record timestamp" time)
2863 (const :tag "Record timestamp with note." note)))
2865 (defcustom org-log-redeadline nil
2866 "Information to record when the deadline date of a tasks is modified.
2868 Possible values are:
2870 nil Don't add anything, just change the date
2871 time Add a time stamp to the task
2872 note Prompt for a note and add it with template `org-log-note-headings'
2874 This option can also be set with on a per-file-basis with
2876 #+STARTUP: nologredeadline
2877 #+STARTUP: logredeadline
2878 #+STARTUP: lognoteredeadline
2880 You can have local logging settings for a subtree by setting the LOGGING
2881 property to one or more of these keywords."
2882 :group 'org-todo
2883 :group 'org-progress
2884 :type '(choice
2885 (const :tag "No logging" nil)
2886 (const :tag "Record timestamp" time)
2887 (const :tag "Record timestamp with note." note)))
2889 (defcustom org-log-note-clock-out nil
2890 "Non-nil means record a note when clocking out of an item.
2891 This can also be configured on a per-file basis by adding one of
2892 the following lines anywhere in the buffer:
2894 #+STARTUP: lognoteclock-out
2895 #+STARTUP: nolognoteclock-out"
2896 :group 'org-todo
2897 :group 'org-progress
2898 :type 'boolean)
2900 (defcustom org-log-done-with-time t
2901 "Non-nil means the CLOSED time stamp will contain date and time.
2902 When nil, only the date will be recorded."
2903 :group 'org-progress
2904 :type 'boolean)
2906 (defcustom org-log-note-headings
2907 '((done . "CLOSING NOTE %t")
2908 (state . "State %-12s from %-12S %t")
2909 (note . "Note taken on %t")
2910 (reschedule . "Rescheduled from %S on %t")
2911 (delschedule . "Not scheduled, was %S on %t")
2912 (redeadline . "New deadline from %S on %t")
2913 (deldeadline . "Removed deadline, was %S on %t")
2914 (refile . "Refiled on %t")
2915 (clock-out . ""))
2916 "Headings for notes added to entries.
2918 The value is an alist, with the car being a symbol indicating the
2919 note context, and the cdr is the heading to be used. The heading
2920 may also be the empty string. The following placeholders can be
2921 used:
2923 %t a time stamp.
2924 %T an active time stamp instead the default inactive one
2925 %d a short-format time stamp.
2926 %D an active short-format time stamp.
2927 %s the new TODO state or time stamp (inactive), in double quotes.
2928 %S the old TODO state or time stamp (inactive), in double quotes.
2929 %u the user name.
2930 %U full user name.
2932 In fact, it is not a good idea to change the `state' entry,
2933 because Agenda Log mode depends on the format of these entries."
2934 :group 'org-todo
2935 :group 'org-progress
2936 :type '(list :greedy t
2937 (cons (const :tag "Heading when closing an item" done) string)
2938 (cons (const :tag
2939 "Heading when changing todo state (todo sequence only)"
2940 state) string)
2941 (cons (const :tag "Heading when just taking a note" note) string)
2942 (cons (const :tag "Heading when rescheduling" reschedule) string)
2943 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2944 (cons (const :tag "Heading when changing deadline" redeadline) string)
2945 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2946 (cons (const :tag "Heading when refiling" refile) string)
2947 (cons (const :tag "Heading when clocking out" clock-out) string)))
2949 (unless (assq 'note org-log-note-headings)
2950 (push '(note . "%t") org-log-note-headings))
2952 (defcustom org-log-into-drawer nil
2953 "Non-nil means insert state change notes and time stamps into a drawer.
2954 When nil, state changes notes will be inserted after the headline and
2955 any scheduling and clock lines, but not inside a drawer.
2957 The value of this variable should be the name of the drawer to use.
2958 LOGBOOK is proposed as the default drawer for this purpose, you can
2959 also set this to a string to define the drawer of your choice.
2961 A value of t is also allowed, representing \"LOGBOOK\".
2963 A value of t or nil can also be set with on a per-file-basis with
2965 #+STARTUP: logdrawer
2966 #+STARTUP: nologdrawer
2968 If this variable is set, `org-log-state-notes-insert-after-drawers'
2969 will be ignored.
2971 You can set the property LOG_INTO_DRAWER to overrule this setting for
2972 a subtree.
2974 Do not check directly this variable in a Lisp program. Call
2975 function `org-log-into-drawer' instead."
2976 :group 'org-todo
2977 :group 'org-progress
2978 :type '(choice
2979 (const :tag "Not into a drawer" nil)
2980 (const :tag "LOGBOOK" t)
2981 (string :tag "Other")))
2983 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2985 (defun org-log-into-drawer ()
2986 "Name of the log drawer, as a string, or nil.
2987 This is the value of `org-log-into-drawer'. However, if the
2988 current entry has or inherits a LOG_INTO_DRAWER property, it will
2989 be used instead of the default value."
2990 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2991 (cond ((equal p "nil") nil)
2992 ((equal p "t") "LOGBOOK")
2993 ((stringp p) p)
2994 (p "LOGBOOK")
2995 ((stringp org-log-into-drawer) org-log-into-drawer)
2996 (org-log-into-drawer "LOGBOOK"))))
2998 (defcustom org-log-state-notes-insert-after-drawers nil
2999 "Non-nil means insert state change notes after any drawers in entry.
3000 Only the drawers that *immediately* follow the headline and the
3001 deadline/scheduled line are skipped.
3002 When nil, insert notes right after the heading and perhaps the line
3003 with deadline/scheduling if present.
3005 This variable will have no effect if `org-log-into-drawer' is
3006 set."
3007 :group 'org-todo
3008 :group 'org-progress
3009 :type 'boolean)
3011 (defcustom org-log-states-order-reversed t
3012 "Non-nil means the latest state note will be directly after heading.
3013 When nil, the state change notes will be ordered according to time.
3015 This option can also be set with on a per-file-basis with
3017 #+STARTUP: logstatesreversed
3018 #+STARTUP: nologstatesreversed"
3019 :group 'org-todo
3020 :group 'org-progress
3021 :type 'boolean)
3023 (defcustom org-todo-repeat-to-state nil
3024 "The TODO state to which a repeater should return the repeating task.
3025 By default this is the first task of a TODO sequence or the
3026 previous state of a TYPE_TODO set. But you can specify to use
3027 the previous state in a TODO sequence or a string.
3029 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3030 entry, which has precedence over this option."
3031 :group 'org-todo
3032 :version "24.1"
3033 :type '(choice (const :tag "Use the previous TODO state" t)
3034 (const :tag "Use the head of the TODO sequence" nil)
3035 (string :tag "Use a specific TODO state")))
3037 (defcustom org-log-repeat 'time
3038 "Non-nil means record moving through the DONE state when triggering repeat.
3039 An auto-repeating task is immediately switched back to TODO when
3040 marked DONE. If you are not logging state changes (by adding \"@\"
3041 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3042 record a closing note, there will be no record of the task moving
3043 through DONE. This variable forces taking a note anyway.
3045 nil Don't force a record
3046 time Record a time stamp
3047 note Prompt for a note and add it with template `org-log-note-headings'
3049 This option can also be set with on a per-file-basis with
3051 #+STARTUP: nologrepeat
3052 #+STARTUP: logrepeat
3053 #+STARTUP: lognoterepeat
3055 You can have local logging settings for a subtree by setting the LOGGING
3056 property to one or more of these keywords."
3057 :group 'org-todo
3058 :group 'org-progress
3059 :type '(choice
3060 (const :tag "Don't force a record" nil)
3061 (const :tag "Force recording the DONE state" time)
3062 (const :tag "Force recording a note with the DONE state" note)))
3065 (defgroup org-priorities nil
3066 "Priorities in Org mode."
3067 :tag "Org Priorities"
3068 :group 'org-todo)
3070 (defcustom org-enable-priority-commands t
3071 "Non-nil means priority commands are active.
3072 When nil, these commands will be disabled, so that you never accidentally
3073 set a priority."
3074 :group 'org-priorities
3075 :type 'boolean)
3077 (defcustom org-highest-priority ?A
3078 "The highest priority of TODO items. A character like ?A, ?B etc.
3079 Must have a smaller ASCII number than `org-lowest-priority'."
3080 :group 'org-priorities
3081 :type 'character)
3083 (defcustom org-lowest-priority ?C
3084 "The lowest priority of TODO items. A character like ?A, ?B etc.
3085 Must have a larger ASCII number than `org-highest-priority'."
3086 :group 'org-priorities
3087 :type 'character)
3089 (defcustom org-default-priority ?B
3090 "The default priority of TODO items.
3091 This is the priority an item gets if no explicit priority is given.
3092 When starting to cycle on an empty priority the first step in the cycle
3093 depends on `org-priority-start-cycle-with-default'. The resulting first
3094 step priority must not exceed the range from `org-highest-priority' to
3095 `org-lowest-priority' which means that `org-default-priority' has to be
3096 in this range exclusive or inclusive the range boundaries. Else the
3097 first step refuses to set the default and the second will fall back
3098 to (depending on the command used) the highest or lowest priority."
3099 :group 'org-priorities
3100 :type 'character)
3102 (defcustom org-priority-start-cycle-with-default t
3103 "Non-nil means start with default priority when starting to cycle.
3104 When this is nil, the first step in the cycle will be (depending on the
3105 command used) one higher or lower than the default priority.
3106 See also `org-default-priority'."
3107 :group 'org-priorities
3108 :type 'boolean)
3110 (defcustom org-get-priority-function nil
3111 "Function to extract the priority from a string.
3112 The string is normally the headline. If this is nil Org computes the
3113 priority from the priority cookie like [#A] in the headline. It returns
3114 an integer, increasing by 1000 for each priority level.
3115 The user can set a different function here, which should take a string
3116 as an argument and return the numeric priority."
3117 :group 'org-priorities
3118 :version "24.1"
3119 :type '(choice
3120 (const nil)
3121 (function)))
3123 (defgroup org-time nil
3124 "Options concerning time stamps and deadlines in Org mode."
3125 :tag "Org Time"
3126 :group 'org)
3128 (defcustom org-time-stamp-rounding-minutes '(0 5)
3129 "Number of minutes to round time stamps to.
3130 \\<org-mode-map>\
3131 These are two values, the first applies when first creating a time stamp.
3132 The second applies when changing it with the commands `S-up' and `S-down'.
3133 When changing the time stamp, this means that it will change in steps
3134 of N minutes, as given by the second value.
3136 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3137 numbers should be factors of 60, so for example 5, 10, 15.
3139 When this is larger than 1, you can still force an exact time stamp by using
3140 a double prefix argument to a time stamp command like \
3141 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3142 and by using a prefix arg to `S-up/down' to specify the exact number
3143 of minutes to shift."
3144 :group 'org-time
3145 :get (lambda (var) ; Make sure both elements are there
3146 (if (integerp (default-value var))
3147 (list (default-value var) 5)
3148 (default-value var)))
3149 :type '(list
3150 (integer :tag "when inserting times")
3151 (integer :tag "when modifying times")))
3153 ;; Normalize old customizations of this variable.
3154 (when (integerp org-time-stamp-rounding-minutes)
3155 (setq org-time-stamp-rounding-minutes
3156 (list org-time-stamp-rounding-minutes
3157 org-time-stamp-rounding-minutes)))
3159 (defcustom org-display-custom-times nil
3160 "Non-nil means overlay custom formats over all time stamps.
3161 The formats are defined through the variable `org-time-stamp-custom-formats'.
3162 To turn this on on a per-file basis, insert anywhere in the file:
3163 #+STARTUP: customtime"
3164 :group 'org-time
3165 :set 'set-default
3166 :type 'sexp)
3167 (make-variable-buffer-local 'org-display-custom-times)
3169 (defcustom org-time-stamp-custom-formats
3170 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3171 "Custom formats for time stamps. See `format-time-string' for the syntax.
3172 These are overlaid over the default ISO format if the variable
3173 `org-display-custom-times' is set. Time like %H:%M should be at the
3174 end of the second format. The custom formats are also honored by export
3175 commands, if custom time display is turned on at the time of export."
3176 :group 'org-time
3177 :type 'sexp)
3179 (defun org-time-stamp-format (&optional long inactive)
3180 "Get the right format for a time string."
3181 (let ((f (if long (cdr org-time-stamp-formats)
3182 (car org-time-stamp-formats))))
3183 (if inactive
3184 (concat "[" (substring f 1 -1) "]")
3185 f)))
3187 (defcustom org-deadline-warning-days 14
3188 "Number of days before expiration during which a deadline becomes active.
3189 This variable governs the display in sparse trees and in the agenda.
3190 When 0 or negative, it means use this number (the absolute value of it)
3191 even if a deadline has a different individual lead time specified.
3193 Custom commands can set this variable in the options section."
3194 :group 'org-time
3195 :group 'org-agenda-daily/weekly
3196 :type 'integer)
3198 (defcustom org-scheduled-delay-days 0
3199 "Number of days before a scheduled item becomes active.
3200 This variable governs the display in sparse trees and in the agenda.
3201 The default value (i.e. 0) means: don't delay scheduled item.
3202 When negative, it means use this number (the absolute value of it)
3203 even if a scheduled item has a different individual delay time
3204 specified.
3206 Custom commands can set this variable in the options section."
3207 :group 'org-time
3208 :group 'org-agenda-daily/weekly
3209 :version "24.4"
3210 :package-version '(Org . "8.0")
3211 :type 'integer)
3213 (defcustom org-read-date-prefer-future t
3214 "Non-nil means assume future for incomplete date input from user.
3215 This affects the following situations:
3216 1. The user gives a month but not a year.
3217 For example, if it is April and you enter \"feb 2\", this will be read
3218 as Feb 2, *next* year. \"May 5\", however, will be this year.
3219 2. The user gives a day, but no month.
3220 For example, if today is the 15th, and you enter \"3\", Org will read
3221 this as the third of *next* month. However, if you enter \"17\",
3222 it will be considered as *this* month.
3224 If you set this variable to the symbol `time', then also the following
3225 will work:
3227 3. If the user gives a time.
3228 If the time is before now, it will be interpreted as tomorrow.
3230 Currently none of this works for ISO week specifications.
3232 When this option is nil, the current day, month and year will always be
3233 used as defaults.
3235 See also `org-agenda-jump-prefer-future'."
3236 :group 'org-time
3237 :type '(choice
3238 (const :tag "Never" nil)
3239 (const :tag "Check month and day" t)
3240 (const :tag "Check month, day, and time" time)))
3242 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3243 "Should the agenda jump command prefer the future for incomplete dates?
3244 The default is to do the same as configured in `org-read-date-prefer-future'.
3245 But you can also set a deviating value here.
3246 This may t or nil, or the symbol `org-read-date-prefer-future'."
3247 :group 'org-agenda
3248 :group 'org-time
3249 :version "24.1"
3250 :type '(choice
3251 (const :tag "Use org-read-date-prefer-future"
3252 org-read-date-prefer-future)
3253 (const :tag "Never" nil)
3254 (const :tag "Always" t)))
3256 (defcustom org-read-date-force-compatible-dates t
3257 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3259 Depending on the system Emacs is running on, certain dates cannot
3260 be represented with the type used internally to represent time.
3261 Dates between 1970-1-1 and 2038-1-1 can always be represented
3262 correctly. Some systems allow for earlier dates, some for later,
3263 some for both. One way to find out it to insert any date into an
3264 Org buffer, putting the cursor on the year and hitting S-up and
3265 S-down to test the range.
3267 When this variable is set to t, the date/time prompt will not let
3268 you specify dates outside the 1970-2037 range, so it is certain that
3269 these dates will work in whatever version of Emacs you are
3270 running, and also that you can move a file from one Emacs implementation
3271 to another. WHenever Org is forcing the year for you, it will display
3272 a message and beep.
3274 When this variable is nil, Org will check if the date is
3275 representable in the specific Emacs implementation you are using.
3276 If not, it will force a year, usually the current year, and beep
3277 to remind you. Currently this setting is not recommended because
3278 the likelihood that you will open your Org files in an Emacs that
3279 has limited date range is not negligible.
3281 A workaround for this problem is to use diary sexp dates for time
3282 stamps outside of this range."
3283 :group 'org-time
3284 :version "24.1"
3285 :type 'boolean)
3287 (defcustom org-read-date-display-live t
3288 "Non-nil means display current interpretation of date prompt live.
3289 This display will be in an overlay, in the minibuffer."
3290 :group 'org-time
3291 :type 'boolean)
3293 (defcustom org-read-date-popup-calendar t
3294 "Non-nil means pop up a calendar when prompting for a date.
3295 In the calendar, the date can be selected with mouse-1. However, the
3296 minibuffer will also be active, and you can simply enter the date as well.
3297 When nil, only the minibuffer will be available."
3298 :group 'org-time
3299 :type 'boolean)
3300 (defvaralias 'org-popup-calendar-for-date-prompt
3301 'org-read-date-popup-calendar)
3303 (defcustom org-extend-today-until 0
3304 "The hour when your day really ends. Must be an integer.
3305 This has influence for the following applications:
3306 - When switching the agenda to \"today\". It it is still earlier than
3307 the time given here, the day recognized as TODAY is actually yesterday.
3308 - When a date is read from the user and it is still before the time given
3309 here, the current date and time will be assumed to be yesterday, 23:59.
3310 Also, timestamps inserted in capture templates follow this rule.
3312 IMPORTANT: This is a feature whose implementation is and likely will
3313 remain incomplete. Really, it is only here because past midnight seems to
3314 be the favorite working time of John Wiegley :-)"
3315 :group 'org-time
3316 :type 'integer)
3318 (defcustom org-use-effective-time nil
3319 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3320 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3321 \"effective time\" of any timestamps between midnight and 8am will be
3322 23:59 of the previous day."
3323 :group 'org-time
3324 :version "24.1"
3325 :type 'boolean)
3327 (defcustom org-use-last-clock-out-time-as-effective-time nil
3328 "When non-nil, use the last clock out time for `org-todo'.
3329 Note that this option has precedence over the combined use of
3330 `org-use-effective-time' and `org-extend-today-until'."
3331 :group 'org-time
3332 :version "24.4"
3333 :package-version '(Org . "8.0")
3334 :type 'boolean)
3336 (defcustom org-edit-timestamp-down-means-later nil
3337 "Non-nil means S-down will increase the time in a time stamp.
3338 When nil, S-up will increase."
3339 :group 'org-time
3340 :type 'boolean)
3342 (defcustom org-calendar-follow-timestamp-change t
3343 "Non-nil means make the calendar window follow timestamp changes.
3344 When a timestamp is modified and the calendar window is visible, it will be
3345 moved to the new date."
3346 :group 'org-time
3347 :type 'boolean)
3349 (defgroup org-tags nil
3350 "Options concerning tags in Org mode."
3351 :tag "Org Tags"
3352 :group 'org)
3354 (defcustom org-tag-alist nil
3355 "Default tags available in Org files.
3357 The value of this variable is an alist. Associations either:
3359 (TAG)
3360 (TAG . SELECT)
3361 (SPECIAL)
3363 where TAG is a tag as a string, SELECT is character, used to
3364 select that tag through the fast tag selection interface, and
3365 SPECIAL is one of the following keywords: `:startgroup',
3366 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3367 `:newline'. These keywords are used to define a hierarchy of
3368 tags. See manual for details.
3370 When this variable is nil, Org mode bases tag input on what is
3371 already in the buffer. The value can be overridden locally by
3372 using a TAGS keyword, e.g.,
3374 #+TAGS: tag1 tag2
3376 See also `org-tag-persistent-alist' to sidestep this behavior."
3377 :group 'org-tags
3378 :type '(repeat
3379 (choice
3380 (cons :tag "Tag with key"
3381 (string :tag "Tag name")
3382 (character :tag "Access char"))
3383 (list :tag "Tag" (string :tag "Tag name"))
3384 (const :tag "Start radio group" (:startgroup))
3385 (const :tag "Start tag group, non distinct" (:startgrouptag))
3386 (const :tag "Group tags delimiter" (:grouptags))
3387 (const :tag "End radio group" (:endgroup))
3388 (const :tag "End tag group, non distinct" (:endgrouptag))
3389 (const :tag "New line" (:newline)))))
3391 (defcustom org-tag-persistent-alist nil
3392 "Tags always available in Org files.
3394 The value of this variable is an alist. Associations either:
3396 (TAG)
3397 (TAG . SELECT)
3398 (SPECIAL)
3400 where TAG is a tag as a string, SELECT is a character, used to
3401 select that tag through the fast tag selection interface, and
3402 SPECIAL is one of the following keywords: `:startgroup',
3403 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3404 `:newline'. These keywords are used to define a hierarchy of
3405 tags. See manual for details.
3407 Unlike to `org-tag-alist', tags defined in this variable do not
3408 depend on a local TAGS keyword. Instead, to disable these tags
3409 on a per-file basis, insert anywhere in the file:
3411 #+STARTUP: noptag"
3412 :group 'org-tags
3413 :type '(repeat
3414 (choice
3415 (cons :tag "Tag with key"
3416 (string :tag "Tag name")
3417 (character :tag "Access char"))
3418 (list :tag "Tag" (string :tag "Tag name"))
3419 (const :tag "Start radio group" (:startgroup))
3420 (const :tag "Start tag group, non distinct" (:startgrouptag))
3421 (const :tag "Group tags delimiter" (:grouptags))
3422 (const :tag "End radio group" (:endgroup))
3423 (const :tag "End tag group, non distinct" (:endgrouptag))
3424 (const :tag "New line" (:newline)))))
3426 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3427 "If non-nil, always offer completion for all tags of all agenda files.
3428 Instead of customizing this variable directly, you might want to
3429 set it locally for capture buffers, because there no list of
3430 tags in that file can be created dynamically (there are none).
3432 (add-hook \\='org-capture-mode-hook
3433 (lambda ()
3434 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3435 :group 'org-tags
3436 :version "24.1"
3437 :type 'boolean)
3439 (defvar org-file-tags nil
3440 "List of tags that can be inherited by all entries in the file.
3441 The tags will be inherited if the variable `org-use-tag-inheritance'
3442 says they should be.
3443 This variable is populated from #+FILETAGS lines.")
3445 (defcustom org-use-fast-tag-selection 'auto
3446 "Non-nil means use fast tag selection scheme.
3447 This is a special interface to select and deselect tags with single keys.
3448 When nil, fast selection is never used.
3449 When the symbol `auto', fast selection is used if and only if selection
3450 characters for tags have been configured, either through the variable
3451 `org-tag-alist' or through a #+TAGS line in the buffer.
3452 When t, fast selection is always used and selection keys are assigned
3453 automatically if necessary."
3454 :group 'org-tags
3455 :type '(choice
3456 (const :tag "Always" t)
3457 (const :tag "Never" nil)
3458 (const :tag "When selection characters are configured" auto)))
3460 (defcustom org-fast-tag-selection-single-key nil
3461 "Non-nil means fast tag selection exits after first change.
3462 When nil, you have to press RET to exit it.
3463 During fast tag selection, you can toggle this flag with `C-c'.
3464 This variable can also have the value `expert'. In this case, the window
3465 displaying the tags menu is not even shown, until you press C-c again."
3466 :group 'org-tags
3467 :type '(choice
3468 (const :tag "No" nil)
3469 (const :tag "Yes" t)
3470 (const :tag "Expert" expert)))
3472 (defvar org-fast-tag-selection-include-todo nil
3473 "Non-nil means fast tags selection interface will also offer TODO states.
3474 This is an undocumented feature, you should not rely on it.")
3476 (defcustom org-tags-column -77
3477 "The column to which tags should be indented in a headline.
3478 If this number is positive, it specifies the column. If it is negative,
3479 it means that the tags should be flushright to that column. For example,
3480 -80 works well for a normal 80 character screen.
3481 When 0, place tags directly after headline text, with only one space in
3482 between."
3483 :group 'org-tags
3484 :type 'integer)
3486 (defcustom org-auto-align-tags t
3487 "Non-nil keeps tags aligned when modifying headlines.
3488 Some operations (i.e. demoting) change the length of a headline and
3489 therefore shift the tags around. With this option turned on, after
3490 each such operation the tags are again aligned to `org-tags-column'."
3491 :group 'org-tags
3492 :type 'boolean)
3494 (defcustom org-use-tag-inheritance t
3495 "Non-nil means tags in levels apply also for sublevels.
3496 When nil, only the tags directly given in a specific line apply there.
3497 This may also be a list of tags that should be inherited, or a regexp that
3498 matches tags that should be inherited. Additional control is possible
3499 with the variable `org-tags-exclude-from-inheritance' which gives an
3500 explicit list of tags to be excluded from inheritance, even if the value of
3501 `org-use-tag-inheritance' would select it for inheritance.
3503 If this option is t, a match early-on in a tree can lead to a large
3504 number of matches in the subtree when constructing the agenda or creating
3505 a sparse tree. If you only want to see the first match in a tree during
3506 a search, check out the variable `org-tags-match-list-sublevels'."
3507 :group 'org-tags
3508 :type '(choice
3509 (const :tag "Not" nil)
3510 (const :tag "Always" t)
3511 (repeat :tag "Specific tags" (string :tag "Tag"))
3512 (regexp :tag "Tags matched by regexp")))
3514 (defcustom org-tags-exclude-from-inheritance nil
3515 "List of tags that should never be inherited.
3516 This is a way to exclude a few tags from inheritance. For way to do
3517 the opposite, to actively allow inheritance for selected tags,
3518 see the variable `org-use-tag-inheritance'."
3519 :group 'org-tags
3520 :type '(repeat (string :tag "Tag")))
3522 (defun org-tag-inherit-p (tag)
3523 "Check if TAG is one that should be inherited."
3524 (cond
3525 ((member tag org-tags-exclude-from-inheritance) nil)
3526 ((eq org-use-tag-inheritance t) t)
3527 ((not org-use-tag-inheritance) nil)
3528 ((stringp org-use-tag-inheritance)
3529 (string-match org-use-tag-inheritance tag))
3530 ((listp org-use-tag-inheritance)
3531 (member tag org-use-tag-inheritance))
3532 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3534 (defcustom org-tags-match-list-sublevels t
3535 "Non-nil means list also sublevels of headlines matching a search.
3536 This variable applies to tags/property searches, and also to stuck
3537 projects because this search is based on a tags match as well.
3539 When set to the symbol `indented', sublevels are indented with
3540 leading dots.
3542 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3543 the sublevels of a headline matching a tag search often also match
3544 the same search. Listing all of them can create very long lists.
3545 Setting this variable to nil causes subtrees of a match to be skipped.
3547 This variable is semi-obsolete and probably should always be true. It
3548 is better to limit inheritance to certain tags using the variables
3549 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3550 :group 'org-tags
3551 :type '(choice
3552 (const :tag "No, don't list them" nil)
3553 (const :tag "Yes, do list them" t)
3554 (const :tag "List them, indented with leading dots" indented)))
3556 (defcustom org-tags-sort-function nil
3557 "When set, tags are sorted using this function as a comparator."
3558 :group 'org-tags
3559 :type '(choice
3560 (const :tag "No sorting" nil)
3561 (const :tag "Alphabetical" string<)
3562 (const :tag "Reverse alphabetical" string>)
3563 (function :tag "Custom function" nil)))
3565 (defvar org-tags-history nil
3566 "History of minibuffer reads for tags.")
3567 (defvar org-last-tags-completion-table nil
3568 "The last used completion table for tags.")
3569 (defvar org-after-tags-change-hook nil
3570 "Hook that is run after the tags in a line have changed.")
3572 (defgroup org-properties nil
3573 "Options concerning properties in Org mode."
3574 :tag "Org Properties"
3575 :group 'org)
3577 (defcustom org-property-format "%-10s %s"
3578 "How property key/value pairs should be formatted by `indent-line'.
3579 When `indent-line' hits a property definition, it will format the line
3580 according to this format, mainly to make sure that the values are
3581 lined-up with respect to each other."
3582 :group 'org-properties
3583 :type 'string)
3585 (defcustom org-properties-postprocess-alist nil
3586 "Alist of properties and functions to adjust inserted values.
3587 Elements of this alist must be of the form
3589 ([string] [function])
3591 where [string] must be a property name and [function] must be a
3592 lambda expression: this lambda expression must take one argument,
3593 the value to adjust, and return the new value as a string.
3595 For example, this element will allow the property \"Remaining\"
3596 to be updated wrt the relation between the \"Effort\" property
3597 and the clock summary:
3599 ((\"Remaining\" (lambda(value)
3600 (let ((clocksum (org-clock-sum-current-item))
3601 (effort (org-duration-to-minutes
3602 (org-entry-get (point) \"Effort\"))))
3603 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3604 :group 'org-properties
3605 :version "24.1"
3606 :type '(alist :key-type (string :tag "Property")
3607 :value-type (function :tag "Function")))
3609 (defcustom org-use-property-inheritance nil
3610 "Non-nil means properties apply also for sublevels.
3612 This setting is chiefly used during property searches. Turning it on can
3613 cause significant overhead when doing a search, which is why it is not
3614 on by default.
3616 When nil, only the properties directly given in the current entry count.
3617 When t, every property is inherited. The value may also be a list of
3618 properties that should have inheritance, or a regular expression matching
3619 properties that should be inherited.
3621 However, note that some special properties use inheritance under special
3622 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3623 and the properties ending in \"_ALL\" when they are used as descriptor
3624 for valid values of a property.
3626 Note for programmers:
3627 When querying an entry with `org-entry-get', you can control if inheritance
3628 should be used. By default, `org-entry-get' looks only at the local
3629 properties. You can request inheritance by setting the inherit argument
3630 to t (to force inheritance) or to `selective' (to respect the setting
3631 in this variable)."
3632 :group 'org-properties
3633 :type '(choice
3634 (const :tag "Not" nil)
3635 (const :tag "Always" t)
3636 (repeat :tag "Specific properties" (string :tag "Property"))
3637 (regexp :tag "Properties matched by regexp")))
3639 (defun org-property-inherit-p (property)
3640 "Return a non-nil value if PROPERTY should be inherited."
3641 (cond
3642 ((eq org-use-property-inheritance t) t)
3643 ((not org-use-property-inheritance) nil)
3644 ((stringp org-use-property-inheritance)
3645 (string-match org-use-property-inheritance property))
3646 ((listp org-use-property-inheritance)
3647 (member-ignore-case property org-use-property-inheritance))
3648 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3650 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3651 "The default column format, if no other format has been defined.
3652 This variable can be set on the per-file basis by inserting a line
3654 #+COLUMNS: %25ITEM ....."
3655 :group 'org-properties
3656 :type 'string)
3658 (defcustom org-columns-ellipses ".."
3659 "The ellipses to be used when a field in column view is truncated.
3660 When this is the empty string, as many characters as possible are shown,
3661 but then there will be no visual indication that the field has been truncated.
3662 When this is a string of length N, the last N characters of a truncated
3663 field are replaced by this string. If the column is narrower than the
3664 ellipses string, only part of the ellipses string will be shown."
3665 :group 'org-properties
3666 :type 'string)
3668 (defconst org-global-properties-fixed
3669 '(("VISIBILITY_ALL" . "folded children content all")
3670 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3671 "List of property/value pairs that can be inherited by any entry.
3673 These are fixed values, for the preset properties. The user variable
3674 that can be used to add to this list is `org-global-properties'.
3676 The entries in this list are cons cells where the car is a property
3677 name and cdr is a string with the value. If the value represents
3678 multiple items like an \"_ALL\" property, separate the items by
3679 spaces.")
3681 (defcustom org-global-properties nil
3682 "List of property/value pairs that can be inherited by any entry.
3684 This list will be combined with the constant `org-global-properties-fixed'.
3686 The entries in this list are cons cells where the car is a property
3687 name and cdr is a string with the value.
3689 You can set buffer-local values for the same purpose in the variable
3690 `org-file-properties' this by adding lines like
3692 #+PROPERTY: NAME VALUE"
3693 :group 'org-properties
3694 :type '(repeat
3695 (cons (string :tag "Property")
3696 (string :tag "Value"))))
3698 (defvar-local org-file-properties nil
3699 "List of property/value pairs that can be inherited by any entry.
3700 Valid for the current buffer.
3701 This variable is populated from #+PROPERTY lines.")
3703 (defgroup org-agenda nil
3704 "Options concerning agenda views in Org mode."
3705 :tag "Org Agenda"
3706 :group 'org)
3708 (defvar-local org-category nil
3709 "Variable used by Org files to set a category for agenda display.
3710 Such files should use a file variable to set it, for example
3712 # -*- mode: org; org-category: \"ELisp\"
3714 or contain a special line
3716 #+CATEGORY: ELisp
3718 If the file does not specify a category, then file's base name
3719 is used instead.")
3720 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3722 (defcustom org-agenda-files nil
3723 "The files to be used for agenda display.
3725 If an entry is a directory, all files in that directory that are matched
3726 by `org-agenda-file-regexp' will be part of the file list.
3728 If the value of the variable is not a list but a single file name, then
3729 the list of agenda files is actually stored and maintained in that file,
3730 one agenda file per line. In this file paths can be given relative to
3731 `org-directory'. Tilde expansion and environment variable substitution
3732 are also made.
3734 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3735 and removed with `\\[org-remove-file]'."
3736 :group 'org-agenda
3737 :type '(choice
3738 (repeat :tag "List of files and directories" file)
3739 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3741 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3742 "Regular expression to match files for `org-agenda-files'.
3743 If any element in the list in that variable contains a directory instead
3744 of a normal file, all files in that directory that are matched by this
3745 regular expression will be included."
3746 :group 'org-agenda
3747 :type 'regexp)
3749 (defcustom org-agenda-text-search-extra-files nil
3750 "List of extra files to be searched by text search commands.
3751 These files will be searched in addition to the agenda files by the
3752 commands `org-search-view' (`\\[org-agenda] s') \
3753 and `org-occur-in-agenda-files'.
3754 Note that these files will only be searched for text search commands,
3755 not for the other agenda views like todo lists, tag searches or the weekly
3756 agenda. This variable is intended to list notes and possibly archive files
3757 that should also be searched by these two commands.
3758 In fact, if the first element in the list is the symbol `agenda-archives',
3759 then all archive files of all agenda files will be added to the search
3760 scope."
3761 :group 'org-agenda
3762 :type '(set :greedy t
3763 (const :tag "Agenda Archives" agenda-archives)
3764 (repeat :inline t (file))))
3766 (defvaralias 'org-agenda-multi-occur-extra-files
3767 'org-agenda-text-search-extra-files)
3769 (defcustom org-agenda-skip-unavailable-files nil
3770 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3771 A nil value means to remove them, after a query, from the list."
3772 :group 'org-agenda
3773 :type 'boolean)
3775 (defcustom org-agenda-diary-file 'diary-file
3776 "File to which to add new entries with the `i' key in agenda and calendar.
3777 When this is the symbol `diary-file', the functionality in the Emacs
3778 calendar will be used to add entries to the `diary-file'. But when this
3779 points to a file, `org-agenda-diary-entry' will be used instead."
3780 :group 'org-agenda
3781 :type '(choice
3782 (const :tag "The standard Emacs diary file" diary-file)
3783 (file :tag "Special Org file diary entries")))
3785 (defgroup org-latex nil
3786 "Options for embedding LaTeX code into Org mode."
3787 :tag "Org LaTeX"
3788 :group 'org)
3790 (defcustom org-format-latex-options
3791 '(:foreground default :background default :scale 1.0
3792 :html-foreground "Black" :html-background "Transparent"
3793 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3794 "Options for creating images from LaTeX fragments.
3795 This is a property list with the following properties:
3796 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3797 `default' means use the foreground of the default face.
3798 `auto' means use the foreground from the text face.
3799 :background the background color, or \"Transparent\".
3800 `default' means use the background of the default face.
3801 `auto' means use the background from the text face.
3802 :scale a scaling factor for the size of the images, to get more pixels
3803 :html-foreground, :html-background, :html-scale
3804 the same numbers for HTML export.
3805 :matchers a list indicating which matchers should be used to
3806 find LaTeX fragments. Valid members of this list are:
3807 \"begin\" find environments
3808 \"$1\" find single characters surrounded by $.$
3809 \"$\" find math expressions surrounded by $...$
3810 \"$$\" find math expressions surrounded by $$....$$
3811 \"\\(\" find math expressions surrounded by \\(...\\)
3812 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3813 :group 'org-latex
3814 :type 'plist)
3816 (defcustom org-format-latex-signal-error t
3817 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3818 When nil, just push out a message."
3819 :group 'org-latex
3820 :version "24.1"
3821 :type 'boolean)
3823 (defcustom org-latex-to-mathml-jar-file nil
3824 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3825 Use this to specify additional executable file say a jar file.
3827 When using MathToWeb as the converter, specify the full-path to
3828 your mathtoweb.jar file."
3829 :group 'org-latex
3830 :version "24.1"
3831 :type '(choice
3832 (const :tag "None" nil)
3833 (file :tag "JAR file" :must-match t)))
3835 (defcustom org-latex-to-mathml-convert-command nil
3836 "Command to convert LaTeX fragments to MathML.
3837 Replace format-specifiers in the command as noted below and use
3838 `shell-command' to convert LaTeX to MathML.
3839 %j: Executable file in fully expanded form as specified by
3840 `org-latex-to-mathml-jar-file'.
3841 %I: Input LaTeX file in fully expanded form.
3842 %i: The latex fragment to be converted.
3843 %o: Output MathML file.
3845 This command is used by `org-create-math-formula'.
3847 When using MathToWeb as the converter, set this option to
3848 \"java -jar %j -unicode -force -df %o %I\".
3850 When using LaTeXML set this option to
3851 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3852 :group 'org-latex
3853 :version "24.1"
3854 :type '(choice
3855 (const :tag "None" nil)
3856 (string :tag "\nShell command")))
3858 (defcustom org-preview-latex-default-process 'dvipng
3859 "The default process to convert LaTeX fragments to image files.
3860 All available processes and theirs documents can be found in
3861 `org-preview-latex-process-alist', which see."
3862 :group 'org-latex
3863 :version "26.1"
3864 :package-version '(Org . "9.0")
3865 :type 'symbol)
3867 (defcustom org-preview-latex-process-alist
3868 '((dvipng
3869 :programs ("latex" "dvipng")
3870 :description "dvi > png"
3871 :message "you need to install the programs: latex and dvipng."
3872 :image-input-type "dvi"
3873 :image-output-type "png"
3874 :image-size-adjust (1.0 . 1.0)
3875 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3876 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3877 (dvisvgm
3878 :programs ("latex" "dvisvgm")
3879 :description "dvi > svg"
3880 :message "you need to install the programs: latex and dvisvgm."
3881 :use-xcolor t
3882 :image-input-type "dvi"
3883 :image-output-type "svg"
3884 :image-size-adjust (1.7 . 1.5)
3885 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3886 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3887 (imagemagick
3888 :programs ("latex" "convert")
3889 :description "pdf > png"
3890 :message "you need to install the programs: latex and imagemagick."
3891 :use-xcolor t
3892 :image-input-type "pdf"
3893 :image-output-type "png"
3894 :image-size-adjust (1.0 . 1.0)
3895 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3896 :image-converter
3897 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3898 "Definitions of external processes for LaTeX previewing.
3899 Org mode can use some external commands to generate TeX snippet's images for
3900 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3901 `org-create-formula-image' how to call them.
3903 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3904 PROPERTIES accepts the following attributes:
3906 :programs list of strings, required programs.
3907 :description string, describe the process.
3908 :message string, message it when required programs cannot be found.
3909 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3910 :image-output-type string, output file type of image converter (e.g., \"png\").
3911 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3912 deal with background and foreground color of image.
3913 Otherwise, dvipng style background and foreground color
3914 format are generated. You may then refer to them in
3915 command options with \"%F\" and \"%B\".
3916 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3917 image size showed in buffer and the cdr element is for
3918 HTML file. This option is only useful for process
3919 developers, users should use variable
3920 `org-format-latex-options' instead.
3921 :post-clean list of strings, files matched are to be cleaned up once
3922 the image is generated. When nil, the files with \".dvi\",
3923 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3924 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3925 be cleaned up.
3926 :latex-header list of strings, the LaTeX header of the snippet file.
3927 When nil, the fallback value is used instead, which is
3928 controlled by `org-format-latex-header',
3929 `org-latex-default-packages-alist' and
3930 `org-latex-packages-alist', which see.
3931 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3932 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3933 replaced with values defined below.
3934 :image-converter list of image converter commands strings. Each of them is
3935 given to the shell and supports any of the following
3936 place-holders defined below.
3938 Place-holders used by `:image-converter' and `:latex-compiler':
3940 %f input file name
3941 %b base name of input file
3942 %o base directory of input file
3943 %O absolute output file name
3945 Place-holders only used by `:image-converter':
3947 %F foreground of image
3948 %B background of image
3949 %D dpi, which is used to adjust image size by some processing commands.
3950 %S the image size scale ratio, which is used to adjust image size by some
3951 processing commands."
3952 :group 'org-latex
3953 :version "26.1"
3954 :package-version '(Org . "9.0")
3955 :type '(alist :tag "LaTeX to image backends"
3956 :value-type (plist)))
3958 (defcustom org-preview-latex-image-directory "ltximg/"
3959 "Path to store latex preview images.
3960 A relative path here creates many directories relative to the
3961 processed Org files paths. An absolute path puts all preview
3962 images at the same place."
3963 :group 'org-latex
3964 :version "26.1"
3965 :package-version '(Org . "9.0")
3966 :type 'string)
3968 (defun org-format-latex-mathml-available-p ()
3969 "Return t if `org-latex-to-mathml-convert-command' is usable."
3970 (save-match-data
3971 (when (and (boundp 'org-latex-to-mathml-convert-command)
3972 org-latex-to-mathml-convert-command)
3973 (let ((executable (car (split-string
3974 org-latex-to-mathml-convert-command))))
3975 (when (executable-find executable)
3976 (if (string-match
3977 "%j" org-latex-to-mathml-convert-command)
3978 (file-readable-p org-latex-to-mathml-jar-file)
3979 t))))))
3981 (defcustom org-format-latex-header "\\documentclass{article}
3982 \\usepackage[usenames]{color}
3983 \[PACKAGES]
3984 \[DEFAULT-PACKAGES]
3985 \\pagestyle{empty} % do not remove
3986 % The settings below are copied from fullpage.sty
3987 \\setlength{\\textwidth}{\\paperwidth}
3988 \\addtolength{\\textwidth}{-3cm}
3989 \\setlength{\\oddsidemargin}{1.5cm}
3990 \\addtolength{\\oddsidemargin}{-2.54cm}
3991 \\setlength{\\evensidemargin}{\\oddsidemargin}
3992 \\setlength{\\textheight}{\\paperheight}
3993 \\addtolength{\\textheight}{-\\headheight}
3994 \\addtolength{\\textheight}{-\\headsep}
3995 \\addtolength{\\textheight}{-\\footskip}
3996 \\addtolength{\\textheight}{-3cm}
3997 \\setlength{\\topmargin}{1.5cm}
3998 \\addtolength{\\topmargin}{-2.54cm}"
3999 "The document header used for processing LaTeX fragments.
4000 It is imperative that this header make sure that no page number
4001 appears on the page. The package defined in the variables
4002 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4003 will either replace the placeholder \"[PACKAGES]\" in this
4004 header, or they will be appended."
4005 :group 'org-latex
4006 :type 'string)
4008 (defun org-set-packages-alist (var val)
4009 "Set the packages alist and make sure it has 3 elements per entry."
4010 (set var (mapcar (lambda (x)
4011 (if (and (consp x) (= (length x) 2))
4012 (list (car x) (nth 1 x) t)
4014 val)))
4016 (defun org-get-packages-alist (var)
4017 "Get the packages alist and make sure it has 3 elements per entry."
4018 (mapcar (lambda (x)
4019 (if (and (consp x) (= (length x) 2))
4020 (list (car x) (nth 1 x) t)
4022 (default-value var)))
4024 (defcustom org-latex-default-packages-alist
4025 '(("AUTO" "inputenc" t ("pdflatex"))
4026 ("T1" "fontenc" t ("pdflatex"))
4027 ("" "graphicx" t)
4028 ("" "grffile" t)
4029 ("" "longtable" nil)
4030 ("" "wrapfig" nil)
4031 ("" "rotating" nil)
4032 ("normalem" "ulem" t)
4033 ("" "amsmath" t)
4034 ("" "textcomp" t)
4035 ("" "amssymb" t)
4036 ("" "capt-of" nil)
4037 ("" "hyperref" nil))
4038 "Alist of default packages to be inserted in the header.
4040 Change this only if one of the packages here causes an
4041 incompatibility with another package you are using.
4043 The packages in this list are needed by one part or another of
4044 Org mode to function properly:
4046 - inputenc, fontenc: for basic font and character selection
4047 - graphicx: for including images
4048 - grffile: allow periods and spaces in graphics file names
4049 - longtable: For multipage tables
4050 - wrapfig: for figure placement
4051 - rotating: for sideways figures and tables
4052 - ulem: for underline and strike-through
4053 - amsmath: for subscript and superscript and math environments
4054 - textcomp, amssymb: for various symbols used
4055 for interpreting the entities in `org-entities'. You can skip
4056 some of these packages if you don't use any of their symbols.
4057 - capt-of: for captions outside of floats
4058 - hyperref: for cross references
4060 Therefore you should not modify this variable unless you know
4061 what you are doing. The one reason to change it anyway is that
4062 you might be loading some other package that conflicts with one
4063 of the default packages. Each element is either a cell or
4064 a string.
4066 A cell is of the format
4068 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4070 If SNIPPET-FLAG is non-nil, the package also needs to be included
4071 when compiling LaTeX snippets into images for inclusion into
4072 non-LaTeX output. COMPILERS is a list of compilers that should
4073 include the package, see `org-latex-compiler'. If the document
4074 compiler is not in the list, and the list is non-nil, the package
4075 will not be inserted in the final document.
4077 A string will be inserted as-is in the header of the document."
4078 :group 'org-latex
4079 :group 'org-export-latex
4080 :set 'org-set-packages-alist
4081 :get 'org-get-packages-alist
4082 :version "26.1"
4083 :package-version '(Org . "8.3")
4084 :type '(repeat
4085 (choice
4086 (list :tag "options/package pair"
4087 (string :tag "options")
4088 (string :tag "package")
4089 (boolean :tag "Snippet")
4090 (choice
4091 (const :tag "For all compilers" nil)
4092 (repeat :tag "Allowed compiler" string)))
4093 (string :tag "A line of LaTeX"))))
4095 (defcustom org-latex-packages-alist nil
4096 "Alist of packages to be inserted in every LaTeX header.
4098 These will be inserted after `org-latex-default-packages-alist'.
4099 Each element is either a cell or a string.
4101 A cell is of the format:
4103 (\"options\" \"package\" SNIPPET-FLAG)
4105 SNIPPET-FLAG, when non-nil, indicates that this package is also
4106 needed when turning LaTeX snippets into images for inclusion into
4107 non-LaTeX output.
4109 A string will be inserted as-is in the header of the document.
4111 Make sure that you only list packages here which:
4113 - you want in every file;
4114 - do not conflict with the setup in `org-format-latex-header';
4115 - do not conflict with the default packages in
4116 `org-latex-default-packages-alist'."
4117 :group 'org-latex
4118 :group 'org-export-latex
4119 :set 'org-set-packages-alist
4120 :get 'org-get-packages-alist
4121 :type '(repeat
4122 (choice
4123 (list :tag "options/package pair"
4124 (string :tag "options")
4125 (string :tag "package")
4126 (boolean :tag "Snippet"))
4127 (string :tag "A line of LaTeX"))))
4129 (defgroup org-appearance nil
4130 "Settings for Org mode appearance."
4131 :tag "Org Appearance"
4132 :group 'org)
4134 (defcustom org-level-color-stars-only nil
4135 "Non-nil means fontify only the stars in each headline.
4136 When nil, the entire headline is fontified.
4137 Changing it requires restart of `font-lock-mode' to become effective
4138 also in regions already fontified."
4139 :group 'org-appearance
4140 :type 'boolean)
4142 (defcustom org-hide-leading-stars nil
4143 "Non-nil means hide the first N-1 stars in a headline.
4144 This works by using the face `org-hide' for these stars. This
4145 face is white for a light background, and black for a dark
4146 background. You may have to customize the face `org-hide' to
4147 make this work.
4148 Changing it requires restart of `font-lock-mode' to become effective
4149 also in regions already fontified.
4150 You may also set this on a per-file basis by adding one of the following
4151 lines to the buffer:
4153 #+STARTUP: hidestars
4154 #+STARTUP: showstars"
4155 :group 'org-appearance
4156 :type 'boolean)
4158 (defcustom org-hidden-keywords nil
4159 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4160 For example, a value \\='(title) for this list makes the document's title
4161 appear in the buffer without the initial \"#+TITLE:\" part."
4162 :group 'org-appearance
4163 :version "24.1"
4164 :type '(set (const :tag "#+AUTHOR" author)
4165 (const :tag "#+DATE" date)
4166 (const :tag "#+EMAIL" email)
4167 (const :tag "#+TITLE" title)))
4169 (defcustom org-custom-properties nil
4170 "List of properties (as strings) with a special meaning.
4171 The default use of these custom properties is to let the user
4172 hide them with `org-toggle-custom-properties-visibility'."
4173 :group 'org-properties
4174 :group 'org-appearance
4175 :version "24.3"
4176 :type '(repeat (string :tag "Property Name")))
4178 (defcustom org-fontify-done-headline nil
4179 "Non-nil means change the face of a headline if it is marked DONE.
4180 Normally, only the TODO/DONE keyword indicates the state of a headline.
4181 When this is non-nil, the headline after the keyword is set to the
4182 `org-headline-done' as an additional indication."
4183 :group 'org-appearance
4184 :type 'boolean)
4186 (defcustom org-fontify-emphasized-text t
4187 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4188 Changing this variable requires a restart of Emacs to take effect."
4189 :group 'org-appearance
4190 :type 'boolean)
4192 (defcustom org-fontify-whole-heading-line nil
4193 "Non-nil means fontify the whole line for headings.
4194 This is useful when setting a background color for the
4195 org-level-* faces."
4196 :group 'org-appearance
4197 :type 'boolean)
4199 (defcustom org-highlight-latex-and-related nil
4200 "Non-nil means highlight LaTeX related syntax in the buffer.
4201 When non nil, the value should be a list containing any of the
4202 following symbols:
4203 `latex' Highlight LaTeX snippets and environments.
4204 `script' Highlight subscript and superscript.
4205 `entities' Highlight entities."
4206 :group 'org-appearance
4207 :version "24.4"
4208 :package-version '(Org . "8.0")
4209 :type '(choice
4210 (const :tag "No highlighting" nil)
4211 (set :greedy t :tag "Highlight"
4212 (const :tag "LaTeX snippets and environments" latex)
4213 (const :tag "Subscript and superscript" script)
4214 (const :tag "Entities" entities))))
4216 (defcustom org-hide-emphasis-markers nil
4217 "Non-nil mean font-lock should hide the emphasis marker characters."
4218 :group 'org-appearance
4219 :type 'boolean)
4221 (defcustom org-hide-macro-markers nil
4222 "Non-nil mean font-lock should hide the brackets marking macro calls."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-pretty-entities nil
4227 "Non-nil means show entities as UTF8 characters.
4228 When nil, the \\name form remains in the buffer."
4229 :group 'org-appearance
4230 :version "24.1"
4231 :type 'boolean)
4233 (defcustom org-pretty-entities-include-sub-superscripts t
4234 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4235 :group 'org-appearance
4236 :version "24.1"
4237 :type 'boolean)
4239 (defvar org-emph-re nil
4240 "Regular expression for matching emphasis.
4241 After a match, the match groups contain these elements:
4242 0 The match of the full regular expression, including the characters
4243 before and after the proper match
4244 1 The character before the proper match, or empty at beginning of line
4245 2 The proper match, including the leading and trailing markers
4246 3 The leading marker like * or /, indicating the type of highlighting
4247 4 The text between the emphasis markers, not including the markers
4248 5 The character after the match, empty at the end of a line")
4250 (defvar org-verbatim-re nil
4251 "Regular expression for matching verbatim text.")
4253 (defvar org-emphasis-regexp-components) ; defined just below
4254 (defvar org-emphasis-alist) ; defined just below
4255 (defun org-set-emph-re (var val)
4256 "Set variable and compute the emphasis regular expression."
4257 (set var val)
4258 (when (and (boundp 'org-emphasis-alist)
4259 (boundp 'org-emphasis-regexp-components)
4260 org-emphasis-alist org-emphasis-regexp-components)
4261 (pcase-let*
4262 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4263 (body (if (<= nl 0) body
4264 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4265 (template
4266 (format (concat "\\([%s]\\|^\\)" ;before markers
4267 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4268 "\\([%s]\\|$\\)") ;after markers
4269 pre border border body border post)))
4270 (setq org-emph-re (format template "*/_+"))
4271 (setq org-verbatim-re (format template "=~")))))
4273 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4274 ;; set this option proved cumbersome. See this message/thread:
4275 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4276 (defvar org-emphasis-regexp-components
4277 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4278 "Components used to build the regular expression for emphasis.
4279 This is a list with five entries. Terminology: In an emphasis string
4280 like \" *strong word* \", we call the initial space PREMATCH, the final
4281 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4282 and \"trong wor\" is the body. The different components in this variable
4283 specify what is allowed/forbidden in each part:
4285 pre Chars allowed as prematch. Beginning of line will be allowed too.
4286 post Chars allowed as postmatch. End of line will be allowed too.
4287 border The chars *forbidden* as border characters.
4288 body-regexp A regexp like \".\" to match a body character. Don't use
4289 non-shy groups here, and don't allow newline here.
4290 newline The maximum number of newlines allowed in an emphasis exp.
4292 You need to reload Org or to restart Emacs after setting this.")
4294 (defcustom org-emphasis-alist
4295 '(("*" bold)
4296 ("/" italic)
4297 ("_" underline)
4298 ("=" org-verbatim verbatim)
4299 ("~" org-code verbatim)
4300 ("+" (:strike-through t)))
4301 "Alist of characters and faces to emphasize text.
4302 Text starting and ending with a special character will be emphasized,
4303 for example *bold*, _underlined_ and /italic/. This variable sets the
4304 marker characters and the face to be used by font-lock for highlighting
4305 in Org buffers.
4307 You need to reload Org or to restart Emacs after customizing this."
4308 :group 'org-appearance
4309 :set 'org-set-emph-re
4310 :version "24.4"
4311 :package-version '(Org . "8.0")
4312 :type '(repeat
4313 (list
4314 (string :tag "Marker character")
4315 (choice
4316 (face :tag "Font-lock-face")
4317 (plist :tag "Face property list"))
4318 (option (const verbatim)))))
4320 (defvar org-protecting-blocks '("src" "example" "export")
4321 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4322 This is needed for font-lock setup.")
4324 ;;; Functions and variables from their packages
4325 ;; Declared here to avoid compiler warnings
4326 (defvar mark-active)
4328 ;; Various packages
4329 (declare-function calc-eval "calc" (str &optional separator &rest args))
4330 (declare-function calendar-forward-day "cal-move" (arg))
4331 (declare-function calendar-goto-date "cal-move" (date))
4332 (declare-function calendar-goto-today "cal-move" ())
4333 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4334 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4335 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4336 (declare-function cdlatex-tab "ext:cdlatex" ())
4337 (declare-function dired-get-filename
4338 "dired"
4339 (&optional localp no-error-if-not-filep))
4340 (declare-function iswitchb-read-buffer
4341 "iswitchb"
4342 (prompt &optional
4343 default require-match _predicate start matches-set))
4344 (declare-function org-agenda-change-all-lines
4345 "org-agenda"
4346 (newhead hdmarker &optional fixface just-this))
4347 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4348 "org-agenda"
4349 (&optional end))
4350 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4351 (declare-function org-agenda-format-item
4352 "org-agenda"
4353 (extra txt &optional level category tags dotime
4354 remove-re habitp))
4355 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4356 (declare-function org-agenda-save-markers-for-cut-and-paste
4357 "org-agenda"
4358 (beg end))
4359 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4360 (declare-function org-agenda-skip "org-agenda" ())
4361 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4362 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4363 (declare-function org-indent-mode "org-indent" (&optional arg))
4364 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4365 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4366 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4367 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4368 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4369 (declare-function parse-time-string "parse-time" (string))
4371 (defvar align-mode-rules-list)
4372 (defvar calc-embedded-close-formula)
4373 (defvar calc-embedded-open-formula)
4374 (defvar calc-embedded-open-mode)
4375 (defvar font-lock-unfontify-region-function)
4376 (defvar iswitchb-temp-buflist)
4377 (defvar org-agenda-tags-todo-honor-ignore-options)
4378 (defvar remember-data-file)
4379 (defvar texmathp-why)
4381 ;;;###autoload
4382 (defun turn-on-orgtbl ()
4383 "Unconditionally turn on `orgtbl-mode'."
4384 (require 'org-table)
4385 (orgtbl-mode 1))
4387 (defun org-at-table-p (&optional table-type)
4388 "Non-nil if the cursor is inside an Org table.
4389 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4390 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4391 (or (not (derived-mode-p 'org-mode))
4392 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4393 (and e (or table-type
4394 (eq 'org (org-element-property :type e))))))))
4396 (defun org-at-table.el-p ()
4397 "Non-nil when point is at a table.el table."
4398 (and (org-match-line "[ \t]*[|+]")
4399 (let ((element (org-element-at-point)))
4400 (and (eq (org-element-type element) 'table)
4401 (eq (org-element-property :type element) 'table.el)))))
4403 (defun org-at-table-hline-p ()
4404 "Non-nil when point is inside a hline in a table.
4405 Assume point is already in a table."
4406 (org-match-line org-table-hline-regexp))
4408 (defun org-table-map-tables (function &optional quietly)
4409 "Apply FUNCTION to the start of all tables in the buffer."
4410 (org-with-wide-buffer
4411 (goto-char (point-min))
4412 (while (re-search-forward org-table-any-line-regexp nil t)
4413 (unless quietly
4414 (message "Mapping tables: %d%%"
4415 (floor (* 100.0 (point)) (buffer-size))))
4416 (beginning-of-line 1)
4417 (when (and (looking-at org-table-line-regexp)
4418 ;; Exclude tables in src/example/verbatim/clocktable blocks
4419 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4420 (save-excursion (funcall function))
4421 (or (looking-at org-table-line-regexp)
4422 (forward-char 1)))
4423 (re-search-forward org-table-any-border-regexp nil 1)))
4424 (unless quietly (message "Mapping tables: done")))
4426 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4427 (declare-function org-clock-update-mode-line "org-clock" ())
4428 (declare-function org-resolve-clocks "org-clock"
4429 (&optional also-non-dangling-p prompt last-valid))
4431 (defun org-at-TBLFM-p (&optional pos)
4432 "Non-nil when point (or POS) is in #+TBLFM line."
4433 (save-excursion
4434 (goto-char (or pos (point)))
4435 (beginning-of-line)
4436 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4437 (eq (org-element-type (org-element-at-point)) 'table))))
4439 (defvar org-clock-start-time)
4440 (defvar org-clock-marker (make-marker)
4441 "Marker recording the last clock-in.")
4442 (defvar org-clock-hd-marker (make-marker)
4443 "Marker recording the last clock-in, but the headline position.")
4444 (defvar org-clock-heading ""
4445 "The heading of the current clock entry.")
4446 (defun org-clock-is-active ()
4447 "Return the buffer where the clock is currently running.
4448 Return nil if no clock is running."
4449 (marker-buffer org-clock-marker))
4451 (defun org-check-running-clock ()
4452 "Check if the current buffer contains the running clock.
4453 If yes, offer to stop it and to save the buffer with the changes."
4454 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4455 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4456 (buffer-name))))
4457 (org-clock-out)
4458 (when (y-or-n-p "Save changed buffer?")
4459 (save-buffer))))
4461 (defun org-clocktable-try-shift (dir n)
4462 "Check if this line starts a clock table, if yes, shift the time block."
4463 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4464 (org-clocktable-shift dir n)))
4466 ;;;###autoload
4467 (defun org-clock-persistence-insinuate ()
4468 "Set up hooks for clock persistence."
4469 (require 'org-clock)
4470 (add-hook 'org-mode-hook 'org-clock-load)
4471 (add-hook 'kill-emacs-hook 'org-clock-save))
4473 (defgroup org-archive nil
4474 "Options concerning archiving in Org mode."
4475 :tag "Org Archive"
4476 :group 'org-structure)
4478 (defcustom org-archive-location "%s_archive::"
4479 "The location where subtrees should be archived.
4481 The value of this variable is a string, consisting of two parts,
4482 separated by a double-colon. The first part is a filename and
4483 the second part is a headline.
4485 When the filename is omitted, archiving happens in the same file.
4486 %s in the filename will be replaced by the current file
4487 name (without the directory part). Archiving to a different file
4488 is useful to keep archived entries from contributing to the
4489 Org Agenda.
4491 The archived entries will be filed as subtrees of the specified
4492 headline. When the headline is omitted, the subtrees are simply
4493 filed away at the end of the file, as top-level entries. Also in
4494 the heading you can use %s to represent the file name, this can be
4495 useful when using the same archive for a number of different files.
4497 Here are a few examples:
4498 \"%s_archive::\"
4499 If the current file is Projects.org, archive in file
4500 Projects.org_archive, as top-level trees. This is the default.
4502 \"::* Archived Tasks\"
4503 Archive in the current file, under the top-level headline
4504 \"* Archived Tasks\".
4506 \"~/org/archive.org::\"
4507 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4509 \"~/org/archive.org::* From %s\"
4510 Archive in file ~/org/archive.org (absolute path), under headlines
4511 \"From FILENAME\" where file name is the current file name.
4513 \"~/org/datetree.org::datetree/* Finished Tasks\"
4514 The \"datetree/\" string is special, signifying to archive
4515 items to the datetree. Items are placed in either the CLOSED
4516 date of the item, or the current date if there is no CLOSED date.
4517 The heading will be a subentry to the current date. There doesn't
4518 need to be a heading, but there always needs to be a slash after
4519 datetree. For example, to store archived items directly in the
4520 datetree, use \"~/org/datetree.org::datetree/\".
4522 \"basement::** Finished Tasks\"
4523 Archive in file ./basement (relative path), as level 3 trees
4524 below the level 2 heading \"** Finished Tasks\".
4526 You may set this option on a per-file basis by adding to the buffer a
4527 line like
4529 #+ARCHIVE: basement::** Finished Tasks
4531 You may also define it locally for a subtree by setting an ARCHIVE property
4532 in the entry. If such a property is found in an entry, or anywhere up
4533 the hierarchy, it will be used."
4534 :group 'org-archive
4535 :type 'string)
4537 (defcustom org-agenda-skip-archived-trees t
4538 "Non-nil means the agenda will skip any items located in archived trees.
4539 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4540 variable is no longer recommended, you should leave it at the value t.
4541 Instead, use the key `v' to cycle the archives-mode in the agenda."
4542 :group 'org-archive
4543 :group 'org-agenda-skip
4544 :type 'boolean)
4546 (defcustom org-columns-skip-archived-trees t
4547 "Non-nil means ignore archived trees when creating column view."
4548 :group 'org-archive
4549 :group 'org-properties
4550 :type 'boolean)
4552 (defcustom org-cycle-open-archived-trees nil
4553 "Non-nil means `org-cycle' will open archived trees.
4554 An archived tree is a tree marked with the tag ARCHIVE.
4555 When nil, archived trees will stay folded. You can still open them with
4556 normal outline commands like `show-all', but not with the cycling commands."
4557 :group 'org-archive
4558 :group 'org-cycle
4559 :type 'boolean)
4561 (defcustom org-sparse-tree-open-archived-trees nil
4562 "Non-nil means sparse tree construction shows matches in archived trees.
4563 When nil, matches in these trees are highlighted, but the trees are kept in
4564 collapsed state."
4565 :group 'org-archive
4566 :group 'org-sparse-trees
4567 :type 'boolean)
4569 (defcustom org-sparse-tree-default-date-type nil
4570 "The default date type when building a sparse tree.
4571 When this is nil, a date is a scheduled or a deadline timestamp.
4572 Otherwise, these types are allowed:
4574 all: all timestamps
4575 active: only active timestamps (<...>)
4576 inactive: only inactive timestamps ([...])
4577 scheduled: only scheduled timestamps
4578 deadline: only deadline timestamps"
4579 :type '(choice (const :tag "Scheduled or deadline" nil)
4580 (const :tag "All timestamps" all)
4581 (const :tag "Only active timestamps" active)
4582 (const :tag "Only inactive timestamps" inactive)
4583 (const :tag "Only scheduled timestamps" scheduled)
4584 (const :tag "Only deadline timestamps" deadline)
4585 (const :tag "Only closed timestamps" closed))
4586 :version "26.1"
4587 :package-version '(Org . "8.3")
4588 :group 'org-sparse-trees)
4590 (defun org-cycle-hide-archived-subtrees (state)
4591 "Re-hide all archived subtrees after a visibility state change.
4592 STATE should be one of the symbols listed in the docstring of
4593 `org-cycle-hook'."
4594 (when (and (not org-cycle-open-archived-trees)
4595 (not (memq state '(overview folded))))
4596 (save-excursion
4597 (let* ((globalp (memq state '(contents all)))
4598 (beg (if globalp (point-min) (point)))
4599 (end (if globalp (point-max) (org-end-of-subtree t))))
4600 (org-hide-archived-subtrees beg end)
4601 (goto-char beg)
4602 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4603 (message "%s" (substitute-command-keys
4604 "Subtree is archived and stays closed. Use \
4605 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4607 (defun org-force-cycle-archived ()
4608 "Cycle subtree even if it is archived."
4609 (interactive)
4610 (setq this-command 'org-cycle)
4611 (let ((org-cycle-open-archived-trees t))
4612 (call-interactively 'org-cycle)))
4614 (defun org-hide-archived-subtrees (beg end)
4615 "Re-hide all archived subtrees after a visibility state change."
4616 (org-with-wide-buffer
4617 (let ((case-fold-search nil)
4618 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4619 (goto-char beg)
4620 ;; Include headline point is currently on.
4621 (beginning-of-line)
4622 (while (and (< (point) end) (re-search-forward re end t))
4623 (when (member org-archive-tag (org-get-tags))
4624 (org-flag-subtree t)
4625 (org-end-of-subtree t))))))
4627 (defun org-flag-subtree (flag)
4628 (save-excursion
4629 (org-back-to-heading t)
4630 (org-flag-region (line-end-position)
4631 (progn (org-end-of-subtree t) (point))
4632 flag
4633 'outline)))
4635 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4637 ;; Declare Column View Code
4639 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4640 (declare-function org-columns-compute "org-colview" (property))
4642 ;; Declare ID code
4644 (declare-function org-id-store-link "org-id")
4645 (declare-function org-id-locations-load "org-id")
4646 (declare-function org-id-locations-save "org-id")
4647 (defvar org-id-track-globally)
4649 ;;; Variables for pre-computed regular expressions, all buffer local
4651 (defvar-local org-todo-regexp nil
4652 "Matches any of the TODO state keywords.
4653 Since TODO keywords are case-sensitive, `case-fold-search' is
4654 expected to be bound to nil when matching against this regexp.")
4656 (defvar-local org-not-done-regexp nil
4657 "Matches any of the TODO state keywords except the last one.
4658 Since TODO keywords are case-sensitive, `case-fold-search' is
4659 expected to be bound to nil when matching against this regexp.")
4661 (defvar-local org-not-done-heading-regexp nil
4662 "Matches a TODO headline that is not done.
4663 Since TODO keywords are case-sensitive, `case-fold-search' is
4664 expected to be bound to nil when matching against this regexp.")
4666 (defvar-local org-todo-line-regexp nil
4667 "Matches a headline and puts TODO state into group 2 if present.
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-complex-heading-regexp nil
4672 "Matches a headline and puts everything into groups:
4674 group 1: Stars
4675 group 2: The TODO keyword, maybe
4676 group 3: Priority cookie
4677 group 4: True headline
4678 group 5: Tags
4680 Since TODO keywords are case-sensitive, `case-fold-search' is
4681 expected to be bound to nil when matching against this regexp.")
4683 (defvar-local org-complex-heading-regexp-format nil
4684 "Printf format to make regexp to match an exact headline.
4685 This regexp will match the headline of any node which has the
4686 exact headline text that is put into the format, but may have any
4687 TODO state, priority and tags.")
4689 (defvar-local org-todo-line-tags-regexp nil
4690 "Matches a headline and puts TODO state into group 2 if present.
4691 Also put tags into group 4 if tags are present.")
4693 (defconst org-plain-time-of-day-regexp
4694 (concat
4695 "\\(\\<[012]?[0-9]"
4696 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4697 "\\(--?"
4698 "\\(\\<[012]?[0-9]"
4699 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4700 "\\)?")
4701 "Regular expression to match a plain time or time range.
4702 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4703 groups carry important information:
4704 0 the full match
4705 1 the first time, range or not
4706 8 the second time, if it is a range.")
4708 (defconst org-plain-time-extension-regexp
4709 (concat
4710 "\\(\\<[012]?[0-9]"
4711 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4712 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4713 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4714 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4715 groups carry important information:
4716 0 the full match
4717 7 hours of duration
4718 9 minutes of duration")
4720 (defconst org-stamp-time-of-day-regexp
4721 (concat
4722 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4723 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4724 "\\(--?"
4725 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4726 "Regular expression to match a timestamp time or time range.
4727 After a match, the following groups carry important information:
4728 0 the full match
4729 1 date plus weekday, for back referencing to make sure both times are on the same day
4730 2 the first time, range or not
4731 4 the second time, if it is a range.")
4733 (defconst org-startup-options
4734 '(("fold" org-startup-folded t)
4735 ("overview" org-startup-folded t)
4736 ("nofold" org-startup-folded nil)
4737 ("showall" org-startup-folded nil)
4738 ("showeverything" org-startup-folded showeverything)
4739 ("content" org-startup-folded content)
4740 ("indent" org-startup-indented t)
4741 ("noindent" org-startup-indented nil)
4742 ("hidestars" org-hide-leading-stars t)
4743 ("showstars" org-hide-leading-stars nil)
4744 ("odd" org-odd-levels-only t)
4745 ("oddeven" org-odd-levels-only nil)
4746 ("align" org-startup-align-all-tables t)
4747 ("noalign" org-startup-align-all-tables nil)
4748 ("shrink" org-startup-shrink-all-tables t)
4749 ("inlineimages" org-startup-with-inline-images t)
4750 ("noinlineimages" org-startup-with-inline-images nil)
4751 ("latexpreview" org-startup-with-latex-preview t)
4752 ("nolatexpreview" org-startup-with-latex-preview nil)
4753 ("customtime" org-display-custom-times t)
4754 ("logdone" org-log-done time)
4755 ("lognotedone" org-log-done note)
4756 ("nologdone" org-log-done nil)
4757 ("lognoteclock-out" org-log-note-clock-out t)
4758 ("nolognoteclock-out" org-log-note-clock-out nil)
4759 ("logrepeat" org-log-repeat state)
4760 ("lognoterepeat" org-log-repeat note)
4761 ("logdrawer" org-log-into-drawer t)
4762 ("nologdrawer" org-log-into-drawer nil)
4763 ("logstatesreversed" org-log-states-order-reversed t)
4764 ("nologstatesreversed" org-log-states-order-reversed nil)
4765 ("nologrepeat" org-log-repeat nil)
4766 ("logreschedule" org-log-reschedule time)
4767 ("lognotereschedule" org-log-reschedule note)
4768 ("nologreschedule" org-log-reschedule nil)
4769 ("logredeadline" org-log-redeadline time)
4770 ("lognoteredeadline" org-log-redeadline note)
4771 ("nologredeadline" org-log-redeadline nil)
4772 ("logrefile" org-log-refile time)
4773 ("lognoterefile" org-log-refile note)
4774 ("nologrefile" org-log-refile nil)
4775 ("fninline" org-footnote-define-inline t)
4776 ("nofninline" org-footnote-define-inline nil)
4777 ("fnlocal" org-footnote-section nil)
4778 ("fnauto" org-footnote-auto-label t)
4779 ("fnprompt" org-footnote-auto-label nil)
4780 ("fnconfirm" org-footnote-auto-label confirm)
4781 ("fnplain" org-footnote-auto-label plain)
4782 ("fnadjust" org-footnote-auto-adjust t)
4783 ("nofnadjust" org-footnote-auto-adjust nil)
4784 ("constcgs" constants-unit-system cgs)
4785 ("constSI" constants-unit-system SI)
4786 ("noptag" org-tag-persistent-alist nil)
4787 ("hideblocks" org-hide-block-startup t)
4788 ("nohideblocks" org-hide-block-startup nil)
4789 ("beamer" org-startup-with-beamer-mode t)
4790 ("entitiespretty" org-pretty-entities t)
4791 ("entitiesplain" org-pretty-entities nil))
4792 "Variable associated with STARTUP options for Org.
4793 Each element is a list of three items: the startup options (as written
4794 in the #+STARTUP line), the corresponding variable, and the value to set
4795 this variable to if the option is found. An optional forth element PUSH
4796 means to push this value onto the list in the variable.")
4798 (defcustom org-group-tags t
4799 "When non-nil (the default), use group tags.
4800 This can be turned on/off through `org-toggle-tags-groups'."
4801 :group 'org-tags
4802 :group 'org-startup
4803 :type 'boolean)
4805 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4807 (defun org-toggle-tags-groups ()
4808 "Toggle support for group tags.
4809 Support for group tags is controlled by the option
4810 `org-group-tags', which is non-nil by default."
4811 (interactive)
4812 (setq org-group-tags (not org-group-tags))
4813 (cond ((and (derived-mode-p 'org-agenda-mode)
4814 org-group-tags)
4815 (org-agenda-redo))
4816 ((derived-mode-p 'org-mode)
4817 (let ((org-inhibit-startup t)) (org-mode))))
4818 (message "Groups tags support has been turned %s"
4819 (if org-group-tags "on" "off")))
4821 (defun org-set-regexps-and-options (&optional tags-only)
4822 "Precompute regular expressions used in the current buffer.
4823 When optional argument TAGS-ONLY is non-nil, only compute tags
4824 related expressions."
4825 (when (derived-mode-p 'org-mode)
4826 (let ((alist (org--setup-collect-keywords
4827 (org-make-options-regexp
4828 (append '("FILETAGS" "TAGS" "SETUPFILE")
4829 (and (not tags-only)
4830 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4831 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4832 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4833 ;; Startup options. Get this early since it does change
4834 ;; behavior for other options (e.g., tags).
4835 (let ((startup (cdr (assq 'startup alist))))
4836 (dolist (option startup)
4837 (let ((entry (assoc-string option org-startup-options t)))
4838 (when entry
4839 (let ((var (nth 1 entry))
4840 (val (nth 2 entry)))
4841 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4842 (unless (listp (symbol-value var))
4843 (set (make-local-variable var) nil))
4844 (add-to-list var val)))))))
4845 (setq-local org-file-tags
4846 (mapcar #'org-add-prop-inherited
4847 (cdr (assq 'filetags alist))))
4848 (setq org-current-tag-alist
4849 (append org-tag-persistent-alist
4850 (let ((tags (cdr (assq 'tags alist))))
4851 (if tags (org-tag-string-to-alist tags)
4852 org-tag-alist))))
4853 (setq org-tag-groups-alist
4854 (org-tag-alist-to-groups org-current-tag-alist))
4855 (unless tags-only
4856 ;; File properties.
4857 (setq-local org-file-properties (cdr (assq 'property alist)))
4858 ;; Archive location.
4859 (let ((archive (cdr (assq 'archive alist))))
4860 (when archive (setq-local org-archive-location archive)))
4861 ;; Category.
4862 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4863 (when cat
4864 (setq-local org-category (intern cat))
4865 (setq-local org-file-properties
4866 (org--update-property-plist
4867 "CATEGORY" cat org-file-properties))))
4868 ;; Columns.
4869 (let ((column (cdr (assq 'columns alist))))
4870 (when column (setq-local org-columns-default-format column)))
4871 ;; Constants.
4872 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4873 ;; Link abbreviations.
4874 (let ((links (cdr (assq 'link alist))))
4875 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4876 ;; Priorities.
4877 (let ((priorities (cdr (assq 'priorities alist))))
4878 (when priorities
4879 (setq-local org-highest-priority (nth 0 priorities))
4880 (setq-local org-lowest-priority (nth 1 priorities))
4881 (setq-local org-default-priority (nth 2 priorities))))
4882 ;; Scripts.
4883 (let ((scripts (assq 'scripts alist)))
4884 (when scripts
4885 (setq-local org-use-sub-superscripts (cdr scripts))))
4886 ;; TODO keywords.
4887 (setq-local org-todo-kwd-alist nil)
4888 (setq-local org-todo-key-alist nil)
4889 (setq-local org-todo-key-trigger nil)
4890 (setq-local org-todo-keywords-1 nil)
4891 (setq-local org-done-keywords nil)
4892 (setq-local org-todo-heads nil)
4893 (setq-local org-todo-sets nil)
4894 (setq-local org-todo-log-states nil)
4895 (let ((todo-sequences
4896 (or (nreverse (cdr (assq 'todo alist)))
4897 (let ((d (default-value 'org-todo-keywords)))
4898 (if (not (stringp (car d))) d
4899 ;; XXX: Backward compatibility code.
4900 (list (cons org-todo-interpretation d)))))))
4901 (dolist (sequence todo-sequences)
4902 (let* ((sequence (or (run-hook-with-args-until-success
4903 'org-todo-setup-filter-hook sequence)
4904 sequence))
4905 (sequence-type (car sequence))
4906 (keywords (cdr sequence))
4907 (sep (member "|" keywords))
4908 names alist)
4909 (dolist (k (remove "|" keywords))
4910 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4912 (error "Invalid TODO keyword %s" k))
4913 (let ((name (match-string 1 k))
4914 (key (match-string 2 k))
4915 (log (org-extract-log-state-settings k)))
4916 (push name names)
4917 (push (cons name (and key (string-to-char key))) alist)
4918 (when log (push log org-todo-log-states))))
4919 (let* ((names (nreverse names))
4920 (done (if sep (org-remove-keyword-keys (cdr sep))
4921 (last names)))
4922 (head (car names))
4923 (tail (list sequence-type head (car done) (org-last done))))
4924 (add-to-list 'org-todo-heads head 'append)
4925 (push names org-todo-sets)
4926 (setq org-done-keywords (append org-done-keywords done nil))
4927 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4928 (setq org-todo-key-alist
4929 (append org-todo-key-alist
4930 (and alist
4931 (append '((:startgroup))
4932 (nreverse alist)
4933 '((:endgroup))))))
4934 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4935 (setq org-todo-sets (nreverse org-todo-sets)
4936 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4937 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4938 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4939 ;; Compute the regular expressions and other local variables.
4940 ;; Using `org-outline-regexp-bol' would complicate them much,
4941 ;; because of the fixed white space at the end of that string.
4942 (unless org-done-keywords
4943 (setq org-done-keywords
4944 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4945 (setq org-not-done-keywords
4946 (org-delete-all org-done-keywords
4947 (copy-sequence org-todo-keywords-1))
4948 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4949 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4950 org-not-done-heading-regexp
4951 (format org-heading-keyword-regexp-format org-not-done-regexp)
4952 org-todo-line-regexp
4953 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4954 org-complex-heading-regexp
4955 (concat "^\\(\\*+\\)"
4956 "\\(?: +" org-todo-regexp "\\)?"
4957 "\\(?: +\\(\\[#.\\]\\)\\)?"
4958 "\\(?: +\\(.*?\\)\\)??"
4959 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4960 "[ \t]*$")
4961 org-complex-heading-regexp-format
4962 (concat "^\\(\\*+\\)"
4963 "\\(?: +" org-todo-regexp "\\)?"
4964 "\\(?: +\\(\\[#.\\]\\)\\)?"
4965 "\\(?: +"
4966 ;; Stats cookies can be stuck to body.
4967 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4968 "\\(%s\\)"
4969 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4970 "\\)"
4971 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4972 "[ \t]*$")
4973 org-todo-line-tags-regexp
4974 (concat "^\\(\\*+\\)"
4975 "\\(?: +" org-todo-regexp "\\)?"
4976 "\\(?: +\\(.*?\\)\\)??"
4977 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
4978 "[ \t]*$"))
4979 (org-compute-latex-and-related-regexp)))))
4981 (defun org--setup-collect-keywords (regexp &optional files alist)
4982 "Return setup keywords values as an alist.
4984 REGEXP matches a subset of setup keywords. FILES is a list of
4985 file names already visited. It is used to avoid circular setup
4986 files. ALIST, when non-nil, is the alist computed so far.
4988 Return value contains the following keys: `archive', `category',
4989 `columns', `constants', `filetags', `link', `priorities',
4990 `property', `scripts', `startup', `tags' and `todo'."
4991 (org-with-wide-buffer
4992 (goto-char (point-min))
4993 (let ((case-fold-search t))
4994 (while (re-search-forward regexp nil t)
4995 (let ((element (org-element-at-point)))
4996 (when (eq (org-element-type element) 'keyword)
4997 (let ((key (org-element-property :key element))
4998 (value (org-element-property :value element)))
4999 (cond
5000 ((equal key "ARCHIVE")
5001 (when (org-string-nw-p value)
5002 (push (cons 'archive value) alist)))
5003 ((equal key "CATEGORY") (push (cons 'category value) alist))
5004 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5005 ((equal key "CONSTANTS")
5006 (let* ((constants (assq 'constants alist))
5007 (store (cdr constants)))
5008 (dolist (pair (split-string value))
5009 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5010 pair)
5011 (let* ((name (match-string 1 pair))
5012 (value (match-string 2 pair))
5013 (old (assoc name store)))
5014 (if old (setcdr old value)
5015 (push (cons name value) store)))))
5016 (if constants (setcdr constants store)
5017 (push (cons 'constants store) alist))))
5018 ((equal key "FILETAGS")
5019 (when (org-string-nw-p value)
5020 (let ((old (assq 'filetags alist))
5021 (new (apply #'nconc
5022 (mapcar (lambda (x) (org-split-string x ":"))
5023 (split-string value)))))
5024 (if old (setcdr old (append new (cdr old)))
5025 (push (cons 'filetags new) alist)))))
5026 ((equal key "LINK")
5027 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5028 (let ((links (assq 'link alist))
5029 (pair (cons (match-string-no-properties 1 value)
5030 (match-string-no-properties 2 value))))
5031 (if links (push pair (cdr links))
5032 (push (list 'link pair) alist)))))
5033 ((equal key "OPTIONS")
5034 (when (and (org-string-nw-p value)
5035 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5036 (push (cons 'scripts (read (match-string 1 value))) alist)))
5037 ((equal key "PRIORITIES")
5038 (push (cons 'priorities
5039 (let ((prio (split-string value)))
5040 (if (< (length prio) 3) '(?A ?C ?B)
5041 (mapcar #'string-to-char prio))))
5042 alist))
5043 ((equal key "PROPERTY")
5044 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5045 (let* ((property (assq 'property alist))
5046 (value (org--update-property-plist
5047 (match-string-no-properties 1 value)
5048 (match-string-no-properties 2 value)
5049 (cdr property))))
5050 (if property (setcdr property value)
5051 (push (cons 'property value) alist)))))
5052 ((equal key "STARTUP")
5053 (let ((startup (assq 'startup alist)))
5054 (if startup
5055 (setcdr startup
5056 (append (cdr startup) (split-string value)))
5057 (push (cons 'startup (split-string value)) alist))))
5058 ((equal key "TAGS")
5059 (let ((tag-cell (assq 'tags alist)))
5060 (if tag-cell
5061 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5062 (push (cons 'tags value) alist))))
5063 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5064 (let ((todo (assq 'todo alist))
5065 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5066 (split-string value))))
5067 (if todo (push value (cdr todo))
5068 (push (list 'todo value) alist))))
5069 ((equal key "SETUPFILE")
5070 (unless buffer-read-only ; Do not check in Gnus messages.
5071 (let ((f (and (org-string-nw-p value)
5072 (expand-file-name
5073 (org-unbracket-string "\"" "\"" value)))))
5074 (when (and f (file-readable-p f) (not (member f files)))
5075 (with-temp-buffer
5076 (setq default-directory (file-name-directory f))
5077 (insert-file-contents f)
5078 (setq alist
5079 ;; Fake Org mode to benefit from cache
5080 ;; without recurring needlessly.
5081 (let ((major-mode 'org-mode))
5082 (org--setup-collect-keywords
5083 regexp (cons f files) alist)))))))))))))))
5084 alist)
5086 (defun org-tag-string-to-alist (s)
5087 "Return tag alist associated to string S.
5088 S is a value for TAGS keyword or produced with
5089 `org-tag-alist-to-string'. Return value is an alist suitable for
5090 `org-tag-alist' or `org-tag-persistent-alist'."
5091 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5092 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5093 "\\|{.+?}\\)" ; regular expression
5094 "\\(?:(\\(.\\))\\)?\\'"))
5095 alist group-flag)
5096 (dolist (tokens lines (cdr (nreverse alist)))
5097 (push '(:newline) alist)
5098 (while tokens
5099 (let ((token (pop tokens)))
5100 (pcase token
5101 ("{"
5102 (push '(:startgroup) alist)
5103 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5104 ("}"
5105 (push '(:endgroup) alist)
5106 (setq group-flag nil))
5107 ("["
5108 (push '(:startgrouptag) alist)
5109 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5110 ("]"
5111 (push '(:endgrouptag) alist)
5112 (setq group-flag nil))
5113 (":"
5114 (push '(:grouptags) alist))
5115 ((guard (string-match tag-re token))
5116 (let ((tag (match-string 1 token))
5117 (key (and (match-beginning 2)
5118 (string-to-char (match-string 2 token)))))
5119 ;; Push all tags in groups, no matter if they already
5120 ;; appear somewhere else in the list.
5121 (when (or group-flag (not (assoc tag alist)))
5122 (push (cons tag key) alist))))))))))
5124 (defun org-tag-alist-to-string (alist &optional skip-key)
5125 "Return tag string associated to ALIST.
5127 ALIST is an alist, as defined in `org-tag-alist' or
5128 `org-tag-persistent-alist', or produced with
5129 `org-tag-string-to-alist'.
5131 Return value is a string suitable as a value for \"TAGS\"
5132 keyword.
5134 When optional argument SKIP-KEY is non-nil, skip selection keys
5135 next to tags."
5136 (mapconcat (lambda (token)
5137 (pcase token
5138 (`(:startgroup) "{")
5139 (`(:endgroup) "}")
5140 (`(:startgrouptag) "[")
5141 (`(:endgrouptag) "]")
5142 (`(:grouptags) ":")
5143 (`(:newline) "\\n")
5144 ((and
5145 (guard (not skip-key))
5146 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5147 (format "%s(%c)" tag key))
5148 (`(,(and tag (pred stringp)) . ,_) tag)
5149 (_ (user-error "Invalid tag token: %S" token))))
5150 alist
5151 " "))
5153 (defun org-tag-alist-to-groups (alist)
5154 "Return group alist from tag ALIST.
5155 ALIST is an alist, as defined in `org-tag-alist' or
5156 `org-tag-persistent-alist', or produced with
5157 `org-tag-string-to-alist'. Return value is an alist following
5158 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5159 a string, summarizing TAGS, as a list of strings."
5160 (let (groups group-status current-group)
5161 (dolist (token alist (nreverse groups))
5162 (pcase token
5163 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5164 (`(,(or :endgroup :endgrouptag))
5165 (when (eq group-status 'append)
5166 (push (nreverse current-group) groups))
5167 (setq group-status nil))
5168 (`(:grouptags) (setq group-status 'append))
5169 ((and `(,tag . ,_) (guard group-status))
5170 (if (eq group-status 'append) (push tag current-group)
5171 (setq current-group (list tag))))
5172 (_ nil)))))
5174 (defvar org--file-cache (make-hash-table :test #'equal)
5175 "Hash table to store contents of files referenced via a URL.
5176 This is the cache of file URLs read using `org-file-contents'.")
5178 (defun org-reset-file-cache ()
5179 "Reset the cache of files downloaded by `org-file-contents'."
5180 (clrhash org--file-cache))
5182 (defun org-file-url-p (file)
5183 "Non-nil if FILE is a URL."
5184 (require 'ffap)
5185 (string-match-p ffap-url-regexp file))
5187 (defun org-file-contents (file &optional noerror nocache)
5188 "Return the contents of FILE, as a string.
5190 FILE can be a file name or URL.
5192 If FILE is a URL, download the contents. If the URL contents are
5193 already cached in the `org--file-cache' hash table, the download step
5194 is skipped.
5196 If NOERROR is non-nil, ignore the error when unable to read the FILE
5197 from file or URL.
5199 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5200 is available. This option applies only if FILE is a URL."
5201 (let* ((is-url (org-file-url-p file))
5202 (cache (and is-url
5203 (not nocache)
5204 (gethash file org--file-cache))))
5205 (cond
5206 (cache)
5207 (is-url
5208 (with-current-buffer (url-retrieve-synchronously file)
5209 (goto-char (point-min))
5210 ;; Move point to after the url-retrieve header.
5211 (search-forward "\n\n" nil :move)
5212 ;; Search for the success code only in the url-retrieve header.
5213 (if (save-excursion
5214 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5215 ;; Update the cache `org--file-cache' and return contents.
5216 (puthash file
5217 (buffer-substring-no-properties (point) (point-max))
5218 org--file-cache)
5219 (funcall (if noerror #'message #'user-error)
5220 "Unable to fetch file from %S"
5221 file))))
5223 (with-temp-buffer
5224 (condition-case nil
5225 (progn
5226 (insert-file-contents file)
5227 (buffer-string))
5228 (file-error
5229 (funcall (if noerror #'message #'user-error)
5230 "Unable to read file %S"
5231 file))))))))
5233 (defun org-extract-log-state-settings (x)
5234 "Extract the log state setting from a TODO keyword string.
5235 This will extract info from a string like \"WAIT(w@/!)\"."
5236 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5237 (let ((kw (match-string 1 x))
5238 (log1 (and (match-end 3) (match-string 3 x)))
5239 (log2 (and (match-end 4) (match-string 4 x))))
5240 (and (or log1 log2)
5241 (list kw
5242 (and log1 (if (equal log1 "!") 'time 'note))
5243 (and log2 (if (equal log2 "!") 'time 'note)))))))
5245 (defun org-remove-keyword-keys (list)
5246 "Remove a pair of parenthesis at the end of each string in LIST."
5247 (mapcar (lambda (x)
5248 (if (string-match "(.*)$" x)
5249 (substring x 0 (match-beginning 0))
5251 list))
5253 (defun org-assign-fast-keys (alist)
5254 "Assign fast keys to a keyword-key alist.
5255 Respect keys that are already there."
5256 (let (new e (alt ?0))
5257 (while (setq e (pop alist))
5258 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5259 (cdr e)) ;; Key already assigned.
5260 (push e new)
5261 (let ((clist (string-to-list (downcase (car e))))
5262 (used (append new alist)))
5263 (when (= (car clist) ?@)
5264 (pop clist))
5265 (while (and clist (rassoc (car clist) used))
5266 (pop clist))
5267 (unless clist
5268 (while (rassoc alt used)
5269 (cl-incf alt)))
5270 (push (cons (car e) (or (car clist) alt)) new))))
5271 (nreverse new)))
5273 ;;; Some variables used in various places
5275 (defvar org-window-configuration nil
5276 "Used in various places to store a window configuration.")
5277 (defvar org-selected-window nil
5278 "Used in various places to store a window configuration.")
5279 (defvar org-finish-function nil
5280 "Function to be called when `C-c C-c' is used.
5281 This is for getting out of special buffers like capture.")
5282 (defvar org-last-state)
5284 ;; Defined somewhere in this file, but used before definition.
5285 (defvar org-entities) ;; defined in org-entities.el
5286 (defvar org-struct-menu)
5287 (defvar org-org-menu)
5288 (defvar org-tbl-menu)
5290 ;;;; Define the Org mode
5292 ;; We use a before-change function to check if a table might need
5293 ;; an update.
5294 (defvar org-table-may-need-update t
5295 "Indicates that a table might need an update.
5296 This variable is set by `org-before-change-function'.
5297 `org-table-align' sets it back to nil.")
5298 (defun org-before-change-function (_beg _end)
5299 "Every change indicates that a table might need an update."
5300 (setq org-table-may-need-update t))
5301 (defvar org-mode-map)
5302 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5303 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5304 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5305 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5306 (defvar org-table-buffer-is-an nil)
5308 (defvar bidi-paragraph-direction)
5309 (defvar buffer-face-mode-face)
5311 (require 'outline)
5313 ;; Other stuff we need.
5314 (require 'time-date)
5315 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5316 (require 'easymenu)
5317 (autoload 'easy-menu-add "easymenu")
5318 (require 'overlay)
5320 ;; (require 'org-macs) moved higher up in the file before it is first used
5321 (require 'org-entities)
5322 ;; (require 'org-compat) moved higher up in the file before it is first used
5323 (require 'org-faces)
5324 (require 'org-list)
5325 (require 'org-pcomplete)
5326 (require 'org-src)
5327 (require 'org-footnote)
5328 (require 'org-macro)
5330 ;; babel
5331 (require 'ob)
5333 ;;;###autoload
5334 (define-derived-mode org-mode outline-mode "Org"
5335 "Outline-based notes management and organizer, alias
5336 \"Carsten's outline-mode for keeping track of everything.\"
5338 Org mode develops organizational tasks around a NOTES file which
5339 contains information about projects as plain text. Org mode is
5340 implemented on top of Outline mode, which is ideal to keep the content
5341 of large files well structured. It supports ToDo items, deadlines and
5342 time stamps, which magically appear in the diary listing of the Emacs
5343 calendar. Tables are easily created with a built-in table editor.
5344 Plain text URL-like links connect to websites, emails (VM), Usenet
5345 messages (Gnus), BBDB entries, and any files related to the project.
5346 For printing and sharing of notes, an Org file (or a part of it)
5347 can be exported as a structured ASCII or HTML file.
5349 The following commands are available:
5351 \\{org-mode-map}"
5353 ;; Get rid of Outline menus, they are not needed
5354 ;; Need to do this here because define-derived-mode sets up
5355 ;; the keymap so late. Still, it is a waste to call this each time
5356 ;; we switch another buffer into Org mode.
5357 (define-key org-mode-map [menu-bar headings] 'undefined)
5358 (define-key org-mode-map [menu-bar hide] 'undefined)
5359 (define-key org-mode-map [menu-bar show] 'undefined)
5361 (org-load-modules-maybe)
5362 (org-install-agenda-files-menu)
5363 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5364 (add-to-invisibility-spec '(org-hide-block . t))
5365 (add-to-invisibility-spec '(org-hide-drawer . t))
5366 (setq-local outline-regexp org-outline-regexp)
5367 (setq-local outline-level 'org-outline-level)
5368 (setq bidi-paragraph-direction 'left-to-right)
5369 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5370 (unless org-display-table
5371 (setq org-display-table (make-display-table)))
5372 (set-display-table-slot
5373 org-display-table 4
5374 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5375 org-ellipsis)))
5376 (setq buffer-display-table org-display-table))
5377 (org-set-regexps-and-options)
5378 (org-set-font-lock-defaults)
5379 (when (and org-tag-faces (not org-tags-special-faces-re))
5380 ;; tag faces set outside customize.... force initialization.
5381 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5382 ;; Calc embedded
5383 (setq-local calc-embedded-open-mode "# ")
5384 ;; Modify a few syntax entries
5385 (modify-syntax-entry ?@ "w")
5386 (modify-syntax-entry ?\" "\"")
5387 (modify-syntax-entry ?\\ "_")
5388 (modify-syntax-entry ?~ "_")
5389 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5390 ;; Activate before-change-function
5391 (setq-local org-table-may-need-update t)
5392 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5393 ;; Check for running clock before killing a buffer
5394 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5395 ;; Initialize macros templates.
5396 (org-macro-initialize-templates)
5397 ;; Initialize radio targets.
5398 (org-update-radio-target-regexp)
5399 ;; Indentation.
5400 (setq-local indent-line-function 'org-indent-line)
5401 (setq-local indent-region-function 'org-indent-region)
5402 ;; Filling and auto-filling.
5403 (org-setup-filling)
5404 ;; Comments.
5405 (org-setup-comments-handling)
5406 ;; Initialize cache.
5407 (org-element-cache-reset)
5408 ;; Beginning/end of defun
5409 (setq-local beginning-of-defun-function 'org-backward-element)
5410 (setq-local end-of-defun-function
5411 (lambda ()
5412 (if (not (org-at-heading-p))
5413 (org-forward-element)
5414 (org-forward-element)
5415 (forward-char -1))))
5416 ;; Next error for sparse trees
5417 (setq-local next-error-function 'org-occur-next-match)
5418 ;; Make sure dependence stuff works reliably, even for users who set it
5419 ;; too late :-(
5420 (if org-enforce-todo-dependencies
5421 (add-hook 'org-blocker-hook
5422 'org-block-todo-from-children-or-siblings-or-parent)
5423 (remove-hook 'org-blocker-hook
5424 'org-block-todo-from-children-or-siblings-or-parent))
5425 (if org-enforce-todo-checkbox-dependencies
5426 (add-hook 'org-blocker-hook
5427 'org-block-todo-from-checkboxes)
5428 (remove-hook 'org-blocker-hook
5429 'org-block-todo-from-checkboxes))
5431 ;; Align options lines
5432 (setq-local
5433 align-mode-rules-list
5434 '((org-in-buffer-settings
5435 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5436 (modes . '(org-mode)))))
5438 ;; Imenu
5439 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5441 ;; Make isearch reveal context
5442 (setq-local outline-isearch-open-invisible-function
5443 (lambda (&rest _) (org-show-context 'isearch)))
5445 ;; Setup the pcomplete hooks
5446 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5447 (setq-local pcomplete-command-name-function 'org-command-at-point)
5448 (setq-local pcomplete-default-completion-function 'ignore)
5449 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5450 (setq-local pcomplete-termination-string "")
5451 (setq-local buffer-face-mode-face 'org-default)
5453 ;; If empty file that did not turn on Org mode automatically, make
5454 ;; it to.
5455 (when (and org-insert-mode-line-in-empty-file
5456 (called-interactively-p 'any)
5457 (= (point-min) (point-max)))
5458 (insert "# -*- mode: org -*-\n\n"))
5459 (unless org-inhibit-startup
5460 (org-unmodified
5461 (when org-startup-with-beamer-mode (org-beamer-mode))
5462 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5463 (org-table-map-tables
5464 (cond ((and org-startup-align-all-tables
5465 org-startup-shrink-all-tables)
5466 (lambda () (org-table-align) (org-table-shrink)))
5467 (org-startup-align-all-tables #'org-table-align)
5468 (t #'org-table-shrink))
5470 (when org-startup-with-inline-images (org-display-inline-images))
5471 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5472 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5473 (when org-startup-truncated (setq truncate-lines t))
5474 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5475 (org-refresh-effort-properties)))
5476 ;; Try to set `org-hide' face correctly.
5477 (let ((foreground (org-find-invisible-foreground)))
5478 (when foreground
5479 (set-face-foreground 'org-hide foreground))))
5481 ;; Update `customize-package-emacs-version-alist'
5482 (add-to-list 'customize-package-emacs-version-alist
5483 '(Org ("8.0" . "24.4")
5484 ("8.1" . "24.4")
5485 ("8.2" . "24.4")
5486 ("8.2.7" . "24.4")
5487 ("8.3" . "26.1")
5488 ("9.0" . "26.1")
5489 ("9.1" . "26.1")
5490 ("9.2" . "27.1")))
5492 (defvar org-mode-transpose-word-syntax-table
5493 (let ((st (make-syntax-table text-mode-syntax-table)))
5494 (dolist (c org-emphasis-alist st)
5495 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5497 (when (fboundp 'abbrev-table-put)
5498 (abbrev-table-put org-mode-abbrev-table
5499 :parents (list text-mode-abbrev-table)))
5501 (defun org-find-invisible-foreground ()
5502 (let ((candidates (remove
5503 "unspecified-bg"
5504 (nconc
5505 (list (face-background 'default)
5506 (face-background 'org-default))
5507 (mapcar
5508 (lambda (alist)
5509 (when (boundp alist)
5510 (cdr (assq 'background-color (symbol-value alist)))))
5511 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5512 (list (face-foreground 'org-hide))))))
5513 (car (remove nil candidates))))
5515 (defun org-current-time (&optional rounding-minutes past)
5516 "Current time, possibly rounded to ROUNDING-MINUTES.
5517 When ROUNDING-MINUTES is not an integer, fall back on the car of
5518 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5519 the rounding returns a past time."
5520 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5521 (car org-time-stamp-rounding-minutes)))
5522 (time (decode-time)) res)
5523 (if (< r 1)
5524 (current-time)
5525 (setq res
5526 (apply 'encode-time
5527 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5528 (nthcdr 2 time))))
5529 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5530 (seconds-to-time (- (float-time res) (* r 60)))
5531 res))))
5533 (defun org-today ()
5534 "Return today date, considering `org-extend-today-until'."
5535 (time-to-days
5536 (time-subtract (current-time)
5537 (list 0 (* 3600 org-extend-today-until) 0))))
5539 ;;;; Font-Lock stuff, including the activators
5541 (defvar org-mouse-map (make-sparse-keymap))
5542 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5543 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5544 (when org-mouse-1-follows-link
5545 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5546 (when org-tab-follows-link
5547 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5548 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5550 (require 'font-lock)
5552 (defconst org-non-link-chars "]\t\n\r<>")
5553 (defvar org-link-types-re nil
5554 "Matches a link that has a url-like prefix like \"http:\"")
5555 (defvar org-link-re-with-space nil
5556 "Matches a link with spaces, optional angular brackets around it.")
5557 (defvar org-link-re-with-space2 nil
5558 "Matches a link with spaces, optional angular brackets around it.")
5559 (defvar org-link-re-with-space3 nil
5560 "Matches a link with spaces, only for internal part in bracket links.")
5561 (defvar org-angle-link-re nil
5562 "Matches link with angular brackets, spaces are allowed.")
5563 (defvar org-plain-link-re nil
5564 "Matches plain link, without spaces.")
5565 (defvar org-bracket-link-regexp nil
5566 "Matches a link in double brackets.")
5567 (defvar org-bracket-link-analytic-regexp nil
5568 "Regular expression used to analyze links.
5569 Here is what the match groups contain after a match:
5570 1: http:
5571 2: http
5572 3: path
5573 4: [desc]
5574 5: desc")
5575 (defvar org-bracket-link-analytic-regexp++ nil
5576 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5577 (defvar org-any-link-re nil
5578 "Regular expression matching any link.")
5580 (defconst org-match-sexp-depth 3
5581 "Number of stacked braces for sub/superscript matching.")
5583 (defun org-create-multibrace-regexp (left right n)
5584 "Create a regular expression which will match a balanced sexp.
5585 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5586 as single character strings.
5587 The regexp returned will match the entire expression including the
5588 delimiters. It will also define a single group which contains the
5589 match except for the outermost delimiters. The maximum depth of
5590 stacked delimiters is N. Escaping delimiters is not possible."
5591 (let* ((nothing (concat "[^" left right "]*?"))
5592 (or "\\|")
5593 (re nothing)
5594 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5595 (while (> n 1)
5596 (setq n (1- n)
5597 re (concat re or next)
5598 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5599 (concat left "\\(" re "\\)" right)))
5601 (defconst org-match-substring-regexp
5602 (concat
5603 "\\(\\S-\\)\\([_^]\\)\\("
5604 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5605 "\\|"
5606 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5607 "\\|"
5608 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5609 "The regular expression matching a sub- or superscript.")
5611 (defconst org-match-substring-with-braces-regexp
5612 (concat
5613 "\\(\\S-\\)\\([_^]\\)"
5614 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5615 "The regular expression matching a sub- or superscript, forcing braces.")
5617 (defun org-make-link-regexps ()
5618 "Update the link regular expressions.
5619 This should be called after the variable `org-link-parameters' has changed."
5620 (let ((types-re (regexp-opt (org-link-types) t)))
5621 (setq org-link-types-re
5622 (concat "\\`" types-re ":")
5623 org-link-re-with-space
5624 (concat "<?" types-re ":"
5625 "\\([^" org-non-link-chars " ]"
5626 "[^" org-non-link-chars "]*"
5627 "[^" org-non-link-chars " ]\\)>?")
5628 org-link-re-with-space2
5629 (concat "<?" types-re ":"
5630 "\\([^" org-non-link-chars " ]"
5631 "[^\t\n\r]*"
5632 "[^" org-non-link-chars " ]\\)>?")
5633 org-link-re-with-space3
5634 (concat "<?" types-re ":"
5635 "\\([^" org-non-link-chars " ]"
5636 "[^\t\n\r]*\\)")
5637 org-angle-link-re
5638 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5639 types-re)
5640 org-plain-link-re
5641 (concat
5642 "\\<" types-re ":"
5643 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5644 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5645 org-bracket-link-regexp
5646 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5647 org-bracket-link-analytic-regexp
5648 (concat
5649 "\\[\\["
5650 "\\(" types-re ":\\)?"
5651 "\\([^]]+\\)"
5652 "\\]"
5653 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5654 "\\]")
5655 org-bracket-link-analytic-regexp++
5656 (concat
5657 "\\[\\["
5658 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5659 "\\([^]]+\\)"
5660 "\\]"
5661 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5662 "\\]")
5663 org-any-link-re
5664 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5665 org-angle-link-re "\\)\\|\\("
5666 org-plain-link-re "\\)"))))
5668 (org-make-link-regexps)
5670 (defvar org-emph-face nil)
5672 (defun org-do-emphasis-faces (limit)
5673 "Run through the buffer and emphasize strings."
5674 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5675 (car org-emphasis-regexp-components))))
5676 (catch :exit
5677 (while (re-search-forward quick-re limit t)
5678 (let* ((marker (match-string 2))
5679 (verbatim? (member marker '("~" "="))))
5680 (when (save-excursion
5681 (goto-char (match-beginning 0))
5682 (and
5683 ;; Do not match table hlines.
5684 (not (and (equal marker "+")
5685 (org-match-line
5686 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5687 ;; Do not match headline stars. Do not consider
5688 ;; stars of a headline as closing marker for bold
5689 ;; markup either.
5690 (not (and (equal marker "*")
5691 (save-excursion
5692 (forward-char)
5693 (skip-chars-backward "*")
5694 (looking-at-p org-outline-regexp-bol))))
5695 ;; Match full emphasis markup regexp.
5696 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5697 ;; Do not span over paragraph boundaries.
5698 (not (string-match-p org-element-paragraph-separate
5699 (match-string 2)))
5700 ;; Do not span over cells in table rows.
5701 (not (and (save-match-data (org-match-line "[ \t]*|"))
5702 (string-match-p "|" (match-string 4))))))
5703 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5704 (font-lock-prepend-text-property
5705 (match-beginning 2) (match-end 2) 'face face)
5706 (when verbatim?
5707 (org-remove-flyspell-overlays-in
5708 (match-beginning 0) (match-end 0)))
5709 (add-text-properties (match-beginning 2) (match-end 2)
5710 '(font-lock-multiline t org-emphasis t))
5711 (when org-hide-emphasis-markers
5712 (add-text-properties (match-end 4) (match-beginning 5)
5713 '(invisible org-link))
5714 (add-text-properties (match-beginning 3) (match-end 3)
5715 '(invisible org-link)))
5716 (throw :exit t))))))))
5718 (defun org-emphasize (&optional char)
5719 "Insert or change an emphasis, i.e. a font like bold or italic.
5720 If there is an active region, change that region to a new emphasis.
5721 If there is no region, just insert the marker characters and position
5722 the cursor between them.
5723 CHAR should be the marker character. If it is a space, it means to
5724 remove the emphasis of the selected region.
5725 If CHAR is not given (for example in an interactive call) it will be
5726 prompted for."
5727 (interactive)
5728 (let ((erc org-emphasis-regexp-components)
5729 (string "") beg end move s)
5730 (if (org-region-active-p)
5731 (setq beg (region-beginning)
5732 end (region-end)
5733 string (buffer-substring beg end))
5734 (setq move t))
5736 (unless char
5737 (message "Emphasis marker or tag: [%s]"
5738 (mapconcat #'car org-emphasis-alist ""))
5739 (setq char (read-char-exclusive)))
5740 (if (equal char ?\s)
5741 (setq s ""
5742 move nil)
5743 (unless (assoc (char-to-string char) org-emphasis-alist)
5744 (user-error "No such emphasis marker: \"%c\"" char))
5745 (setq s (char-to-string char)))
5746 (while (and (> (length string) 1)
5747 (equal (substring string 0 1) (substring string -1))
5748 (assoc (substring string 0 1) org-emphasis-alist))
5749 (setq string (substring string 1 -1)))
5750 (setq string (concat s string s))
5751 (when beg (delete-region beg end))
5752 (unless (or (bolp)
5753 (string-match (concat "[" (nth 0 erc) "\n]")
5754 (char-to-string (char-before (point)))))
5755 (insert " "))
5756 (unless (or (eobp)
5757 (string-match (concat "[" (nth 1 erc) "\n]")
5758 (char-to-string (char-after (point)))))
5759 (insert " ") (backward-char 1))
5760 (insert string)
5761 (and move (backward-char 1))))
5763 (defconst org-nonsticky-props
5764 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5766 (defsubst org-rear-nonsticky-at (pos)
5767 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5769 (defun org-activate-links (limit)
5770 "Add link properties to links.
5771 This includes angle, plain, and bracket links."
5772 (catch :exit
5773 (while (re-search-forward org-any-link-re limit t)
5774 (let* ((start (match-beginning 0))
5775 (end (match-end 0))
5776 (style (cond ((eq ?< (char-after start)) 'angle)
5777 ((eq ?\[ (char-after (1+ start))) 'bracket)
5778 (t 'plain))))
5779 (when (and (memq style org-highlight-links)
5780 ;; Do not confuse plain links with tags.
5781 (not (and (eq style 'plain)
5782 (let ((face (get-text-property
5783 (max (1- start) (point-min)) 'face)))
5784 (if (consp face) (memq 'org-tag face)
5785 (eq 'org-tag face))))))
5786 (let* ((link-object (save-excursion
5787 (goto-char start)
5788 (save-match-data (org-element-link-parser))))
5789 (link (org-element-property :raw-link link-object))
5790 (type (org-element-property :type link-object))
5791 (path (org-element-property :path link-object))
5792 (properties ;for link's visible part
5793 (list
5794 'face (pcase (org-link-get-parameter type :face)
5795 ((and (pred functionp) face) (funcall face path))
5796 ((and (pred facep) face) face)
5797 ((and (pred consp) face) face) ;anonymous
5798 (_ 'org-link))
5799 'mouse-face (or (org-link-get-parameter type :mouse-face)
5800 'highlight)
5801 'keymap (or (org-link-get-parameter type :keymap)
5802 org-mouse-map)
5803 'help-echo (pcase (org-link-get-parameter type :help-echo)
5804 ((and (pred stringp) echo) echo)
5805 ((and (pred functionp) echo) echo)
5806 (_ (concat "LINK: " link)))
5807 'htmlize-link (pcase (org-link-get-parameter type
5808 :htmlize-link)
5809 ((and (pred functionp) f) (funcall f))
5810 (_ `(:uri ,link)))
5811 'font-lock-multiline t)))
5812 (org-remove-flyspell-overlays-in start end)
5813 (org-rear-nonsticky-at end)
5814 (if (not (eq 'bracket style))
5815 (add-text-properties start end properties)
5816 ;; Handle invisible parts in bracket links.
5817 (remove-text-properties start end '(invisible nil))
5818 (let ((hidden
5819 (append `(invisible
5820 ,(or (org-link-get-parameter type :display)
5821 'org-link))
5822 properties))
5823 (visible-start (or (match-beginning 4) (match-beginning 2)))
5824 (visible-end (or (match-end 4) (match-end 2))))
5825 (add-text-properties start visible-start hidden)
5826 (add-text-properties visible-start visible-end properties)
5827 (add-text-properties visible-end end hidden)
5828 (org-rear-nonsticky-at visible-start)
5829 (org-rear-nonsticky-at visible-end)))
5830 (let ((f (org-link-get-parameter type :activate-func)))
5831 (when (functionp f)
5832 (funcall f start end path (eq style 'bracket))))
5833 (throw :exit t))))) ;signal success
5834 nil))
5836 (defun org-activate-code (limit)
5837 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5838 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5839 (remove-text-properties (match-beginning 0) (match-end 0)
5840 '(display t invisible t intangible t))
5843 (defcustom org-src-fontify-natively t
5844 "When non-nil, fontify code in code blocks.
5845 See also the `org-block' face."
5846 :type 'boolean
5847 :version "26.1"
5848 :package-version '(Org . "8.3")
5849 :group 'org-appearance
5850 :group 'org-babel)
5852 (defcustom org-allow-promoting-top-level-subtree nil
5853 "When non-nil, allow promoting a top level subtree.
5854 The leading star of the top level headline will be replaced
5855 by a #."
5856 :type 'boolean
5857 :version "24.1"
5858 :group 'org-appearance)
5860 (defun org-fontify-meta-lines-and-blocks (limit)
5861 (condition-case nil
5862 (org-fontify-meta-lines-and-blocks-1 limit)
5863 (error (message "Org mode fontification error in %S at %d"
5864 (current-buffer)
5865 (line-number-at-pos)))))
5867 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5868 "Fontify #+ lines and blocks."
5869 (let ((case-fold-search t))
5870 (when (re-search-forward
5871 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5872 limit t)
5873 (let ((beg (match-beginning 0))
5874 (block-start (match-end 0))
5875 (block-end nil)
5876 (lang (match-string 7))
5877 (beg1 (line-beginning-position 2))
5878 (dc1 (downcase (match-string 2)))
5879 (dc3 (downcase (match-string 3)))
5880 end end1 quoting block-type)
5881 (cond
5882 ((and (match-end 4) (equal dc3 "+begin"))
5883 ;; Truly a block
5884 (setq block-type (downcase (match-string 5))
5885 quoting (member block-type org-protecting-blocks))
5886 (when (re-search-forward
5887 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5888 nil t) ;; on purpose, we look further than LIMIT
5889 (setq end (min (point-max) (match-end 0))
5890 end1 (min (point-max) (1- (match-beginning 0))))
5891 (setq block-end (match-beginning 0))
5892 (when quoting
5893 (org-remove-flyspell-overlays-in beg1 end1)
5894 (remove-text-properties beg end
5895 '(display t invisible t intangible t)))
5896 (add-text-properties
5897 beg end '(font-lock-fontified t font-lock-multiline t))
5898 (add-text-properties beg beg1 '(face org-meta-line))
5899 (org-remove-flyspell-overlays-in beg beg1)
5900 (add-text-properties ; For end_src
5901 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5902 (org-remove-flyspell-overlays-in end1 end)
5903 (cond
5904 ((and lang (not (string= lang "")) org-src-fontify-natively)
5905 (org-src-font-lock-fontify-block lang block-start block-end)
5906 (add-text-properties beg1 block-end '(src-block t)))
5907 (quoting
5908 (add-text-properties beg1 (min (point-max) (1+ end1))
5909 (list 'face
5910 (list :inherit
5911 (let ((face-name
5912 (intern (format "org-block-%s" lang))))
5913 (append (and (facep face-name) (list face-name))
5914 '(org-block))))))) ; end of source block
5915 ((not org-fontify-quote-and-verse-blocks))
5916 ((string= block-type "quote")
5917 (add-face-text-property
5918 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5919 ((string= block-type "verse")
5920 (add-face-text-property
5921 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5922 (add-text-properties beg beg1 '(face org-block-begin-line))
5923 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5924 '(face org-block-end-line))
5926 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5927 (org-remove-flyspell-overlays-in
5928 (match-beginning 0)
5929 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5930 (add-text-properties
5931 beg (match-end 3)
5932 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5933 '(font-lock-fontified t invisible t)
5934 '(font-lock-fontified t face org-document-info-keyword)))
5935 (add-text-properties
5936 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5937 (if (string-equal dc1 "+title:")
5938 '(font-lock-fontified t face org-document-title)
5939 '(font-lock-fontified t face org-document-info))))
5940 ((string-prefix-p "+caption" dc1)
5941 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5942 (remove-text-properties (match-beginning 0) (match-end 0)
5943 '(display t invisible t intangible t))
5944 ;; Handle short captions.
5945 (save-excursion
5946 (beginning-of-line)
5947 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5948 (add-text-properties (line-beginning-position) (match-end 1)
5949 '(font-lock-fontified t face org-meta-line))
5950 (add-text-properties (match-end 0) (line-end-position)
5951 '(font-lock-fontified t face org-block))
5953 ((member dc3 '(" " ""))
5954 (org-remove-flyspell-overlays-in beg (match-end 0))
5955 (add-text-properties
5956 beg (match-end 0)
5957 '(font-lock-fontified t face font-lock-comment-face)))
5958 (t ;; just any other in-buffer setting, but not indented
5959 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5960 (remove-text-properties (match-beginning 0) (match-end 0)
5961 '(display t invisible t intangible t))
5962 (add-text-properties beg (match-end 0)
5963 '(font-lock-fontified t face org-meta-line))
5964 t))))))
5966 (defun org-fontify-drawers (limit)
5967 "Fontify drawers."
5968 (when (re-search-forward org-drawer-regexp limit t)
5969 (add-text-properties
5970 (match-beginning 0) (match-end 0)
5971 '(font-lock-fontified t face org-special-keyword))
5972 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5975 (defun org-fontify-macros (limit)
5976 "Fontify macros."
5977 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
5978 (let ((begin (match-beginning 0))
5979 (opening-end (match-beginning 1)))
5980 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
5981 (match-string 1))
5982 (let ((end (match-end 1))
5983 (closing-start (match-beginning 1)))
5984 (add-text-properties
5985 begin end
5986 '(font-lock-multiline t font-lock-fontified t face org-macro))
5987 (org-remove-flyspell-overlays-in begin end)
5988 (when org-hide-macro-markers
5989 (add-text-properties begin opening-end '(invisible t))
5990 (add-text-properties closing-start end '(invisible t)))
5991 t)))))
5993 (defun org-activate-footnote-links (limit)
5994 "Add text properties for footnotes."
5995 (let ((fn (org-footnote-next-reference-or-definition limit)))
5996 (when fn
5997 (let* ((beg (nth 1 fn))
5998 (end (nth 2 fn))
5999 (label (car fn))
6000 (referencep (/= (line-beginning-position) beg)))
6001 (when (and referencep (nth 3 fn))
6002 (save-excursion
6003 (goto-char beg)
6004 (search-forward (or label "fn:"))
6005 (org-remove-flyspell-overlays-in beg (match-end 0))))
6006 (add-text-properties beg end
6007 (list 'mouse-face 'highlight
6008 'keymap org-mouse-map
6009 'help-echo
6010 (if referencep "Footnote reference"
6011 "Footnote definition")
6012 'font-lock-fontified t
6013 'font-lock-multiline t
6014 'face 'org-footnote))))))
6016 (defun org-activate-dates (limit)
6017 "Add text properties for dates."
6018 (when (and (re-search-forward org-tsr-regexp-both limit t)
6019 (not (equal (char-before (match-beginning 0)) 91)))
6020 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6021 (add-text-properties (match-beginning 0) (match-end 0)
6022 (list 'mouse-face 'highlight
6023 'keymap org-mouse-map))
6024 (org-rear-nonsticky-at (match-end 0))
6025 (when org-display-custom-times
6026 ;; If it's a date range, activate custom time for second date.
6027 (when (match-end 3)
6028 (org-display-custom-time (match-beginning 3) (match-end 3)))
6029 (org-display-custom-time (match-beginning 1) (match-end 1)))
6032 (defvar-local org-target-link-regexp nil
6033 "Regular expression matching radio targets in plain text.")
6035 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6036 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6037 border border border))
6038 "Regular expression matching a link target.")
6040 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6041 "Regular expression matching a radio target.")
6043 (defconst org-any-target-regexp
6044 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6045 "Regular expression matching any target.")
6047 (defun org-activate-target-links (limit)
6048 "Add text properties for target matches."
6049 (when org-target-link-regexp
6050 (let ((case-fold-search t))
6051 (when (re-search-forward org-target-link-regexp limit t)
6052 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6053 (add-text-properties (match-beginning 1) (match-end 1)
6054 (list 'mouse-face 'highlight
6055 'keymap org-mouse-map
6056 'help-echo "Radio target link"
6057 'org-linked-text t))
6058 (org-rear-nonsticky-at (match-end 1))
6059 t))))
6061 (defun org-update-radio-target-regexp ()
6062 "Find all radio targets in this file and update the regular expression.
6063 Also refresh fontification if needed."
6064 (interactive)
6065 (let ((old-regexp org-target-link-regexp)
6066 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6067 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6068 (targets
6069 (org-with-wide-buffer
6070 (goto-char (point-min))
6071 (let (rtn)
6072 (while (re-search-forward org-radio-target-regexp nil t)
6073 ;; Make sure point is really within the object.
6074 (backward-char)
6075 (let ((obj (org-element-context)))
6076 (when (eq (org-element-type obj) 'radio-target)
6077 (cl-pushnew (org-element-property :value obj) rtn
6078 :test #'equal))))
6079 rtn))))
6080 (setq org-target-link-regexp
6081 (and targets
6082 (concat before-re
6083 (mapconcat
6084 (lambda (x)
6085 (replace-regexp-in-string
6086 " +" "\\s-+" (regexp-quote x) t t))
6087 targets
6088 "\\|")
6089 after-re)))
6090 (unless (equal old-regexp org-target-link-regexp)
6091 ;; Clean-up cache.
6092 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6093 ((not org-target-link-regexp) old-regexp)
6095 (concat before-re
6096 (mapconcat
6097 (lambda (re)
6098 (substring re (length before-re)
6099 (- (length after-re))))
6100 (list old-regexp org-target-link-regexp)
6101 "\\|")
6102 after-re)))))
6103 (org-with-wide-buffer
6104 (goto-char (point-min))
6105 (while (re-search-forward regexp nil t)
6106 (org-element-cache-refresh (match-beginning 1)))))
6107 ;; Re fontify buffer.
6108 (when (memq 'radio org-highlight-links)
6109 (org-restart-font-lock)))))
6111 (defvar org-latex-and-related-regexp nil
6112 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6114 (defun org-compute-latex-and-related-regexp ()
6115 "Compute regular expression for LaTeX, entities and sub/superscript.
6116 Result depends on variable `org-highlight-latex-and-related'."
6117 (setq-local
6118 org-latex-and-related-regexp
6119 (let* ((re-sub
6120 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6121 ((eq org-use-sub-superscripts '{})
6122 (list org-match-substring-with-braces-regexp))
6123 (org-use-sub-superscripts (list org-match-substring-regexp))))
6124 (re-latex
6125 (when (memq 'latex org-highlight-latex-and-related)
6126 (let ((matchers (plist-get org-format-latex-options :matchers)))
6127 (delq nil
6128 (mapcar (lambda (x)
6129 (and (member (car x) matchers) (nth 1 x)))
6130 org-latex-regexps)))))
6131 (re-entities
6132 (when (memq 'entities org-highlight-latex-and-related)
6133 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6134 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6136 (defun org-do-latex-and-related (limit)
6137 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6138 LIMIT bounds the search for syntax to highlight. Stop at first
6139 highlighted object, if any. Return t if some highlighting was
6140 done, nil otherwise."
6141 (when (org-string-nw-p org-latex-and-related-regexp)
6142 (catch 'found
6143 (while (re-search-forward org-latex-and-related-regexp limit t)
6144 (unless
6145 (cl-some
6146 (lambda (f)
6147 (memq f '(org-code org-verbatim underline org-special-keyword)))
6148 (save-excursion
6149 (goto-char (1+ (match-beginning 0)))
6150 (face-at-point nil t)))
6151 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6152 '(?_ ?^))
6154 0)))
6155 (font-lock-prepend-text-property
6156 (+ offset (match-beginning 0)) (match-end 0)
6157 'face 'org-latex-and-related)
6158 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6159 '(font-lock-multiline t)))
6160 (throw 'found t)))
6161 nil)))
6163 (defun org-restart-font-lock ()
6164 "Restart `font-lock-mode', to force refontification."
6165 (when (and (boundp 'font-lock-mode) font-lock-mode)
6166 (font-lock-mode -1)
6167 (font-lock-mode 1)))
6169 (defun org-activate-tags (limit)
6170 (when (re-search-forward
6171 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6172 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6173 (add-text-properties (match-beginning 1) (match-end 1)
6174 (list 'mouse-face 'highlight
6175 'keymap org-mouse-map))
6176 (org-rear-nonsticky-at (match-end 1))
6179 (defun org-outline-level ()
6180 "Compute the outline level of the heading at point.
6182 If this is called at a normal headline, the level is the number
6183 of stars. Use `org-reduced-level' to remove the effect of
6184 `org-odd-levels'. Unlike to `org-current-level', this function
6185 takes into consideration inlinetasks."
6186 (org-with-wide-buffer
6187 (end-of-line)
6188 (if (re-search-backward org-outline-regexp-bol nil t)
6189 (1- (- (match-end 0) (match-beginning 0)))
6190 0)))
6192 (defvar org-font-lock-keywords nil)
6194 (defsubst org-re-property (property &optional literal allow-null value)
6195 "Return a regexp matching a PROPERTY line.
6197 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6198 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6199 non-nil, match properties even without a value.
6201 Match group 3 is set to the value when it exists. If there is no
6202 value and ALLOW-NULL is non-nil, it is set to the empty string.
6204 With optional argument VALUE, match only property lines with
6205 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6206 unless LITERAL is non-nil."
6207 (concat
6208 "^\\(?4:[ \t]*\\)"
6209 (format "\\(?1::\\(?2:%s\\):\\)"
6210 (if literal property (regexp-quote property)))
6211 (cond (value
6212 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6213 (if literal value (regexp-quote value))))
6214 (allow-null
6215 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6217 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6219 (defconst org-property-re
6220 (org-re-property "\\S-+" 'literal t)
6221 "Regular expression matching a property line.
6222 There are four matching groups:
6223 1: :PROPKEY: including the leading and trailing colon,
6224 2: PROPKEY without the leading and trailing colon,
6225 3: PROPVAL without leading or trailing spaces,
6226 4: the indentation of the current line,
6227 5: trailing whitespace.")
6229 (defvar org-font-lock-hook nil
6230 "Functions to be called for special font lock stuff.")
6232 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6234 (defvar org-font-lock-set-keywords-hook nil
6235 "Functions that can manipulate `org-font-lock-extra-keywords'.
6236 This is called after `org-font-lock-extra-keywords' is defined, but before
6237 it is installed to be used by font lock. This can be useful if something
6238 needs to be inserted at a specific position in the font-lock sequence.")
6240 (defun org-font-lock-hook (limit)
6241 "Run `org-font-lock-hook' within LIMIT."
6242 (run-hook-with-args 'org-font-lock-hook limit))
6244 (defun org-set-font-lock-defaults ()
6245 "Set font lock defaults for the current buffer."
6246 (let* ((em org-fontify-emphasized-text)
6247 (lk org-highlight-links)
6248 (org-font-lock-extra-keywords
6249 (list
6250 ;; Call the hook
6251 '(org-font-lock-hook)
6252 ;; Headlines
6253 `(,(if org-fontify-whole-heading-line
6254 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6255 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6256 (1 (org-get-level-face 1))
6257 (2 (org-get-level-face 2))
6258 (3 (org-get-level-face 3)))
6259 ;; Table lines
6260 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6261 (1 'org-table t))
6262 ;; Table internals
6263 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6264 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6265 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6266 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6267 ;; Drawers
6268 '(org-fontify-drawers)
6269 ;; Properties
6270 (list org-property-re
6271 '(1 'org-special-keyword t)
6272 '(3 'org-property-value t))
6273 ;; Link related fontification.
6274 '(org-activate-links)
6275 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6276 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6277 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6278 (when (memq 'footnote lk) '(org-activate-footnote-links))
6279 ;; Targets.
6280 (list org-any-target-regexp '(0 'org-target t))
6281 ;; Diary sexps.
6282 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6283 ;; Macro
6284 '(org-fontify-macros)
6285 ;; TODO keyword
6286 (list (format org-heading-keyword-regexp-format
6287 org-todo-regexp)
6288 '(2 (org-get-todo-face 2) t))
6289 ;; DONE
6290 (if org-fontify-done-headline
6291 (list (format org-heading-keyword-regexp-format
6292 (concat
6293 "\\(?:"
6294 (mapconcat 'regexp-quote org-done-keywords "\\|")
6295 "\\)"))
6296 '(2 'org-headline-done t))
6297 nil)
6298 ;; Priorities
6299 '(org-font-lock-add-priority-faces)
6300 ;; Tags
6301 '(org-font-lock-add-tag-faces)
6302 ;; Tags groups
6303 (when (and org-group-tags org-tag-groups-alist)
6304 (list (concat org-outline-regexp-bol ".+\\(:"
6305 (regexp-opt (mapcar 'car org-tag-groups-alist))
6306 ":\\).*$")
6307 '(1 'org-tag-group prepend)))
6308 ;; Special keywords
6309 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6310 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6311 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6312 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6313 ;; Emphasis
6314 (when em '(org-do-emphasis-faces))
6315 ;; Checkboxes
6316 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6317 1 'org-checkbox prepend)
6318 (when (cdr (assq 'checkbox org-list-automatic-rules))
6319 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6320 (0 (org-get-checkbox-statistics-face) t)))
6321 ;; Description list items
6322 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6323 1 'org-list-dt prepend)
6324 ;; ARCHIVEd headings
6325 (list (concat
6326 org-outline-regexp-bol
6327 "\\(.*:" org-archive-tag ":.*\\)")
6328 '(1 'org-archived prepend))
6329 ;; Specials
6330 '(org-do-latex-and-related)
6331 '(org-fontify-entities)
6332 '(org-raise-scripts)
6333 ;; Code
6334 '(org-activate-code (1 'org-code t))
6335 ;; COMMENT
6336 (list (format
6337 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6338 org-todo-regexp
6339 org-comment-string)
6340 '(9 'org-special-keyword t))
6341 ;; Blocks and meta lines
6342 '(org-fontify-meta-lines-and-blocks))))
6343 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6344 (run-hooks 'org-font-lock-set-keywords-hook)
6345 ;; Now set the full font-lock-keywords
6346 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6347 (setq-local font-lock-defaults
6348 '(org-font-lock-keywords t nil nil backward-paragraph))
6349 (kill-local-variable 'font-lock-keywords)
6350 nil))
6352 (defun org-toggle-pretty-entities ()
6353 "Toggle the composition display of entities as UTF8 characters."
6354 (interactive)
6355 (setq-local org-pretty-entities (not org-pretty-entities))
6356 (org-restart-font-lock)
6357 (if org-pretty-entities
6358 (message "Entities are now displayed as UTF8 characters")
6359 (save-restriction
6360 (widen)
6361 (decompose-region (point-min) (point-max))
6362 (message "Entities are now displayed as plain text"))))
6364 (defvar-local org-custom-properties-overlays nil
6365 "List of overlays used for custom properties.")
6367 (defun org-toggle-custom-properties-visibility ()
6368 "Display or hide properties in `org-custom-properties'."
6369 (interactive)
6370 (if org-custom-properties-overlays
6371 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6372 (setq org-custom-properties-overlays nil))
6373 (when org-custom-properties
6374 (org-with-wide-buffer
6375 (goto-char (point-min))
6376 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6377 (while (re-search-forward regexp nil t)
6378 (let ((end (cdr (save-match-data (org-get-property-block)))))
6379 (when (and end (< (point) end))
6380 ;; Hide first custom property in current drawer.
6381 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6382 (overlay-put o 'invisible t)
6383 (overlay-put o 'org-custom-property t)
6384 (push o org-custom-properties-overlays))
6385 ;; Hide additional custom properties in the same drawer.
6386 (while (re-search-forward regexp end t)
6387 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6388 (overlay-put o 'invisible t)
6389 (overlay-put o 'org-custom-property t)
6390 (push o org-custom-properties-overlays)))))
6391 ;; Each entry is limited to a single property drawer.
6392 (outline-next-heading)))))))
6394 (defun org-fontify-entities (limit)
6395 "Find an entity to fontify."
6396 (let (ee)
6397 (when org-pretty-entities
6398 (catch 'match
6399 ;; "\_ "-family is left out on purpose. Only the first one,
6400 ;; i.e., "\_ ", could be fontified anyway, and it would be
6401 ;; confusing when adding a second white space character.
6402 (while (re-search-forward
6403 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6404 limit t)
6405 (when (and (not (org-at-comment-p))
6406 (setq ee (org-entity-get (match-string 1)))
6407 (= (length (nth 6 ee)) 1))
6408 (let* ((end (if (equal (match-string 2) "{}")
6409 (match-end 2)
6410 (match-end 1))))
6411 (add-text-properties
6412 (match-beginning 0) end
6413 (list 'font-lock-fontified t))
6414 (compose-region (match-beginning 0) end
6415 (nth 6 ee) nil)
6416 (backward-char 1)
6417 (throw 'match t))))
6418 nil))))
6420 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6421 "Fontify string S like in Org mode."
6422 (with-temp-buffer
6423 (insert s)
6424 (let ((org-odd-levels-only odd-levels))
6425 (org-mode)
6426 (org-font-lock-ensure)
6427 (buffer-string))))
6429 (defvar org-m nil)
6430 (defvar org-l nil)
6431 (defvar org-f nil)
6432 (defun org-get-level-face (n)
6433 "Get the right face for match N in font-lock matching of headlines."
6434 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6435 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6436 (if org-cycle-level-faces
6437 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6438 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6439 (cond
6440 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6441 ((eq n 2) org-f)
6442 (t (unless org-level-color-stars-only org-f))))
6444 (defun org-face-from-face-or-color (context inherit face-or-color)
6445 "Create a face list that inherits INHERIT, but sets the foreground color.
6446 When FACE-OR-COLOR is not a string, just return it."
6447 (if (stringp face-or-color)
6448 (list :inherit inherit
6449 (cdr (assoc context org-faces-easy-properties))
6450 face-or-color)
6451 face-or-color))
6453 (defun org-get-todo-face (kwd)
6454 "Get the right face for a TODO keyword KWD.
6455 If KWD is a number, get the corresponding match group."
6456 (when (numberp kwd) (setq kwd (match-string kwd)))
6457 (or (org-face-from-face-or-color
6458 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6459 (and (member kwd org-done-keywords) 'org-done)
6460 'org-todo))
6462 (defun org-get-priority-face (priority)
6463 "Get the right face for PRIORITY.
6464 PRIORITY is a character."
6465 (or (org-face-from-face-or-color
6466 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6467 'org-priority))
6469 (defun org-get-tag-face (tag)
6470 "Get the right face for TAG.
6471 If TAG is a number, get the corresponding match group."
6472 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6473 (or (org-face-from-face-or-color
6474 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6475 'org-tag)))
6477 (defun org-font-lock-add-priority-faces (limit)
6478 "Add the special priority faces."
6479 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6480 (add-text-properties
6481 (match-beginning 1) (match-end 1)
6482 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6483 'font-lock-fontified t))))
6485 (defun org-font-lock-add-tag-faces (limit)
6486 "Add the special tag faces."
6487 (when (and org-tag-faces org-tags-special-faces-re)
6488 (while (re-search-forward org-tags-special-faces-re limit t)
6489 (add-text-properties (match-beginning 1) (match-end 1)
6490 (list 'face (org-get-tag-face 1)
6491 'font-lock-fontified t))
6492 (backward-char 1))))
6494 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6495 "Remove fontification and activation overlays from links."
6496 (font-lock-default-unfontify-region beg end)
6497 (let* ((buffer-undo-list t)
6498 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6499 (inhibit-modification-hooks t)
6500 deactivate-mark buffer-file-name buffer-file-truename)
6501 (decompose-region beg end)
6502 (remove-text-properties beg end
6503 '(mouse-face t keymap t org-linked-text t
6504 invisible t intangible t
6505 org-emphasis t))
6506 (org-remove-font-lock-display-properties beg end)))
6508 (defconst org-script-display '(((raise -0.3) (height 0.7))
6509 ((raise 0.3) (height 0.7))
6510 ((raise -0.5))
6511 ((raise 0.5)))
6512 "Display properties for showing superscripts and subscripts.")
6514 (defun org-remove-font-lock-display-properties (beg end)
6515 "Remove specific display properties that have been added by font lock.
6516 The will remove the raise properties that are used to show superscripts
6517 and subscripts."
6518 (let (next prop)
6519 (while (< beg end)
6520 (setq next (next-single-property-change beg 'display nil end)
6521 prop (get-text-property beg 'display))
6522 (when (member prop org-script-display)
6523 (put-text-property beg next 'display nil))
6524 (setq beg next))))
6526 (defun org-raise-scripts (limit)
6527 "Add raise properties to sub/superscripts."
6528 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6529 (re-search-forward
6530 (if (eq org-use-sub-superscripts t)
6531 org-match-substring-regexp
6532 org-match-substring-with-braces-regexp)
6533 limit t))
6534 (let* ((pos (point)) table-p comment-p
6535 (mpos (match-beginning 3))
6536 (emph-p (get-text-property mpos 'org-emphasis))
6537 (link-p (get-text-property mpos 'mouse-face))
6538 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6539 (goto-char (point-at-bol))
6540 (setq table-p (looking-at-p org-table-dataline-regexp)
6541 comment-p (looking-at-p "^[ \t]*#[ +]"))
6542 (goto-char pos)
6543 ;; Handle a_b^c
6544 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6545 (unless (or comment-p emph-p link-p keyw-p)
6546 (put-text-property (match-beginning 3) (match-end 0)
6547 'display
6548 (if (equal (char-after (match-beginning 2)) ?^)
6549 (nth (if table-p 3 1) org-script-display)
6550 (nth (if table-p 2 0) org-script-display)))
6551 (add-text-properties (match-beginning 2) (match-end 2)
6552 (list 'invisible t))
6553 (when (and (eq (char-after (match-beginning 3)) ?{)
6554 (eq (char-before (match-end 3)) ?}))
6555 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6556 (list 'invisible t))
6557 (add-text-properties (1- (match-end 3)) (match-end 3)
6558 (list 'invisible t))))
6559 t)))
6561 (defun org-remove-empty-overlays-at (pos)
6562 "Remove outline overlays that do not contain non-white stuff."
6563 (dolist (o (overlays-at pos))
6564 (and (eq 'outline (overlay-get o 'invisible))
6565 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6566 (overlay-end o))))
6567 (delete-overlay o))))
6569 (defun org-show-empty-lines-in-parent ()
6570 "Move to the parent and re-show empty lines before visible headlines."
6571 (save-excursion
6572 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6573 (org-cycle-show-empty-lines context))))
6575 (defun org-files-list ()
6576 "Return `org-agenda-files' list, plus all open Org files.
6577 This is useful for operations that need to scan all of a user's
6578 open and agenda-wise Org files."
6579 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6580 (dolist (buf (buffer-list))
6581 (with-current-buffer buf
6582 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6583 (cl-pushnew (expand-file-name (buffer-file-name)) files
6584 :test #'equal))))
6585 files))
6587 (defsubst org-entry-beginning-position ()
6588 "Return the beginning position of the current entry."
6589 (save-excursion (org-back-to-heading t) (point)))
6591 (defsubst org-entry-end-position ()
6592 "Return the end position of the current entry."
6593 (save-excursion (outline-next-heading) (point)))
6595 (defun org-subtree-end-visible-p ()
6596 "Is the end of the current subtree visible?"
6597 (pos-visible-in-window-p
6598 (save-excursion (org-end-of-subtree t) (point))))
6600 (defun org-first-headline-recenter ()
6601 "Move cursor to the first headline and recenter the headline."
6602 (let ((window (get-buffer-window)))
6603 (when window
6604 (goto-char (point-min))
6605 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6606 (set-window-start window (line-beginning-position))))))
6609 ;;; Visibility (headlines, blocks, drawers)
6611 ;;;; Headlines visibility
6613 (defun org-show-entry ()
6614 "Show the body directly following this heading.
6615 Show the heading too, if it is currently invisible."
6616 (interactive)
6617 (save-excursion
6618 (ignore-errors
6619 (org-back-to-heading t)
6620 (org-flag-region
6621 (line-end-position 0)
6622 (save-excursion
6623 (if (re-search-forward
6624 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6625 (match-beginning 1)
6626 (point-max)))
6628 'outline))))
6630 (defun org-show-children (&optional level)
6631 "Show all direct subheadings of this heading.
6632 Prefix arg LEVEL is how many levels below the current level
6633 should be shown. Default is enough to cause the following
6634 heading to appear."
6635 (interactive "p")
6636 (save-excursion
6637 (org-back-to-heading t)
6638 (let* ((current-level (funcall outline-level))
6639 (max-level (org-get-valid-level
6640 current-level
6641 (if level (prefix-numeric-value level) 1)))
6642 (end (save-excursion (org-end-of-subtree t t)))
6643 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6644 (past-first-child nil)
6645 ;; Make sure to skip inlinetasks.
6646 (re (format regexp-fmt
6647 current-level
6648 (cond
6649 ((not (featurep 'org-inlinetask)) "")
6650 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6652 (t (1- org-inlinetask-min-level))))))
6653 ;; Display parent heading.
6654 (org-flag-heading nil)
6655 (forward-line)
6656 ;; Display children. First child may be deeper than expected
6657 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6658 ;; MAX-LEVEL accordingly.
6659 (while (re-search-forward re end t)
6660 (unless past-first-child
6661 (setq re (format regexp-fmt
6662 current-level
6663 (max (funcall outline-level) max-level)))
6664 (setq past-first-child t))
6665 (org-flag-heading nil)))))
6667 (defun org-show-subtree ()
6668 "Show everything after this heading at deeper levels."
6669 (interactive)
6670 (org-flag-region
6671 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6673 ;;;; Blocks visibility
6675 (defun org-hide-block-toggle-maybe ()
6676 "Toggle visibility of block at point.
6677 Unlike to `org-hide-block-toggle', this function does not throw
6678 an error. Return a non-nil value when toggling is successful."
6679 (interactive)
6680 (ignore-errors (org-hide-block-toggle)))
6682 (defun org-hide-block-toggle (&optional force)
6683 "Toggle the visibility of the current block.
6684 When optional argument FORCE is `off', make block visible. If it
6685 is non-nil, hide it unconditionally. Throw an error when not at
6686 a block. Return a non-nil value when toggling is successful."
6687 (interactive)
6688 (let ((element (org-element-at-point)))
6689 (unless (memq (org-element-type element)
6690 '(center-block comment-block dynamic-block example-block
6691 export-block quote-block special-block
6692 src-block verse-block))
6693 (user-error "Not at a block"))
6694 (let* ((post (org-element-property :post-affiliated element))
6695 (start (save-excursion
6696 (goto-char post)
6697 (line-end-position)))
6698 (end (save-excursion
6699 (goto-char (org-element-property :end element))
6700 (skip-chars-backward " \t\n")
6701 (line-end-position))))
6702 ;; Do nothing when not before or at the block opening line or at
6703 ;; the block closing line.
6704 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6705 (cond ((eq force 'off)
6706 (org-flag-region start end nil 'org-hide-block))
6707 (force
6708 (org-flag-region start end t 'org-hide-block))
6709 ((eq (get-char-property start 'invisible) 'org-hide-block)
6710 (org-flag-region start end nil 'org-hide-block))
6712 (org-flag-region start end t 'org-hide-block)))
6713 ;; When the block is hidden away, make sure point is left in
6714 ;; a visible part of the buffer.
6715 (when (invisible-p (max (1- (point)) (point-min)))
6716 (goto-char post))
6717 ;; Signal success.
6718 t))))
6720 (defun org-hide-block-toggle-all ()
6721 "Toggle the visibility of all blocks in the current buffer."
6722 (org-block-map 'org-hide-block-toggle))
6724 (defun org-hide-block-all ()
6725 "Fold all blocks in the current buffer."
6726 (interactive)
6727 (org-show-all '(blocks))
6728 (org-block-map 'org-hide-block-toggle-maybe))
6730 ;;;; Drawers visibility
6732 (defun org-cycle-hide-drawers (state &optional exceptions)
6733 "Re-hide all drawers after a visibility state change.
6734 STATE should be one of the symbols listed in the docstring of
6735 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6736 a list of strings specifying which drawers should not be hidden."
6737 (when (and (derived-mode-p 'org-mode)
6738 (not (memq state '(overview folded contents))))
6739 (save-excursion
6740 (let* ((globalp (eq state 'all))
6741 (beg (if globalp (point-min) (point)))
6742 (end (if globalp (point-max)
6743 (if (eq state 'children)
6744 (save-excursion (outline-next-heading) (point))
6745 (org-end-of-subtree t)))))
6746 (goto-char beg)
6747 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6748 (unless (member-ignore-case (match-string 1) exceptions)
6749 (let ((drawer (org-element-at-point)))
6750 (when (memq (org-element-type drawer) '(drawer property-drawer))
6751 (org-flag-drawer t drawer)
6752 ;; Make sure to skip drawer entirely or we might flag
6753 ;; it another time when matching its ending line with
6754 ;; `org-drawer-regexp'.
6755 (goto-char (org-element-property :end drawer))))))))))
6757 (defun org-flag-drawer (flag &optional element)
6758 "When FLAG is non-nil, hide the drawer we are at.
6759 Otherwise make it visible. When optional argument ELEMENT is
6760 a parsed drawer, as returned by `org-element-at-point', hide or
6761 show that drawer instead."
6762 (let ((drawer (or element
6763 (and (save-excursion
6764 (beginning-of-line)
6765 (looking-at-p org-drawer-regexp))
6766 (org-element-at-point)))))
6767 (when (memq (org-element-type drawer) '(drawer property-drawer))
6768 (let ((post (org-element-property :post-affiliated drawer)))
6769 (org-flag-region
6770 (save-excursion (goto-char post) (line-end-position))
6771 (save-excursion (goto-char (org-element-property :end drawer))
6772 (skip-chars-backward " \t\n")
6773 (line-end-position))
6774 flag 'org-hide-drawer)
6775 ;; When the drawer is hidden away, make sure point lies in
6776 ;; a visible part of the buffer.
6777 (when (invisible-p (max (1- (point)) (point-min)))
6778 (goto-char post))))))
6780 ;;;; Visibility cycling
6782 (defvar-local org-cycle-global-status nil)
6783 (put 'org-cycle-global-status 'org-state t)
6784 (defvar-local org-cycle-subtree-status nil)
6785 (put 'org-cycle-subtree-status 'org-state t)
6787 (defun org-show-all (&optional types)
6788 "Show all contents in the visible part of the buffer.
6789 By default, the function expands headings, blocks and drawers.
6790 When optional argument TYPE is a list of symbols among `blocks',
6791 `drawers' and `headings', to only expand one specific type."
6792 (dolist (type (or types '(blocks drawers headings)))
6793 (org-flag-region (point-min) (point-max) nil
6794 (pcase type
6795 (`blocks 'org-hide-block)
6796 (`drawers 'org-hide-drawer)
6797 (`headings 'outline)
6798 (_ (error "Invalid type: %S" type))))))
6800 ;;;###autoload
6801 (defun org-cycle (&optional arg)
6802 "TAB-action and visibility cycling for Org mode.
6804 This is the command invoked in Org mode by the `TAB' key. Its main
6805 purpose is outline visibility cycling, but it also invokes other actions
6806 in special contexts.
6808 When this function is called with a `\\[universal-argument]' prefix, rotate \
6809 the entire
6810 buffer through 3 states (global cycling)
6811 1. OVERVIEW: Show only top-level headlines.
6812 2. CONTENTS: Show all headlines of all levels, but no body text.
6813 3. SHOW ALL: Show everything.
6815 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6816 switch to the startup visibility,
6817 determined by the variable `org-startup-folded', and by any VISIBILITY
6818 properties in the buffer.
6820 With a `\\[universal-argument] \\[universal-argument] \
6821 \\[universal-argument]' prefix argument, show the entire buffer, including
6822 any drawers.
6824 When inside a table, re-align the table and move to the next field.
6826 When point is at the beginning of a headline, rotate the subtree started
6827 by this line through 3 different states (local cycling)
6828 1. FOLDED: Only the main headline is shown.
6829 2. CHILDREN: The main headline and the direct children are shown.
6830 From this state, you can move to one of the children
6831 and zoom in further.
6832 3. SUBTREE: Show the entire subtree, including body text.
6833 If there is no subtree, switch directly from CHILDREN to FOLDED.
6835 When point is at the beginning of an empty headline and the variable
6836 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6837 of the headline by demoting and promoting it to likely levels. This
6838 speeds up creation document structure by pressing `TAB' once or several
6839 times right after creating a new headline.
6841 When there is a numeric prefix, go up to a heading with level ARG, do
6842 a `show-subtree' and return to the previous cursor position. If ARG
6843 is negative, go up that many levels.
6845 When point is not at the beginning of a headline, execute the global
6846 binding for `TAB', which is re-indenting the line. See the option
6847 `org-cycle-emulate-tab' for details.
6849 As a special case, if point is at the beginning of the buffer and there is
6850 no headline in line 1, this function will act as if called with prefix arg
6851 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6852 prefix arg, but only
6853 if the variable `org-cycle-global-at-bob' is t."
6854 (interactive "P")
6855 (org-load-modules-maybe)
6856 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6857 (and org-cycle-level-after-item/entry-creation
6858 (or (org-cycle-level)
6859 (org-cycle-item-indentation))))
6860 (let* ((limit-level
6861 (or org-cycle-max-level
6862 (and (boundp 'org-inlinetask-min-level)
6863 org-inlinetask-min-level
6864 (1- org-inlinetask-min-level))))
6865 (nstars (and limit-level
6866 (if org-odd-levels-only
6867 (and limit-level (1- (* limit-level 2)))
6868 limit-level)))
6869 (org-outline-regexp
6870 (if (not (derived-mode-p 'org-mode))
6871 outline-regexp
6872 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6873 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6874 (not (looking-at org-outline-regexp))))
6875 (org-cycle-hook
6876 (if bob-special
6877 (delq 'org-optimize-window-after-visibility-change
6878 (copy-sequence org-cycle-hook))
6879 org-cycle-hook))
6880 (pos (point)))
6882 (cond
6884 ((equal arg '(16))
6885 (setq last-command 'dummy)
6886 (org-set-startup-visibility)
6887 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6889 ((equal arg '(64))
6890 (org-show-all)
6891 (org-unlogged-message "Entire buffer visible, including drawers"))
6893 ((equal arg '(4)) (org-cycle-internal-global))
6895 ;; Try hiding block at point.
6896 ((org-hide-block-toggle-maybe))
6898 ;; Try cdlatex TAB completion
6899 ((org-try-cdlatex-tab))
6901 ;; Table: enter it or move to the next field.
6902 ((org-at-table-p 'any)
6903 (if (org-at-table.el-p)
6904 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6905 Use `\\[org-edit-special]' to edit table.el tables"))
6906 (if arg (org-table-edit-field t)
6907 (org-table-justify-field-maybe)
6908 (call-interactively 'org-table-next-field))))
6910 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6912 ;; Global cycling: delegate to `org-cycle-internal-global'.
6913 (bob-special (org-cycle-internal-global))
6915 ;; Drawers: delegate to `org-flag-drawer'.
6916 ((save-excursion
6917 (beginning-of-line 1)
6918 (looking-at org-drawer-regexp))
6919 (org-flag-drawer ; toggle block visibility
6920 (not (get-char-property (match-end 0) 'invisible))))
6922 ;; Show-subtree, ARG levels up from here.
6923 ((integerp arg)
6924 (save-excursion
6925 (org-back-to-heading)
6926 (outline-up-heading (if (< arg 0) (- arg)
6927 (- (funcall outline-level) arg)))
6928 (org-show-subtree)))
6930 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6931 ((and (featurep 'org-inlinetask)
6932 (org-inlinetask-at-task-p)
6933 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6934 (org-inlinetask-toggle-visibility))
6936 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6937 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6938 (save-excursion (move-beginning-of-line 1)
6939 (looking-at org-outline-regexp)))
6940 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6941 (org-cycle-internal-local))
6943 ;; From there: TAB emulation and template completion.
6944 (buffer-read-only (org-back-to-heading))
6946 ((run-hook-with-args-until-success
6947 'org-tab-after-check-for-cycling-hook))
6949 ((run-hook-with-args-until-success
6950 'org-tab-before-tab-emulation-hook))
6952 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6953 (or (not (bolp))
6954 (not (looking-at org-outline-regexp))))
6955 (call-interactively (global-key-binding "\t")))
6957 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6958 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6959 (or (and (eq org-cycle-emulate-tab 'white)
6960 (= (match-end 0) (point-at-eol)))
6961 (and (eq org-cycle-emulate-tab 'whitestart)
6962 (>= (match-end 0) pos))))
6964 (eq org-cycle-emulate-tab t))
6965 (call-interactively (global-key-binding "\t")))
6967 (t (save-excursion
6968 (org-back-to-heading)
6969 (org-cycle)))))))
6971 (defun org-cycle-internal-global ()
6972 "Do the global cycling action."
6973 ;; Hack to avoid display of messages for .org attachments in Gnus
6974 (let ((ga (string-match "\\*fontification" (buffer-name))))
6975 (cond
6976 ((and (eq last-command this-command)
6977 (eq org-cycle-global-status 'overview))
6978 ;; We just created the overview - now do table of contents
6979 ;; This can be slow in very large buffers, so indicate action
6980 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6981 (unless ga (org-unlogged-message "CONTENTS..."))
6982 (org-content)
6983 (unless ga (org-unlogged-message "CONTENTS...done"))
6984 (setq org-cycle-global-status 'contents)
6985 (run-hook-with-args 'org-cycle-hook 'contents))
6987 ((and (eq last-command this-command)
6988 (eq org-cycle-global-status 'contents))
6989 ;; We just showed the table of contents - now show everything
6990 (run-hook-with-args 'org-pre-cycle-hook 'all)
6991 (org-show-all '(headings blocks))
6992 (unless ga (org-unlogged-message "SHOW ALL"))
6993 (setq org-cycle-global-status 'all)
6994 (run-hook-with-args 'org-cycle-hook 'all))
6997 ;; Default action: go to overview
6998 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6999 (org-overview)
7000 (unless ga (org-unlogged-message "OVERVIEW"))
7001 (setq org-cycle-global-status 'overview)
7002 (run-hook-with-args 'org-cycle-hook 'overview)))))
7004 (defvar org-called-with-limited-levels nil
7005 "Non-nil when `org-with-limited-levels' is currently active.")
7007 (defun org-cycle-internal-local ()
7008 "Do the local cycling action."
7009 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7010 ;; First, determine end of headline (EOH), end of subtree or item
7011 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7012 (save-excursion
7013 (if (org-at-item-p)
7014 (progn
7015 (beginning-of-line)
7016 (setq struct (org-list-struct))
7017 (setq eoh (point-at-eol))
7018 (setq eos (org-list-get-item-end-before-blank (point) struct))
7019 (setq has-children (org-list-has-child-p (point) struct)))
7020 (org-back-to-heading)
7021 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7022 (setq eos (save-excursion (org-end-of-subtree t t)
7023 (when (bolp) (backward-char)) (point)))
7024 (setq has-children
7025 (or (save-excursion
7026 (let ((level (funcall outline-level)))
7027 (outline-next-heading)
7028 (and (org-at-heading-p t)
7029 (> (funcall outline-level) level))))
7030 (save-excursion
7031 (org-list-search-forward (org-item-beginning-re) eos t)))))
7032 ;; Determine end invisible part of buffer (EOL)
7033 (beginning-of-line 2)
7034 (while (and (not (eobp)) ;This is like `next-line'.
7035 (get-char-property (1- (point)) 'invisible))
7036 (goto-char (next-single-char-property-change (point) 'invisible))
7037 (and (eolp) (beginning-of-line 2)))
7038 (setq eol (point)))
7039 ;; Find out what to do next and set `this-command'
7040 (cond
7041 ((= eos eoh)
7042 ;; Nothing is hidden behind this heading
7043 (unless (org-before-first-heading-p)
7044 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7045 (org-unlogged-message "EMPTY ENTRY")
7046 (setq org-cycle-subtree-status nil)
7047 (save-excursion
7048 (goto-char eos)
7049 (outline-next-heading)
7050 (when (org-invisible-p) (org-flag-heading nil))))
7051 ((and (or (>= eol eos)
7052 (not (string-match "\\S-" (buffer-substring eol eos))))
7053 (or has-children
7054 (not (setq children-skipped
7055 org-cycle-skip-children-state-if-no-children))))
7056 ;; Entire subtree is hidden in one line: children view
7057 (unless (org-before-first-heading-p)
7058 (run-hook-with-args 'org-pre-cycle-hook 'children))
7059 (if (org-at-item-p)
7060 (org-list-set-item-visibility (point-at-bol) struct 'children)
7061 (org-show-entry)
7062 (org-with-limited-levels (org-show-children))
7063 (org-show-set-visibility 'canonical)
7064 ;; Fold every list in subtree to top-level items.
7065 (when (eq org-cycle-include-plain-lists 'integrate)
7066 (save-excursion
7067 (org-back-to-heading)
7068 (while (org-list-search-forward (org-item-beginning-re) eos t)
7069 (beginning-of-line 1)
7070 (let* ((struct (org-list-struct))
7071 (prevs (org-list-prevs-alist struct))
7072 (end (org-list-get-bottom-point struct)))
7073 (dolist (e (org-list-get-all-items (point) struct prevs))
7074 (org-list-set-item-visibility e struct 'folded))
7075 (goto-char (if (< end eos) end eos)))))))
7076 (org-unlogged-message "CHILDREN")
7077 (save-excursion
7078 (goto-char eos)
7079 (outline-next-heading)
7080 (when (org-invisible-p) (org-flag-heading nil)))
7081 (setq org-cycle-subtree-status 'children)
7082 (unless (org-before-first-heading-p)
7083 (run-hook-with-args 'org-cycle-hook 'children)))
7084 ((or children-skipped
7085 (and (eq last-command this-command)
7086 (eq org-cycle-subtree-status 'children)))
7087 ;; We just showed the children, or no children are there,
7088 ;; now show everything.
7089 (unless (org-before-first-heading-p)
7090 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7091 (org-flag-region eoh eos nil 'outline)
7092 (org-unlogged-message
7093 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7094 (setq org-cycle-subtree-status 'subtree)
7095 (unless (org-before-first-heading-p)
7096 (run-hook-with-args 'org-cycle-hook 'subtree)))
7098 ;; Default action: hide the subtree.
7099 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7100 (org-flag-region eoh eos t 'outline)
7101 (org-unlogged-message "FOLDED")
7102 (setq org-cycle-subtree-status 'folded)
7103 (unless (org-before-first-heading-p)
7104 (run-hook-with-args 'org-cycle-hook 'folded))))))
7106 ;;;###autoload
7107 (defun org-global-cycle (&optional arg)
7108 "Cycle the global visibility. For details see `org-cycle'.
7109 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7110 With a numeric prefix, show all headlines up to that level."
7111 (interactive "P")
7112 (let ((org-cycle-include-plain-lists
7113 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7114 (cond
7115 ((integerp arg)
7116 (org-show-all '(headings blocks))
7117 (outline-hide-sublevels arg)
7118 (setq org-cycle-global-status 'contents))
7119 ((equal arg '(4))
7120 (org-set-startup-visibility)
7121 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7123 (org-cycle '(4))))))
7125 (defun org-set-startup-visibility ()
7126 "Set the visibility required by startup options and properties."
7127 (cond
7128 ((eq org-startup-folded t)
7129 (org-overview))
7130 ((eq org-startup-folded 'content)
7131 (org-content))
7132 ((or (eq org-startup-folded 'showeverything)
7133 (eq org-startup-folded nil))
7134 (org-show-all)))
7135 (unless (eq org-startup-folded 'showeverything)
7136 (when org-hide-block-startup (org-hide-block-all))
7137 (org-set-visibility-according-to-property)
7138 (org-cycle-hide-archived-subtrees 'all)
7139 (org-cycle-hide-drawers 'all)
7140 (org-cycle-show-empty-lines t)))
7142 (defun org-set-visibility-according-to-property ()
7143 "Switch subtree visibilities according to :VISIBILITY: property."
7144 (interactive)
7145 (org-with-wide-buffer
7146 (goto-char (point-min))
7147 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7148 (if (not (org-at-property-p)) (outline-next-heading)
7149 (let ((state (match-string 3)))
7150 (save-excursion
7151 (org-back-to-heading t)
7152 (outline-hide-subtree)
7153 (org-reveal)
7154 (cond
7155 ((equal state "folded")
7156 (outline-hide-subtree))
7157 ((equal state "children")
7158 (org-show-hidden-entry)
7159 (org-show-children))
7160 ((equal state "content")
7161 (save-excursion
7162 (save-restriction
7163 (org-narrow-to-subtree)
7164 (org-content))))
7165 ((member state '("all" "showall"))
7166 (outline-show-subtree)))))))))
7168 (defun org-overview ()
7169 "Switch to overview mode, showing only top-level headlines.
7170 This shows all headlines with a level equal or greater than the level
7171 of the first headline in the buffer. This is important, because if the
7172 first headline is not level one, then (hide-sublevels 1) gives confusing
7173 results."
7174 (interactive)
7175 (save-excursion
7176 (let ((level
7177 (save-excursion
7178 (goto-char (point-min))
7179 (when (re-search-forward org-outline-regexp-bol nil t)
7180 (goto-char (match-beginning 0))
7181 (funcall outline-level)))))
7182 (and level (outline-hide-sublevels level)))))
7184 (defun org-content (&optional arg)
7185 "Show all headlines in the buffer, like a table of contents.
7186 With numerical argument N, show content up to level N."
7187 (interactive "P")
7188 (org-overview)
7189 (save-excursion
7190 ;; Visit all headings and show their offspring
7191 (and (integerp arg) (org-overview))
7192 (goto-char (point-max))
7193 (catch 'exit
7194 (while (and (progn (condition-case nil
7195 (outline-previous-visible-heading 1)
7196 (error (goto-char (point-min))))
7198 (looking-at org-outline-regexp))
7199 (if (integerp arg)
7200 (org-show-children (1- arg))
7201 (outline-show-branches))
7202 (when (bobp) (throw 'exit nil))))))
7204 (defun org-optimize-window-after-visibility-change (state)
7205 "Adjust the window after a change in outline visibility.
7206 This function is the default value of the hook `org-cycle-hook'."
7207 (when (get-buffer-window (current-buffer))
7208 (cond
7209 ((eq state 'content) nil)
7210 ((eq state 'all) nil)
7211 ((eq state 'folded) nil)
7212 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7213 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7215 (defun org-clean-visibility-after-subtree-move ()
7216 "Fix visibility issues after moving a subtree."
7217 ;; First, find a reasonable region to look at:
7218 ;; Start two siblings above, end three below
7219 (let* ((beg (save-excursion
7220 (and (org-get-last-sibling)
7221 (org-get-last-sibling))
7222 (point)))
7223 (end (save-excursion
7224 (and (org-get-next-sibling)
7225 (org-get-next-sibling)
7226 (org-get-next-sibling))
7227 (if (org-at-heading-p)
7228 (point-at-eol)
7229 (point))))
7230 (level (looking-at "\\*+"))
7231 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7232 (save-excursion
7233 (save-restriction
7234 (narrow-to-region beg end)
7235 (when re
7236 ;; Properly fold already folded siblings
7237 (goto-char (point-min))
7238 (while (re-search-forward re nil t)
7239 (when (and (not (org-invisible-p))
7240 (org-invisible-p (line-end-position)))
7241 (outline-hide-entry))))
7242 (org-cycle-hide-drawers 'all)
7243 (org-cycle-show-empty-lines 'overview)))))
7245 (defun org-cycle-show-empty-lines (state)
7246 "Show empty lines above all visible headlines.
7247 The region to be covered depends on STATE when called through
7248 `org-cycle-hook'. Lisp program can use t for STATE to get the
7249 entire buffer covered. Note that an empty line is only shown if there
7250 are at least `org-cycle-separator-lines' empty lines before the headline."
7251 (when (/= org-cycle-separator-lines 0)
7252 (save-excursion
7253 (let* ((n (abs org-cycle-separator-lines))
7254 (re (cond
7255 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7256 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7257 (t (let ((ns (number-to-string (- n 2))))
7258 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7259 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7260 beg end)
7261 (cond
7262 ((memq state '(overview contents t))
7263 (setq beg (point-min) end (point-max)))
7264 ((memq state '(children folded))
7265 (setq beg (point)
7266 end (progn (org-end-of-subtree t t)
7267 (line-beginning-position 2)))))
7268 (when beg
7269 (goto-char beg)
7270 (while (re-search-forward re end t)
7271 (unless (get-char-property (match-end 1) 'invisible)
7272 (let ((e (match-end 1))
7273 (b (if (>= org-cycle-separator-lines 0)
7274 (match-beginning 1)
7275 (save-excursion
7276 (goto-char (match-beginning 0))
7277 (skip-chars-backward " \t\n")
7278 (line-end-position)))))
7279 (org-flag-region b e nil 'outline))))))))
7280 ;; Never hide empty lines at the end of the file.
7281 (save-excursion
7282 (goto-char (point-max))
7283 (outline-previous-heading)
7284 (outline-end-of-heading)
7285 (when (and (looking-at "[ \t\n]+")
7286 (= (match-end 0) (point-max)))
7287 (org-flag-region (point) (match-end 0) nil 'outline))))
7289 ;;;; Reveal point location
7291 (defun org-show-context (&optional key)
7292 "Make sure point and context are visible.
7293 Optional argument KEY, when non-nil, is a symbol. See
7294 `org-show-context-detail' for allowed values and how much is to
7295 be shown."
7296 (org-show-set-visibility
7297 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7298 ((cdr (assq key org-show-context-detail)))
7299 (t (cdr (assq 'default org-show-context-detail))))))
7301 (defun org-show-set-visibility (detail)
7302 "Set visibility around point according to DETAIL.
7303 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7304 `tree', `canonical' or t. See `org-show-context-detail' for more
7305 information."
7306 ;; Show current heading and possibly its entry, following headline
7307 ;; or all children.
7308 (if (and (org-at-heading-p) (not (eq detail 'local)))
7309 (org-flag-heading nil)
7310 (org-show-entry)
7311 ;; If point is hidden within a drawer or a block, make sure to
7312 ;; expose it.
7313 (dolist (o (overlays-at (point)))
7314 (when (memq (overlay-get o 'invisible)
7315 '(org-hide-block org-hide-drawer outline))
7316 (delete-overlay o)))
7317 (unless (org-before-first-heading-p)
7318 (org-with-limited-levels
7319 (cl-case detail
7320 ((tree canonical t) (org-show-children))
7321 ((nil minimal ancestors))
7322 (t (save-excursion
7323 (outline-next-heading)
7324 (org-flag-heading nil)))))))
7325 ;; Show all siblings.
7326 (when (eq detail 'lineage) (org-show-siblings))
7327 ;; Show ancestors, possibly with their children.
7328 (when (memq detail '(ancestors lineage tree canonical t))
7329 (save-excursion
7330 (while (org-up-heading-safe)
7331 (org-flag-heading nil)
7332 (when (memq detail '(canonical t)) (org-show-entry))
7333 (when (memq detail '(tree canonical t)) (org-show-children))))))
7335 (defvar org-reveal-start-hook nil
7336 "Hook run before revealing a location.")
7338 (defun org-reveal (&optional siblings)
7339 "Show current entry, hierarchy above it, and the following headline.
7341 This can be used to show a consistent set of context around
7342 locations exposed with `org-show-context'.
7344 With optional argument SIBLINGS, on each level of the hierarchy all
7345 siblings are shown. This repairs the tree structure to what it would
7346 look like when opened with hierarchical calls to `org-cycle'.
7348 With a \\[universal-argument] \\[universal-argument] prefix, \
7349 go to the parent and show the entire tree."
7350 (interactive "P")
7351 (run-hooks 'org-reveal-start-hook)
7352 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7353 ((equal siblings '(16))
7354 (save-excursion
7355 (when (org-up-heading-safe)
7356 (org-show-subtree)
7357 (run-hook-with-args 'org-cycle-hook 'subtree))))
7358 (t (org-show-set-visibility 'lineage))))
7361 ;;; Indirect buffer display of subtrees
7363 (defvar org-indirect-dedicated-frame nil
7364 "This is the frame being used for indirect tree display.")
7365 (defvar org-last-indirect-buffer nil)
7367 (defun org-tree-to-indirect-buffer (&optional arg)
7368 "Create indirect buffer and narrow it to current subtree.
7370 With a numerical prefix ARG, go up to this level and then take that tree.
7371 If ARG is negative, go up that many levels.
7373 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7374 indirect buffer previously made with this command, to avoid proliferation of
7375 indirect buffers. However, when you call the command with a \
7376 `\\[universal-argument]' prefix, or
7377 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7378 so that you can work with several indirect buffers at the same time. If
7379 `org-indirect-buffer-display' is `dedicated-frame', the \
7380 `\\[universal-argument]' prefix also
7381 requests that a new frame be made for the new buffer, so that the dedicated
7382 frame is not changed."
7383 (interactive "P")
7384 (let ((cbuf (current-buffer))
7385 (cwin (selected-window))
7386 (pos (point))
7387 beg end level heading ibuf)
7388 (save-excursion
7389 (org-back-to-heading t)
7390 (when (numberp arg)
7391 (setq level (org-outline-level))
7392 (when (< arg 0) (setq arg (+ level arg)))
7393 (while (> (setq level (org-outline-level)) arg)
7394 (org-up-heading-safe)))
7395 (setq beg (point)
7396 heading (org-get-heading 'no-tags))
7397 (org-end-of-subtree t t)
7398 (when (org-at-heading-p) (backward-char 1))
7399 (setq end (point)))
7400 (when (and (buffer-live-p org-last-indirect-buffer)
7401 (not (eq org-indirect-buffer-display 'new-frame))
7402 (not arg))
7403 (kill-buffer org-last-indirect-buffer))
7404 (setq ibuf (org-get-indirect-buffer cbuf heading)
7405 org-last-indirect-buffer ibuf)
7406 (cond
7407 ((or (eq org-indirect-buffer-display 'new-frame)
7408 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7409 (select-frame (make-frame))
7410 (delete-other-windows)
7411 (pop-to-buffer-same-window ibuf)
7412 (org-set-frame-title heading))
7413 ((eq org-indirect-buffer-display 'dedicated-frame)
7414 (raise-frame
7415 (select-frame (or (and org-indirect-dedicated-frame
7416 (frame-live-p org-indirect-dedicated-frame)
7417 org-indirect-dedicated-frame)
7418 (setq org-indirect-dedicated-frame (make-frame)))))
7419 (delete-other-windows)
7420 (pop-to-buffer-same-window ibuf)
7421 (org-set-frame-title (concat "Indirect: " heading)))
7422 ((eq org-indirect-buffer-display 'current-window)
7423 (pop-to-buffer-same-window ibuf))
7424 ((eq org-indirect-buffer-display 'other-window)
7425 (pop-to-buffer ibuf))
7426 (t (error "Invalid value")))
7427 (narrow-to-region beg end)
7428 (org-show-all '(headings blocks))
7429 (goto-char pos)
7430 (run-hook-with-args 'org-cycle-hook 'all)
7431 (and (window-live-p cwin) (select-window cwin))))
7433 (defun org-get-indirect-buffer (&optional buffer heading)
7434 (setq buffer (or buffer (current-buffer)))
7435 (let ((n 1) (base (buffer-name buffer)) bname)
7436 (while (buffer-live-p
7437 (get-buffer
7438 (setq bname
7439 (concat base "-"
7440 (if heading (concat heading "-" (number-to-string n))
7441 (number-to-string n))))))
7442 (setq n (1+ n)))
7443 (condition-case nil
7444 (make-indirect-buffer buffer bname 'clone)
7445 (error (make-indirect-buffer buffer bname)))))
7447 (defun org-set-frame-title (title)
7448 "Set the title of the current frame to the string TITLE."
7449 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7451 ;;;; Structure editing
7453 ;;; Inserting headlines
7455 (defun org--line-empty-p (n)
7456 "Is the Nth next line empty?
7458 Counts the current line as N = 1 and the previous line as N = 0;
7459 see `beginning-of-line'."
7460 (save-excursion
7461 (and (not (bobp))
7462 (or (beginning-of-line n) t)
7463 (save-match-data
7464 (looking-at "[ \t]*$")))))
7466 (defun org-previous-line-empty-p ()
7467 "Is the previous line a blank line?
7468 When NEXT is non-nil, check the next line instead."
7469 (org--line-empty-p 0))
7471 (defun org-next-line-empty-p ()
7472 "Is the previous line a blank line?
7473 When NEXT is non-nil, check the next line instead."
7474 (org--line-empty-p 2))
7476 (defun org--blank-before-heading-p (&optional parent)
7477 "Non-nil when an empty line should precede a new heading here.
7478 When optional argument PARENT is non-nil, consider parent
7479 headline instead of current one."
7480 (pcase (assq 'heading org-blank-before-new-entry)
7481 (`(heading . auto)
7482 (save-excursion
7483 (org-with-limited-levels
7484 (unless (and (org-before-first-heading-p)
7485 (not (outline-next-heading)))
7486 (org-back-to-heading t)
7487 (when parent (org-up-heading-safe))
7488 (cond ((not (bobp))
7489 (org-previous-line-empty-p))
7490 ((outline-next-heading)
7491 (org-previous-line-empty-p))
7492 ;; Ignore trailing spaces on last buffer line.
7493 ((progn (skip-chars-backward " \t") (bolp))
7494 (org-previous-line-empty-p))
7495 (t nil))))))
7496 (`(heading . ,value) value)
7497 (_ nil)))
7499 (defun org-insert-heading (&optional arg invisible-ok top)
7500 "Insert a new heading or an item with the same depth at point.
7502 If point is at the beginning of a heading, insert a new heading
7503 or a new headline above the current one. When at the beginning
7504 of a regular line of text, turn it into a heading.
7506 If point is in the middle of a line, split it and create a new
7507 headline with the text in the current line after point (see
7508 `org-M-RET-may-split-line' on how to modify this behavior). As
7509 a special case, on a headline, splitting can only happen on the
7510 title itself. E.g., this excludes breaking stars or tags.
7512 With a `\\[universal-argument]' prefix, set \
7513 `org-insert-heading-respect-content' to
7514 a non-nil value for the duration of the command. This forces the
7515 insertion of a heading after the current subtree, independently
7516 on the location of point.
7518 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7519 insert the heading at the end of the tree
7520 above the current heading. For example, if point is within a
7521 2nd-level heading, then it will insert a 2nd-level heading at
7522 the end of the 1st-level parent subtree.
7524 When INVISIBLE-OK is set, stop at invisible headlines when going
7525 back. This is important for non-interactive uses of the
7526 command.
7528 When optional argument TOP is non-nil, insert a level 1 heading,
7529 unconditionally."
7530 (interactive "P")
7531 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7532 (level (org-current-level))
7533 (stars (make-string (if (and level (not top)) level 1) ?*)))
7534 (cond
7535 ((or org-insert-heading-respect-content
7536 (member arg '((4) (16)))
7537 (and (not invisible-ok)
7538 (invisible-p (max (1- (point)) (point-min)))))
7539 ;; Position point at the location of insertion.
7540 (if (not level) ;before first headline
7541 (org-with-limited-levels (outline-next-heading))
7542 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7543 ;; is nil.
7544 (org-with-limited-levels (org-back-to-heading invisible-ok))
7545 (cond ((equal arg '(16))
7546 (org-up-heading-safe)
7547 (org-end-of-subtree t t))
7549 (org-end-of-subtree t t))))
7550 (unless (bolp) (insert "\n")) ;ensure final newline
7551 (unless (and blank? (org-previous-line-empty-p))
7552 (org-N-empty-lines-before-current (if blank? 1 0)))
7553 (insert stars " \n")
7554 (forward-char -1))
7555 ;; At a headline...
7556 ((org-at-heading-p)
7557 (cond ((bolp)
7558 (when blank? (save-excursion (insert "\n")))
7559 (save-excursion (insert stars " \n"))
7560 (unless (and blank? (org-previous-line-empty-p))
7561 (org-N-empty-lines-before-current (if blank? 1 0)))
7562 (end-of-line))
7563 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7564 (org-match-line org-complex-heading-regexp)
7565 (org-pos-in-match-range (point) 4))
7566 ;; Grab the text that should moved to the new headline.
7567 ;; Preserve tags.
7568 (let ((split (delete-and-extract-region (point) (match-end 4))))
7569 (if (looking-at "[ \t]*$") (replace-match "")
7570 (org-set-tags nil t))
7571 (end-of-line)
7572 (when blank? (insert "\n"))
7573 (insert "\n" stars " ")
7574 (when (org-string-nw-p split) (insert split))
7575 (when (eobp) (save-excursion (insert "\n")))))
7577 (end-of-line)
7578 (when blank? (insert "\n"))
7579 (insert "\n" stars " ")
7580 (when (eobp) (save-excursion (insert "\n"))))))
7581 ;; On regular text, turn line into a headline or split, if
7582 ;; appropriate.
7583 ((bolp)
7584 (insert stars " ")
7585 (unless (and blank? (org-previous-line-empty-p))
7586 (org-N-empty-lines-before-current (if blank? 1 0))))
7588 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7589 (end-of-line))
7590 (insert "\n" stars " ")
7591 (unless (and blank? (org-previous-line-empty-p))
7592 (org-N-empty-lines-before-current (if blank? 1 0))))))
7593 (run-hooks 'org-insert-heading-hook))
7595 (defun org-N-empty-lines-before-current (n)
7596 "Make the number of empty lines before current exactly N.
7597 So this will delete or add empty lines."
7598 (let ((column (current-column)))
7599 (beginning-of-line)
7600 (unless (bobp)
7601 (let ((start (save-excursion
7602 (skip-chars-backward " \r\t\n")
7603 (line-end-position))))
7604 (delete-region start (line-end-position 0))))
7605 (insert (make-string n ?\n))
7606 (move-to-column column)))
7608 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7609 "Return the heading of the current entry, without the stars.
7610 When NO-TAGS is non-nil, don't include tags.
7611 When NO-TODO is non-nil, don't include TODO keywords.
7612 When NO-PRIORITY is non-nil, don't include priority cookie.
7613 When NO-COMMENT is non-nil, don't include COMMENT string."
7614 (save-excursion
7615 (org-back-to-heading t)
7616 (let ((case-fold-search nil))
7617 (looking-at org-complex-heading-regexp)
7618 (let ((todo (and (not no-todo) (match-string 2)))
7619 (priority (and (not no-priority) (match-string 3)))
7620 (headline (pcase (match-string 4)
7621 (`nil "")
7622 ((and (guard no-comment) h)
7623 (replace-regexp-in-string
7624 (eval-when-compile
7625 (format "\\`%s[ \t]+" org-comment-string))
7626 "" h))
7627 (h h)))
7628 (tags (and (not no-tags) (match-string 5))))
7629 (mapconcat #'identity
7630 (delq nil (list todo priority headline tags))
7631 " ")))))
7633 (defun org-heading-components ()
7634 "Return the components of the current heading.
7635 This is a list with the following elements:
7636 - the level as an integer
7637 - the reduced level, different if `org-odd-levels-only' is set.
7638 - the TODO keyword, or nil
7639 - the priority character, like ?A, or nil if no priority is given
7640 - the headline text itself, or the tags string if no headline text
7641 - the tags string, or nil."
7642 (save-excursion
7643 (org-back-to-heading t)
7644 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7645 (list (length (match-string 1))
7646 (org-reduced-level (length (match-string 1)))
7647 (match-string-no-properties 2)
7648 (and (match-end 3) (aref (match-string 3) 2))
7649 (match-string-no-properties 4)
7650 (match-string-no-properties 5)))))
7652 (defun org-get-entry ()
7653 "Get the entry text, after heading, entire subtree."
7654 (save-excursion
7655 (org-back-to-heading t)
7656 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7658 (defun org-edit-headline (&optional heading)
7659 "Edit the current headline.
7660 Set it to HEADING when provided."
7661 (interactive)
7662 (org-with-wide-buffer
7663 (org-back-to-heading t)
7664 (let ((case-fold-search nil))
7665 (when (looking-at org-complex-heading-regexp)
7666 (let* ((old (match-string-no-properties 4))
7667 (new (save-match-data
7668 (org-trim (or heading (read-string "Edit: " old))))))
7669 (unless (equal old new)
7670 (if old (replace-match new t t nil 4)
7671 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7672 (insert " " new))
7673 (org-set-tags nil t)
7674 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7676 (defun org-insert-heading-after-current ()
7677 "Insert a new heading with same level as current, after current subtree."
7678 (interactive)
7679 (org-back-to-heading)
7680 (org-insert-heading)
7681 (org-move-subtree-down)
7682 (end-of-line 1))
7684 (defun org-insert-heading-respect-content (&optional invisible-ok)
7685 "Insert heading with `org-insert-heading-respect-content' set to t."
7686 (interactive)
7687 (org-insert-heading '(4) invisible-ok))
7689 (defun org-insert-todo-heading-respect-content (&optional force-state)
7690 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7691 (interactive)
7692 (org-insert-todo-heading force-state '(4)))
7694 (defun org-insert-todo-heading (arg &optional force-heading)
7695 "Insert a new heading with the same level and TODO state as current heading.
7697 If the heading has no TODO state, or if the state is DONE, use
7698 the first state (TODO by default). Also with one prefix arg,
7699 force first state. With two prefix args, force inserting at the
7700 end of the parent subtree.
7702 When called at a plain list item, insert a new item with an
7703 unchecked check box."
7704 (interactive "P")
7705 (when (or force-heading (not (org-insert-item 'checkbox)))
7706 (org-insert-heading (or (and (equal arg '(16)) '(16))
7707 force-heading))
7708 (save-excursion
7709 (org-forward-heading-same-level -1)
7710 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7711 (let* ((new-mark-x
7712 (if (or (equal arg '(4))
7713 (not (match-beginning 2))
7714 (member (match-string 2) org-done-keywords))
7715 (car org-todo-keywords-1)
7716 (match-string 2)))
7717 (new-mark
7719 (run-hook-with-args-until-success
7720 'org-todo-get-default-hook new-mark-x nil)
7721 new-mark-x)))
7722 (beginning-of-line 1)
7723 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7724 (if org-treat-insert-todo-heading-as-state-change
7725 (org-todo new-mark)
7726 (insert new-mark " "))))
7727 (when org-provide-todo-statistics
7728 (org-update-parent-todo-statistics))))
7730 (defun org-insert-subheading (arg)
7731 "Insert a new subheading and demote it.
7732 Works for outline headings and for plain lists alike."
7733 (interactive "P")
7734 (org-insert-heading arg)
7735 (cond
7736 ((org-at-heading-p) (org-do-demote))
7737 ((org-at-item-p) (org-indent-item))))
7739 (defun org-insert-todo-subheading (arg)
7740 "Insert a new subheading with TODO keyword or checkbox and demote it.
7741 Works for outline headings and for plain lists alike."
7742 (interactive "P")
7743 (org-insert-todo-heading arg)
7744 (cond
7745 ((org-at-heading-p) (org-do-demote))
7746 ((org-at-item-p) (org-indent-item))))
7748 ;;; Promotion and Demotion
7750 (defvar org-after-demote-entry-hook nil
7751 "Hook run after an entry has been demoted.
7752 The cursor will be at the beginning of the entry.
7753 When a subtree is being demoted, the hook will be called for each node.")
7755 (defvar org-after-promote-entry-hook nil
7756 "Hook run after an entry has been promoted.
7757 The cursor will be at the beginning of the entry.
7758 When a subtree is being promoted, the hook will be called for each node.")
7760 (defun org-promote-subtree ()
7761 "Promote the entire subtree.
7762 See also `org-promote'."
7763 (interactive)
7764 (save-excursion
7765 (org-with-limited-levels (org-map-tree 'org-promote)))
7766 (org-fix-position-after-promote))
7768 (defun org-demote-subtree ()
7769 "Demote the entire subtree.
7770 See `org-demote' and `org-promote'."
7771 (interactive)
7772 (save-excursion
7773 (org-with-limited-levels (org-map-tree 'org-demote)))
7774 (org-fix-position-after-promote))
7776 (defun org-do-promote ()
7777 "Promote the current heading higher up the tree.
7778 If the region is active in `transient-mark-mode', promote all
7779 headings in the region."
7780 (interactive)
7781 (save-excursion
7782 (if (org-region-active-p)
7783 (org-map-region 'org-promote (region-beginning) (region-end))
7784 (org-promote)))
7785 (org-fix-position-after-promote))
7787 (defun org-do-demote ()
7788 "Demote the current heading lower down the tree.
7789 If the region is active in `transient-mark-mode', demote all
7790 headings in the region."
7791 (interactive)
7792 (save-excursion
7793 (if (org-region-active-p)
7794 (org-map-region 'org-demote (region-beginning) (region-end))
7795 (org-demote)))
7796 (org-fix-position-after-promote))
7798 (defun org-fix-position-after-promote ()
7799 "Fix cursor position and indentation after demoting/promoting."
7800 (let ((pos (point)))
7801 (when (save-excursion
7802 (beginning-of-line)
7803 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7804 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7805 (cond ((eobp) (insert " "))
7806 ((eolp) (insert " "))
7807 ((equal (char-after) ?\s) (forward-char 1))))))
7809 (defun org-current-level ()
7810 "Return the level of the current entry, or nil if before the first headline.
7811 The level is the number of stars at the beginning of the
7812 headline. Use `org-reduced-level' to remove the effect of
7813 `org-odd-levels'. Unlike to `org-outline-level', this function
7814 ignores inlinetasks."
7815 (let ((level (org-with-limited-levels (org-outline-level))))
7816 (and (> level 0) level)))
7818 (defun org-get-previous-line-level ()
7819 "Return the outline depth of the last headline before the current line.
7820 Returns 0 for the first headline in the buffer, and nil if before the
7821 first headline."
7822 (and (org-current-level)
7823 (or (and (/= (line-beginning-position) (point-min))
7824 (save-excursion (beginning-of-line 0) (org-current-level)))
7825 0)))
7827 (defun org-reduced-level (l)
7828 "Compute the effective level of a heading.
7829 This takes into account the setting of `org-odd-levels-only'."
7830 (cond
7831 ((zerop l) 0)
7832 (org-odd-levels-only (1+ (floor (/ l 2))))
7833 (t l)))
7835 (defun org-level-increment ()
7836 "Return the number of stars that will be added or removed at a
7837 time to headlines when structure editing, based on the value of
7838 `org-odd-levels-only'."
7839 (if org-odd-levels-only 2 1))
7841 (defun org-get-valid-level (level &optional change)
7842 "Rectify a level change under the influence of `org-odd-levels-only'.
7843 LEVEL is a current level, CHANGE is by how much the level should
7844 be modified. Even if CHANGE is nil, LEVEL may be returned
7845 modified because even level numbers will become the next higher
7846 odd number. Returns values greater than 0."
7847 (if org-odd-levels-only
7848 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7849 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7850 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7851 (max 1 (+ level (or change 0)))))
7853 (defun org-promote ()
7854 "Promote the current heading higher up the tree."
7855 (org-with-wide-buffer
7856 (org-back-to-heading t)
7857 (let* ((after-change-functions (remq 'flyspell-after-change-function
7858 after-change-functions))
7859 (level (save-match-data (funcall outline-level)))
7860 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7861 (diff (abs (- level (length up-head) -1))))
7862 (cond
7863 ((and (= level 1) org-allow-promoting-top-level-subtree)
7864 (replace-match "# " nil t))
7865 ((= level 1)
7866 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7867 (t (replace-match up-head nil t)))
7868 (unless (= level 1)
7869 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7870 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7871 (run-hooks 'org-after-promote-entry-hook))))
7873 (defun org-demote ()
7874 "Demote the current heading lower down the tree."
7875 (org-with-wide-buffer
7876 (org-back-to-heading t)
7877 (let* ((after-change-functions (remq 'flyspell-after-change-function
7878 after-change-functions))
7879 (level (save-match-data (funcall outline-level)))
7880 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7881 (diff (abs (- level (length down-head) -1))))
7882 (replace-match down-head nil t)
7883 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7884 (when org-adapt-indentation (org-fixup-indentation diff))
7885 (run-hooks 'org-after-demote-entry-hook))))
7887 (defun org-cycle-level ()
7888 "Cycle the level of an empty headline through possible states.
7889 This goes first to child, then to parent, level, then up the hierarchy.
7890 After top level, it switches back to sibling level."
7891 (interactive)
7892 (let ((org-adapt-indentation nil))
7893 (when (org-point-at-end-of-empty-headline)
7894 (setq this-command 'org-cycle-level) ; Only needed for caching
7895 (let ((cur-level (org-current-level))
7896 (prev-level (org-get-previous-line-level)))
7897 (cond
7898 ;; If first headline in file, promote to top-level.
7899 ((= prev-level 0)
7900 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7901 do (org-do-promote)))
7902 ;; If same level as prev, demote one.
7903 ((= prev-level cur-level)
7904 (org-do-demote))
7905 ;; If parent is top-level, promote to top level if not already.
7906 ((= prev-level 1)
7907 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7908 do (org-do-promote)))
7909 ;; If top-level, return to prev-level.
7910 ((= cur-level 1)
7911 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7912 do (org-do-demote)))
7913 ;; If less than prev-level, promote one.
7914 ((< cur-level prev-level)
7915 (org-do-promote))
7916 ;; If deeper than prev-level, promote until higher than
7917 ;; prev-level.
7918 ((> cur-level prev-level)
7919 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7920 do (org-do-promote))))
7921 t))))
7923 (defun org-map-tree (fun)
7924 "Call FUN for every heading underneath the current one."
7925 (org-back-to-heading t)
7926 (let ((level (funcall outline-level)))
7927 (save-excursion
7928 (funcall fun)
7929 (while (and (progn
7930 (outline-next-heading)
7931 (> (funcall outline-level) level))
7932 (not (eobp)))
7933 (funcall fun)))))
7935 (defun org-map-region (fun beg end)
7936 "Call FUN for every heading between BEG and END."
7937 (let ((org-ignore-region t))
7938 (save-excursion
7939 (setq end (copy-marker end))
7940 (goto-char beg)
7941 (when (and (re-search-forward org-outline-regexp-bol nil t)
7942 (< (point) end))
7943 (funcall fun))
7944 (while (and (progn
7945 (outline-next-heading)
7946 (< (point) end))
7947 (not (eobp)))
7948 (funcall fun)))))
7950 (defun org-fixup-indentation (diff)
7951 "Change the indentation in the current entry by DIFF.
7953 DIFF is an integer. Indentation is done according to the
7954 following rules:
7956 - Planning information and property drawers are always indented
7957 according to the new level of the headline;
7959 - Footnote definitions and their contents are ignored;
7961 - Inlinetasks' boundaries are not shifted;
7963 - Empty lines are ignored;
7965 - Other lines' indentation are shifted by DIFF columns, unless
7966 it would introduce a structural change in the document, in
7967 which case no shifting is done at all.
7969 Assume point is at a heading or an inlinetask beginning."
7970 (org-with-wide-buffer
7971 (narrow-to-region (line-beginning-position)
7972 (save-excursion
7973 (if (org-with-limited-levels (org-at-heading-p))
7974 (org-with-limited-levels (outline-next-heading))
7975 (org-inlinetask-goto-end))
7976 (point)))
7977 (forward-line)
7978 ;; Indent properly planning info and property drawer.
7979 (when (looking-at-p org-planning-line-re)
7980 (org-indent-line)
7981 (forward-line))
7982 (when (looking-at org-property-drawer-re)
7983 (goto-char (match-end 0))
7984 (forward-line)
7985 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7986 (catch 'no-shift
7987 (when (zerop diff) (throw 'no-shift nil))
7988 ;; If DIFF is negative, first check if a shift is possible at all
7989 ;; (e.g., it doesn't break structure). This can only happen if
7990 ;; some contents are not properly indented.
7991 (let ((case-fold-search t))
7992 (when (< diff 0)
7993 (let ((diff (- diff))
7994 (forbidden-re (concat org-outline-regexp
7995 "\\|"
7996 (substring org-footnote-definition-re 1))))
7997 (save-excursion
7998 (while (not (eobp))
7999 (cond
8000 ((looking-at-p "[ \t]*$") (forward-line))
8001 ((and (looking-at-p org-footnote-definition-re)
8002 (let ((e (org-element-at-point)))
8003 (and (eq (org-element-type e) 'footnote-definition)
8004 (goto-char (org-element-property :end e))))))
8005 ((looking-at-p org-outline-regexp) (forward-line))
8006 ;; Give up if shifting would move before column 0 or
8007 ;; if it would introduce a headline or a footnote
8008 ;; definition.
8010 (skip-chars-forward " \t")
8011 (let ((ind (current-column)))
8012 (when (or (< ind diff)
8013 (and (= ind diff) (looking-at-p forbidden-re)))
8014 (throw 'no-shift nil)))
8015 ;; Ignore contents of example blocks and source
8016 ;; blocks if their indentation is meant to be
8017 ;; preserved. Jump to block's closing line.
8018 (beginning-of-line)
8019 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8020 (let ((e (org-element-at-point)))
8021 (and (memq (org-element-type e)
8022 '(example-block src-block))
8023 (or org-src-preserve-indentation
8024 (org-element-property :preserve-indent e))
8025 (goto-char (org-element-property :end e))
8026 (progn (skip-chars-backward " \r\t\n")
8027 (beginning-of-line)
8028 t))))
8029 (forward-line))))))))
8030 ;; Shift lines but footnote definitions, inlinetasks boundaries
8031 ;; by DIFF. Also skip contents of source or example blocks
8032 ;; when indentation is meant to be preserved.
8033 (while (not (eobp))
8034 (cond
8035 ((and (looking-at-p org-footnote-definition-re)
8036 (let ((e (org-element-at-point)))
8037 (and (eq (org-element-type e) 'footnote-definition)
8038 (goto-char (org-element-property :end e))))))
8039 ((looking-at-p org-outline-regexp) (forward-line))
8040 ((looking-at-p "[ \t]*$") (forward-line))
8042 (indent-line-to (+ (org-get-indentation) diff))
8043 (beginning-of-line)
8044 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8045 (let ((e (org-element-at-point)))
8046 (and (memq (org-element-type e)
8047 '(example-block src-block))
8048 (or org-src-preserve-indentation
8049 (org-element-property :preserve-indent e))
8050 (goto-char (org-element-property :end e))
8051 (progn (skip-chars-backward " \r\t\n")
8052 (beginning-of-line)
8053 t))))
8054 (forward-line)))))))))
8056 (defun org-convert-to-odd-levels ()
8057 "Convert an Org file with all levels allowed to one with odd levels.
8058 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8059 level 5 etc."
8060 (interactive)
8061 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8062 (let ((outline-level 'org-outline-level)
8063 (org-odd-levels-only nil) n)
8064 (save-excursion
8065 (goto-char (point-min))
8066 (while (re-search-forward "^\\*\\*+ " nil t)
8067 (setq n (- (length (match-string 0)) 2))
8068 (while (>= (setq n (1- n)) 0)
8069 (org-demote))
8070 (end-of-line 1))))))
8072 (defun org-convert-to-oddeven-levels ()
8073 "Convert an Org file with only odd levels to one with odd/even levels.
8074 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8075 file contains a section with an even level, conversion would
8076 destroy the structure of the file. An error is signaled in this
8077 case."
8078 (interactive)
8079 (goto-char (point-min))
8080 ;; First check if there are no even levels
8081 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8082 (org-show-set-visibility 'canonical)
8083 (error "Not all levels are odd in this file. Conversion not possible"))
8084 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8085 (let ((outline-regexp org-outline-regexp)
8086 (outline-level 'org-outline-level)
8087 (org-odd-levels-only nil) n)
8088 (save-excursion
8089 (goto-char (point-min))
8090 (while (re-search-forward "^\\*\\*+ " nil t)
8091 (setq n (/ (1- (length (match-string 0))) 2))
8092 (while (>= (setq n (1- n)) 0)
8093 (org-promote))
8094 (end-of-line 1))))))
8096 (defun org-tr-level (n)
8097 "Make N odd if required."
8098 (if org-odd-levels-only (1+ (/ n 2)) n))
8100 ;;; Vertical tree motion, cutting and pasting of subtrees
8102 (defun org-move-subtree-up (&optional arg)
8103 "Move the current subtree up past ARG headlines of the same level."
8104 (interactive "p")
8105 (org-move-subtree-down (- (prefix-numeric-value arg))))
8107 (defun org-move-subtree-down (&optional arg)
8108 "Move the current subtree down past ARG headlines of the same level."
8109 (interactive "p")
8110 (setq arg (prefix-numeric-value arg))
8111 (org-preserve-local-variables
8112 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8113 'org-get-last-sibling))
8114 (ins-point (make-marker))
8115 (cnt (abs arg))
8116 (col (current-column))
8117 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8118 ;; Select the tree
8119 (org-back-to-heading)
8120 (setq beg0 (point))
8121 (save-excursion
8122 (setq ne-beg (org-back-over-empty-lines))
8123 (setq beg (point)))
8124 (save-match-data
8125 (save-excursion (outline-end-of-heading)
8126 (setq folded (org-invisible-p)))
8127 (progn (org-end-of-subtree nil t)
8128 (unless (eobp) (backward-char))))
8129 (outline-next-heading)
8130 (setq ne-end (org-back-over-empty-lines))
8131 (setq end (point))
8132 (goto-char beg0)
8133 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8134 ;; include less whitespace
8135 (save-excursion
8136 (goto-char beg)
8137 (forward-line (- ne-beg ne-end))
8138 (setq beg (point))))
8139 ;; Find insertion point, with error handling
8140 (while (> cnt 0)
8141 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8142 (goto-char beg0)
8143 (user-error "Cannot move past superior level or buffer limit"))
8144 (setq cnt (1- cnt)))
8145 (when (> arg 0)
8146 ;; Moving forward - still need to move over subtree
8147 (org-end-of-subtree t t)
8148 (save-excursion
8149 (org-back-over-empty-lines)
8150 (or (bolp) (newline))))
8151 (setq ne-ins (org-back-over-empty-lines))
8152 (move-marker ins-point (point))
8153 (setq txt (buffer-substring beg end))
8154 (org-save-markers-in-region beg end)
8155 (delete-region beg end)
8156 (org-remove-empty-overlays-at beg)
8157 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8158 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8159 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8160 (let ((bbb (point)))
8161 (insert-before-markers txt)
8162 (org-reinstall-markers-in-region bbb)
8163 (move-marker ins-point bbb))
8164 (or (bolp) (insert "\n"))
8165 (setq ins-end (point))
8166 (goto-char ins-point)
8167 (org-skip-whitespace)
8168 (when (and (< arg 0)
8169 (org-first-sibling-p)
8170 (> ne-ins ne-beg))
8171 ;; Move whitespace back to beginning
8172 (save-excursion
8173 (goto-char ins-end)
8174 (let ((kill-whole-line t))
8175 (kill-line (- ne-ins ne-beg)) (point)))
8176 (insert (make-string (- ne-ins ne-beg) ?\n)))
8177 (move-marker ins-point nil)
8178 (if folded
8179 (outline-hide-subtree)
8180 (org-show-entry)
8181 (org-show-children))
8182 (org-clean-visibility-after-subtree-move)
8183 ;; move back to the initial column we were at
8184 (move-to-column col))))
8186 (defvar org-subtree-clip ""
8187 "Clipboard for cut and paste of subtrees.
8188 This is actually only a copy of the kill, because we use the normal kill
8189 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8191 (defvar org-subtree-clip-folded nil
8192 "Was the last copied subtree folded?
8193 This is used to fold the tree back after pasting.")
8195 (defun org-cut-subtree (&optional n)
8196 "Cut the current subtree into the clipboard.
8197 With prefix arg N, cut this many sequential subtrees.
8198 This is a short-hand for marking the subtree and then cutting it."
8199 (interactive "p")
8200 (org-copy-subtree n 'cut))
8202 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8203 "Copy the current subtree into the clipboard.
8204 With prefix arg N, copy this many sequential subtrees.
8205 This is a short-hand for marking the subtree and then copying it.
8206 If CUT is non-nil, actually cut the subtree.
8207 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8208 of some markers in the region, even if CUT is non-nil. This is
8209 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8210 (interactive "p")
8211 (org-preserve-local-variables
8212 (let (beg end folded (beg0 (point)))
8213 (if (called-interactively-p 'any)
8214 (org-back-to-heading nil) ; take what looks like a subtree
8215 (org-back-to-heading t)) ; take what is really there
8216 (setq beg (point))
8217 (skip-chars-forward " \t\r\n")
8218 (save-match-data
8219 (if nosubtrees
8220 (outline-next-heading)
8221 (save-excursion (outline-end-of-heading)
8222 (setq folded (org-invisible-p)))
8223 (ignore-errors (org-forward-heading-same-level (1- n) t))
8224 (org-end-of-subtree t t)))
8225 ;; Include the end of an inlinetask
8226 (when (and (featurep 'org-inlinetask)
8227 (looking-at-p (concat (org-inlinetask-outline-regexp)
8228 "END[ \t]*$")))
8229 (end-of-line))
8230 (setq end (point))
8231 (goto-char beg0)
8232 (when (> end beg)
8233 (setq org-subtree-clip-folded folded)
8234 (when (or cut force-store-markers)
8235 (org-save-markers-in-region beg end))
8236 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8237 (setq org-subtree-clip (current-kill 0))
8238 (message "%s: Subtree(s) with %d characters"
8239 (if cut "Cut" "Copied")
8240 (length org-subtree-clip))))))
8242 (defun org-paste-subtree (&optional level tree for-yank remove)
8243 "Paste the clipboard as a subtree, with modification of headline level.
8244 The entire subtree is promoted or demoted in order to match a new headline
8245 level.
8247 If the cursor is at the beginning of a headline, the same level as
8248 that headline is used to paste the tree.
8250 If not, the new level is derived from the *visible* headings
8251 before and after the insertion point, and taken to be the inferior headline
8252 level of the two. So if the previous visible heading is level 3 and the
8253 next is level 4 (or vice versa), level 4 will be used for insertion.
8254 This makes sure that the subtree remains an independent subtree and does
8255 not swallow low level entries.
8257 You can also force a different level, either by using a numeric prefix
8258 argument, or by inserting the heading marker by hand. For example, if the
8259 cursor is after \"*****\", then the tree will be shifted to level 5.
8261 If optional TREE is given, use this text instead of the kill ring.
8263 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8264 move back over whitespace before inserting, and move point to the end of
8265 the inserted text when done.
8267 When REMOVE is non-nil, remove the subtree from the clipboard."
8268 (interactive "P")
8269 (setq tree (or tree (and kill-ring (current-kill 0))))
8270 (unless (org-kill-is-subtree-p tree)
8271 (user-error "%s"
8272 (substitute-command-keys
8273 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8274 (org-with-limited-levels
8275 (let* ((visp (not (org-invisible-p)))
8276 (txt tree)
8277 (^re_ "\\(\\*+\\)[ \t]*")
8278 (old-level (if (string-match org-outline-regexp-bol txt)
8279 (- (match-end 0) (match-beginning 0) 1)
8280 -1))
8281 (force-level (cond (level (prefix-numeric-value level))
8282 ((and (looking-at "[ \t]*$")
8283 (string-match
8284 "^\\*+$" (buffer-substring
8285 (point-at-bol) (point))))
8286 (- (match-end 0) (match-beginning 0)))
8287 ((and (bolp)
8288 (looking-at org-outline-regexp))
8289 (- (match-end 0) (point) 1))))
8290 (previous-level (save-excursion
8291 (condition-case nil
8292 (progn
8293 (outline-previous-visible-heading 1)
8294 (if (looking-at ^re_)
8295 (- (match-end 0) (match-beginning 0) 1)
8297 (error 1))))
8298 (next-level (save-excursion
8299 (condition-case nil
8300 (progn
8301 (or (looking-at org-outline-regexp)
8302 (outline-next-visible-heading 1))
8303 (if (looking-at ^re_)
8304 (- (match-end 0) (match-beginning 0) 1)
8306 (error 1))))
8307 (new-level (or force-level (max previous-level next-level)))
8308 (shift (if (or (= old-level -1)
8309 (= new-level -1)
8310 (= old-level new-level))
8312 (- new-level old-level)))
8313 (delta (if (> shift 0) -1 1))
8314 (func (if (> shift 0) 'org-demote 'org-promote))
8315 (org-odd-levels-only nil)
8316 beg end newend)
8317 ;; Remove the forced level indicator
8318 (when force-level
8319 (delete-region (point-at-bol) (point)))
8320 ;; Paste
8321 (beginning-of-line (if (bolp) 1 2))
8322 (setq beg (point))
8323 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8324 (insert-before-markers txt)
8325 (unless (string-suffix-p "\n" txt) (insert "\n"))
8326 (setq newend (point))
8327 (org-reinstall-markers-in-region beg)
8328 (setq end (point))
8329 (goto-char beg)
8330 (skip-chars-forward " \t\n\r")
8331 (setq beg (point))
8332 (when (and (org-invisible-p) visp)
8333 (save-excursion (outline-show-heading)))
8334 ;; Shift if necessary
8335 (unless (= shift 0)
8336 (save-restriction
8337 (narrow-to-region beg end)
8338 (while (not (= shift 0))
8339 (org-map-region func (point-min) (point-max))
8340 (setq shift (+ delta shift)))
8341 (goto-char (point-min))
8342 (setq newend (point-max))))
8343 (when (or (called-interactively-p 'interactive) for-yank)
8344 (message "Clipboard pasted as level %d subtree" new-level))
8345 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8346 kill-ring
8347 (eq org-subtree-clip (current-kill 0))
8348 org-subtree-clip-folded)
8349 ;; The tree was folded before it was killed/copied
8350 (outline-hide-subtree))
8351 (and for-yank (goto-char newend))
8352 (and remove (setq kill-ring (cdr kill-ring))))))
8354 (defun org-kill-is-subtree-p (&optional txt)
8355 "Check if the current kill is an outline subtree, or a set of trees.
8356 Returns nil if kill does not start with a headline, or if the first
8357 headline level is not the largest headline level in the tree.
8358 So this will actually accept several entries of equal levels as well,
8359 which is OK for `org-paste-subtree'.
8360 If optional TXT is given, check this string instead of the current kill."
8361 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8362 (re (org-get-limited-outline-regexp))
8363 (^re (concat "^" re))
8364 (start-level (and kill
8365 (string-match
8366 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8367 kill)
8368 (- (match-end 2) (match-beginning 2) 1)))
8369 (start (1+ (or (match-beginning 2) -1))))
8370 (if (not start-level)
8371 (progn
8372 nil) ;; does not even start with a heading
8373 (catch 'exit
8374 (while (setq start (string-match ^re kill (1+ start)))
8375 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8376 (throw 'exit nil)))
8377 t))))
8379 (defvar org-markers-to-move nil
8380 "Markers that should be moved with a cut-and-paste operation.
8381 Those markers are stored together with their positions relative to
8382 the start of the region.")
8384 (defun org-save-markers-in-region (beg end)
8385 "Check markers in region.
8386 If these markers are between BEG and END, record their position relative
8387 to BEG, so that after moving the block of text, we can put the markers back
8388 into place.
8389 This function gets called just before an entry or tree gets cut from the
8390 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8391 called immediately, to move the markers with the entries."
8392 (setq org-markers-to-move nil)
8393 (when (featurep 'org-clock)
8394 (org-clock-save-markers-for-cut-and-paste beg end))
8395 (when (featurep 'org-agenda)
8396 (org-agenda-save-markers-for-cut-and-paste beg end)))
8398 (defun org-check-and-save-marker (marker beg end)
8399 "Check if MARKER is between BEG and END.
8400 If yes, remember the marker and the distance to BEG."
8401 (when (and (marker-buffer marker)
8402 (equal (marker-buffer marker) (current-buffer))
8403 (>= marker beg) (< marker end))
8404 (push (cons marker (- marker beg)) org-markers-to-move)))
8406 (defun org-reinstall-markers-in-region (beg)
8407 "Move all remembered markers to their position relative to BEG."
8408 (dolist (x org-markers-to-move)
8409 (move-marker (car x) (+ beg (cdr x))))
8410 (setq org-markers-to-move nil))
8412 (defun org-narrow-to-subtree ()
8413 "Narrow buffer to the current subtree."
8414 (interactive)
8415 (save-excursion
8416 (save-match-data
8417 (org-with-limited-levels
8418 (narrow-to-region
8419 (progn (org-back-to-heading t) (point))
8420 (progn (org-end-of-subtree t t)
8421 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8422 (point)))))))
8424 (defun org-narrow-to-block ()
8425 "Narrow buffer to the current block."
8426 (interactive)
8427 (let* ((case-fold-search t)
8428 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8429 "^[ \t]*#\\+end_.*")))
8430 (if blockp
8431 (narrow-to-region (car blockp) (cdr blockp))
8432 (user-error "Not in a block"))))
8434 (defun org-clone-subtree-with-time-shift (n &optional shift)
8435 "Clone the task (subtree) at point N times.
8436 The clones will be inserted as siblings.
8438 In interactive use, the user will be prompted for the number of
8439 clones to be produced. If the entry has a timestamp, the user
8440 will also be prompted for a time shift, which may be a repeater
8441 as used in time stamps, for example `+3d'. To disable this,
8442 you can call the function with a universal prefix argument.
8444 When a valid repeater is given and the entry contains any time
8445 stamps, the clones will become a sequence in time, with time
8446 stamps in the subtree shifted for each clone produced. If SHIFT
8447 is nil or the empty string, time stamps will be left alone. The
8448 ID property of the original subtree is removed.
8450 In each clone, all the CLOCK entries will be removed. This
8451 prevents Org from considering that the clocked times overlap.
8453 If the original subtree did contain time stamps with a repeater,
8454 the following will happen:
8455 - the repeater will be removed in each clone
8456 - an additional clone will be produced, with the current, unshifted
8457 date(s) in the entry.
8458 - the original entry will be placed *after* all the clones, with
8459 repeater intact.
8460 - the start days in the repeater in the original entry will be shifted
8461 to past the last clone.
8462 In this way you can spell out a number of instances of a repeating task,
8463 and still retain the repeater to cover future instances of the task.
8465 As described above, N+1 clones are produced when the original
8466 subtree has a repeater. Setting N to 0, then, can be used to
8467 remove the repeater from a subtree and create a shifted clone
8468 with the original repeater."
8469 (interactive "nNumber of clones to produce: ")
8470 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8471 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8472 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8473 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8474 (shift
8475 (or shift
8476 (if (and (not (equal current-prefix-arg '(4)))
8477 (save-excursion
8478 (goto-char beg)
8479 (re-search-forward org-ts-regexp-both end-of-tree t)))
8480 (read-from-minibuffer
8481 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8482 ""))) ;No time shift
8483 (doshift
8484 (and (org-string-nw-p shift)
8485 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8486 shift)
8487 (user-error "Invalid shift specification %s" shift)))))
8488 (goto-char end-of-tree)
8489 (unless (bolp) (insert "\n"))
8490 (let* ((end (point))
8491 (template (buffer-substring beg end))
8492 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8493 (shift-what (pcase (and doshift (match-string 2 shift))
8494 (`nil nil)
8495 ("d" 'day)
8496 ("w" (setq shift-n (* 7 shift-n)) 'day)
8497 ("m" 'month)
8498 ("y" 'year)
8499 (_ (error "Unsupported time unit"))))
8500 (nmin 1)
8501 (nmax n)
8502 (n-no-remove -1)
8503 (idprop (org-entry-get nil "ID")))
8504 (when (and doshift
8505 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8506 template))
8507 (delete-region beg end)
8508 (setq end beg)
8509 (setq nmin 0)
8510 (setq nmax (1+ nmax))
8511 (setq n-no-remove nmax))
8512 (goto-char end)
8513 (cl-loop for n from nmin to nmax do
8514 (insert
8515 ;; Prepare clone.
8516 (with-temp-buffer
8517 (insert template)
8518 (org-mode)
8519 (goto-char (point-min))
8520 (org-show-subtree)
8521 (and idprop (if org-clone-delete-id
8522 (org-entry-delete nil "ID")
8523 (org-id-get-create t)))
8524 (unless (= n 0)
8525 (while (re-search-forward org-clock-line-re nil t)
8526 (delete-region (line-beginning-position)
8527 (line-beginning-position 2)))
8528 (goto-char (point-min))
8529 (while (re-search-forward org-drawer-regexp nil t)
8530 (org-remove-empty-drawer-at (point))))
8531 (goto-char (point-min))
8532 (when doshift
8533 (while (re-search-forward org-ts-regexp-both nil t)
8534 (org-timestamp-change (* n shift-n) shift-what))
8535 (unless (= n n-no-remove)
8536 (goto-char (point-min))
8537 (while (re-search-forward org-ts-regexp nil t)
8538 (save-excursion
8539 (goto-char (match-beginning 0))
8540 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8541 (delete-region (match-beginning 1) (match-end 1)))))))
8542 (buffer-string)))))
8543 (goto-char beg)))
8545 ;;; Outline Sorting
8547 (defun org-sort (&optional with-case)
8548 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8549 Optional argument WITH-CASE means sort case-sensitively."
8550 (interactive "P")
8551 (org-call-with-arg
8552 (cond ((org-at-table-p) #'org-table-sort-lines)
8553 ((org-at-item-p) #'org-sort-list)
8554 (t #'org-sort-entries))
8555 with-case))
8557 (defun org-sort-remove-invisible (s)
8558 "Remove invisible part of links and emphasis markers from string S."
8559 (remove-text-properties 0 (length s) org-rm-props s)
8560 (replace-regexp-in-string
8561 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8562 (replace-regexp-in-string
8563 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8564 (org-link-display-format s)
8565 t t) t t))
8567 (defvar org-priority-regexp) ; defined later in the file
8569 (defvar org-after-sorting-entries-or-items-hook nil
8570 "Hook that is run after a bunch of entries or items have been sorted.
8571 When children are sorted, the cursor is in the parent line when this
8572 hook gets called. When a region or a plain list is sorted, the cursor
8573 will be in the first entry of the sorted region/list.")
8575 (defun org-sort-entries
8576 (&optional with-case sorting-type getkey-func compare-func property
8577 interactive?)
8578 "Sort entries on a certain level of an outline tree.
8579 If there is an active region, the entries in the region are sorted.
8580 Else, if the cursor is before the first entry, sort the top-level items.
8581 Else, the children of the entry at point are sorted.
8583 Sorting can be alphabetically, numerically, by date/time as given by
8584 a time stamp, by a property, by priority order, or by a custom function.
8586 The command prompts for the sorting type unless it has been given to the
8587 function through the SORTING-TYPE argument, which needs to be a character,
8588 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8589 the precise meaning of each character:
8591 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8592 c By creation time, which is assumed to be the first inactive time stamp
8593 at the beginning of a line.
8594 d By deadline date/time.
8595 k By clocking time.
8596 n Numerically, by converting the beginning of the entry/item to a number.
8597 o By order of TODO keywords.
8598 p By priority according to the cookie.
8599 r By the value of a property.
8600 s By scheduled date/time.
8601 t By date/time, either the first active time stamp in the entry, or, if
8602 none exist, by the first inactive one.
8604 Capital letters will reverse the sort order.
8606 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8607 called with point at the beginning of the record. It must return a
8608 value that is compatible with COMPARE-FUNC, the function used to
8609 compare entries.
8611 Comparing entries ignores case by default. However, with an optional argument
8612 WITH-CASE, the sorting considers case as well.
8614 Sorting is done against the visible part of the headlines, it ignores hidden
8615 links.
8617 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8619 A non-nil value for INTERACTIVE? is used to signal that this
8620 function is being called interactively."
8621 (interactive (list current-prefix-arg nil nil nil nil t))
8622 (let ((case-func (if with-case 'identity 'downcase))
8623 start beg end stars re re2
8624 txt what tmp)
8625 ;; Find beginning and end of region to sort
8626 (cond
8627 ((org-region-active-p)
8628 ;; we will sort the region
8629 (setq end (region-end)
8630 what "region")
8631 (goto-char (region-beginning))
8632 (unless (org-at-heading-p) (outline-next-heading))
8633 (setq start (point)))
8634 ((or (org-at-heading-p)
8635 (ignore-errors (progn (org-back-to-heading) t)))
8636 ;; we will sort the children of the current headline
8637 (org-back-to-heading)
8638 (setq start (point)
8639 end (progn (org-end-of-subtree t t)
8640 (or (bolp) (insert "\n"))
8641 (when (>= (org-back-over-empty-lines) 1)
8642 (forward-line 1))
8643 (point))
8644 what "children")
8645 (goto-char start)
8646 (outline-show-subtree)
8647 (outline-next-heading))
8649 ;; we will sort the top-level entries in this file
8650 (goto-char (point-min))
8651 (or (org-at-heading-p) (outline-next-heading))
8652 (setq start (point))
8653 (goto-char (point-max))
8654 (beginning-of-line 1)
8655 (when (looking-at ".*?\\S-")
8656 ;; File ends in a non-white line
8657 (end-of-line 1)
8658 (insert "\n"))
8659 (setq end (point-max))
8660 (setq what "top-level")
8661 (goto-char start)
8662 (org-show-all '(headings blocks))))
8664 (setq beg (point))
8665 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8667 (looking-at "\\(\\*+\\)")
8668 (setq stars (match-string 1)
8669 re (concat "^" (regexp-quote stars) " +")
8670 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8671 txt (buffer-substring beg end))
8672 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8673 (when (and (not (equal stars "*")) (string-match re2 txt))
8674 (user-error "Region to sort contains a level above the first entry"))
8676 (unless sorting-type
8677 (message
8678 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8679 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8680 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8681 what)
8682 (setq sorting-type (read-char-exclusive)))
8684 (unless getkey-func
8685 (and (= (downcase sorting-type) ?f)
8686 (setq getkey-func
8687 (or (and interactive?
8688 (org-read-function
8689 "Function for extracting keys: "))
8690 (error "Missing key extractor")))))
8692 (and (= (downcase sorting-type) ?r)
8693 (not property)
8694 (setq property
8695 (completing-read "Property: "
8696 (mapcar #'list (org-buffer-property-keys t))
8697 nil t)))
8699 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8700 (message "Sorting entries...")
8702 (save-restriction
8703 (narrow-to-region start end)
8704 (let ((restore-clock?
8705 ;; The clock marker is lost when using `sort-subr'; mark
8706 ;; the clock with temporary `:org-clock-marker-backup'
8707 ;; text property.
8708 (when (and (eq (org-clock-is-active) (current-buffer))
8709 (<= start (marker-position org-clock-marker))
8710 (>= end (marker-position org-clock-marker)))
8711 (org-with-silent-modifications
8712 (put-text-property (1- org-clock-marker) org-clock-marker
8713 :org-clock-marker-backup t))
8715 (dcst (downcase sorting-type))
8716 (case-fold-search nil)
8717 (now (current-time)))
8718 (org-preserve-local-variables
8719 (sort-subr
8720 (/= dcst sorting-type)
8721 ;; This function moves to the beginning character of the
8722 ;; "record" to be sorted.
8723 (lambda nil
8724 (if (re-search-forward re nil t)
8725 (goto-char (match-beginning 0))
8726 (goto-char (point-max))))
8727 ;; This function moves to the last character of the "record" being
8728 ;; sorted.
8729 (lambda nil
8730 (save-match-data
8731 (condition-case nil
8732 (outline-forward-same-level 1)
8733 (error
8734 (goto-char (point-max))))))
8735 ;; This function returns the value that gets sorted against.
8736 (lambda ()
8737 (cond
8738 ((= dcst ?n)
8739 (if (looking-at org-complex-heading-regexp)
8740 (string-to-number
8741 (org-sort-remove-invisible (match-string 4)))
8742 nil))
8743 ((= dcst ?a)
8744 (if (looking-at org-complex-heading-regexp)
8745 (funcall case-func
8746 (org-sort-remove-invisible (match-string 4)))
8747 nil))
8748 ((= dcst ?k)
8749 (or (get-text-property (point) :org-clock-minutes) 0))
8750 ((= dcst ?t)
8751 (let ((end (save-excursion (outline-next-heading) (point))))
8752 (if (or (re-search-forward org-ts-regexp end t)
8753 (re-search-forward org-ts-regexp-both end t))
8754 (org-time-string-to-seconds (match-string 0))
8755 (float-time now))))
8756 ((= dcst ?c)
8757 (let ((end (save-excursion (outline-next-heading) (point))))
8758 (if (re-search-forward
8759 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8760 end t)
8761 (org-time-string-to-seconds (match-string 0))
8762 (float-time now))))
8763 ((= dcst ?s)
8764 (let ((end (save-excursion (outline-next-heading) (point))))
8765 (if (re-search-forward org-scheduled-time-regexp end t)
8766 (org-time-string-to-seconds (match-string 1))
8767 (float-time now))))
8768 ((= dcst ?d)
8769 (let ((end (save-excursion (outline-next-heading) (point))))
8770 (if (re-search-forward org-deadline-time-regexp end t)
8771 (org-time-string-to-seconds (match-string 1))
8772 (float-time now))))
8773 ((= dcst ?p)
8774 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8775 (string-to-char (match-string 2))
8776 org-default-priority))
8777 ((= dcst ?r)
8778 (or (org-entry-get nil property) ""))
8779 ((= dcst ?o)
8780 (when (looking-at org-complex-heading-regexp)
8781 (let* ((m (match-string 2))
8782 (s (if (member m org-done-keywords) '- '+)))
8783 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8784 ((= dcst ?f)
8785 (if getkey-func
8786 (progn
8787 (setq tmp (funcall getkey-func))
8788 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8789 tmp)
8790 (error "Invalid key function `%s'" getkey-func)))
8791 (t (error "Invalid sorting type `%c'" sorting-type))))
8793 (cond
8794 ((= dcst ?a) 'string<)
8795 ((= dcst ?f)
8796 (or compare-func
8797 (and interactive?
8798 (org-read-function
8799 (concat "Function for comparing keys "
8800 "(empty for default `sort-subr' predicate): ")
8801 'allow-empty))))
8802 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8803 (when restore-clock?
8804 (move-marker org-clock-marker
8805 (1+ (next-single-property-change
8806 start :org-clock-marker-backup)))
8807 (remove-text-properties (1- org-clock-marker) org-clock-marker
8808 '(:org-clock-marker-backup t)))))
8809 (run-hooks 'org-after-sorting-entries-or-items-hook)
8810 (message "Sorting entries...done")))
8812 (defun org-contextualize-keys (alist contexts)
8813 "Return valid elements in ALIST depending on CONTEXTS.
8815 `org-agenda-custom-commands' or `org-capture-templates' are the
8816 values used for ALIST, and `org-agenda-custom-commands-contexts'
8817 or `org-capture-templates-contexts' are the associated contexts
8818 definitions."
8819 (let ((contexts
8820 ;; normalize contexts
8821 (mapcar
8822 (lambda(c) (cond ((listp (cadr c))
8823 (list (car c) (car c) (nth 1 c)))
8824 ((string= "" (cadr c))
8825 (list (car c) (car c) (nth 2 c)))
8826 (t c)))
8827 contexts))
8828 (a alist) r s)
8829 ;; loop over all commands or templates
8830 (dolist (c a)
8831 (let (vrules repl)
8832 (cond
8833 ((not (assoc (car c) contexts))
8834 (push c r))
8835 ((and (assoc (car c) contexts)
8836 (setq vrules (org-contextualize-validate-key
8837 (car c) contexts)))
8838 (mapc (lambda (vr)
8839 (unless (equal (car vr) (cadr vr))
8840 (setq repl vr)))
8841 vrules)
8842 (if (not repl) (push c r)
8843 (push (cadr repl) s)
8844 (push
8845 (cons (car c)
8846 (cdr (or (assoc (cadr repl) alist)
8847 (error "Undefined key `%s' as contextual replacement for `%s'"
8848 (cadr repl) (car c)))))
8849 r))))))
8850 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8851 (delq
8853 (delete-dups
8854 (mapcar (lambda (x)
8855 (let ((tpl (car x)))
8856 (unless (delq
8858 (mapcar (lambda (y)
8859 (equal y tpl))
8861 x)))
8862 (reverse r))))))
8864 (defun org-contextualize-validate-key (key contexts)
8865 "Check CONTEXTS for agenda or capture KEY."
8866 (let (res)
8867 (dolist (r contexts)
8868 (dolist (rr (car (last r)))
8869 (when
8870 (and (equal key (car r))
8871 (if (functionp rr) (funcall rr)
8872 (or (and (eq (car rr) 'in-file)
8873 (buffer-file-name)
8874 (string-match (cdr rr) (buffer-file-name)))
8875 (and (eq (car rr) 'in-mode)
8876 (string-match (cdr rr) (symbol-name major-mode)))
8877 (and (eq (car rr) 'in-buffer)
8878 (string-match (cdr rr) (buffer-name)))
8879 (when (and (eq (car rr) 'not-in-file)
8880 (buffer-file-name))
8881 (not (string-match (cdr rr) (buffer-file-name))))
8882 (when (eq (car rr) 'not-in-mode)
8883 (not (string-match (cdr rr) (symbol-name major-mode))))
8884 (when (eq (car rr) 'not-in-buffer)
8885 (not (string-match (cdr rr) (buffer-name)))))))
8886 (push r res))))
8887 (delete-dups (delq nil res))))
8889 (defun org-context-p (&rest contexts)
8890 "Check if local context is any of CONTEXTS.
8891 Possible values in the list of contexts are `table', `headline', and `item'."
8892 (let ((pos (point)))
8893 (goto-char (point-at-bol))
8894 (prog1 (or (and (memq 'table contexts)
8895 (looking-at "[ \t]*|"))
8896 (and (memq 'headline contexts)
8897 (looking-at org-outline-regexp))
8898 (and (memq 'item contexts)
8899 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8900 (and (memq 'item-body contexts)
8901 (org-in-item-p)))
8902 (goto-char pos))))
8904 ;;;###autoload
8905 (defun org-run-like-in-org-mode (cmd)
8906 "Run a command, pretending that the current buffer is in Org mode.
8907 This will temporarily bind local variables that are typically bound in
8908 Org mode to the values they have in Org mode, and then interactively
8909 call CMD."
8910 (org-load-modules-maybe)
8911 (let (binds)
8912 (dolist (var (org-get-local-variables))
8913 (when (or (not (boundp (car var)))
8914 (eq (symbol-value (car var))
8915 (default-value (car var))))
8916 (push (list (car var) `(quote ,(cadr var))) binds)))
8917 (eval `(let ,binds
8918 (call-interactively (quote ,cmd))))))
8920 (defun org-get-category (&optional pos force-refresh)
8921 "Get the category applying to position POS."
8922 (save-match-data
8923 (when force-refresh (org-refresh-category-properties))
8924 (let ((pos (or pos (point))))
8925 (or (get-text-property pos 'org-category)
8926 (progn (org-refresh-category-properties)
8927 (get-text-property pos 'org-category))))))
8929 ;;; Refresh properties
8931 (defun org-refresh-properties (dprop tprop)
8932 "Refresh buffer text properties.
8933 DPROP is the drawer property and TPROP is either the
8934 corresponding text property to set, or an alist with each element
8935 being a text property (as a symbol) and a function to apply to
8936 the value of the drawer property."
8937 (let* ((case-fold-search t)
8938 (inhibit-read-only t)
8939 (inherit? (org-property-inherit-p dprop))
8940 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8941 (global (and inherit? (org--property-global-value dprop nil))))
8942 (org-with-silent-modifications
8943 (org-with-point-at 1
8944 ;; Set global values (e.g., values defined through
8945 ;; "#+PROPERTY:" keywords) to the whole buffer.
8946 (when global (put-text-property (point-min) (point-max) tprop global))
8947 ;; Set local values.
8948 (while (re-search-forward property-re nil t)
8949 (when (org-at-property-p)
8950 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8951 (outline-next-heading))))))
8953 (defun org-refresh-property (tprop p &optional inherit)
8954 "Refresh the buffer text property TPROP from the drawer property P.
8955 The refresh happens only for the current headline, or the whole
8956 sub-tree if optional argument INHERIT is non-nil."
8957 (unless (org-before-first-heading-p)
8958 (save-excursion
8959 (org-back-to-heading t)
8960 (let ((start (point))
8961 (end (save-excursion
8962 (if inherit (org-end-of-subtree t t)
8963 (or (outline-next-heading) (point-max))))))
8964 (if (symbolp tprop)
8965 ;; TPROP is a text property symbol.
8966 (put-text-property start end tprop p)
8967 ;; TPROP is an alist with (property . function) elements.
8968 (pcase-dolist (`(,prop . ,f) tprop)
8969 (put-text-property start end prop (funcall f p))))))))
8971 (defun org-refresh-category-properties ()
8972 "Refresh category text properties in the buffer."
8973 (let ((case-fold-search t)
8974 (inhibit-read-only t)
8975 (default-category
8976 (cond ((null org-category)
8977 (if buffer-file-name
8978 (file-name-sans-extension
8979 (file-name-nondirectory buffer-file-name))
8980 "???"))
8981 ((symbolp org-category) (symbol-name org-category))
8982 (t org-category))))
8983 (org-with-silent-modifications
8984 (org-with-wide-buffer
8985 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8986 ;; This is the default category for the buffer. If none is
8987 ;; found, fall-back to `org-category' or buffer file name.
8988 (put-text-property
8989 (point-min) (point-max)
8990 'org-category
8991 (catch 'buffer-category
8992 (goto-char (point-max))
8993 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8994 (let ((element (org-element-at-point)))
8995 (when (eq (org-element-type element) 'keyword)
8996 (throw 'buffer-category
8997 (org-element-property :value element)))))
8998 default-category))
8999 ;; Set sub-tree specific categories.
9000 (goto-char (point-min))
9001 (let ((regexp (org-re-property "CATEGORY")))
9002 (while (re-search-forward regexp nil t)
9003 (let ((value (match-string-no-properties 3)))
9004 (when (org-at-property-p)
9005 (put-text-property
9006 (save-excursion (org-back-to-heading t) (point))
9007 (save-excursion (org-end-of-subtree t t) (point))
9008 'org-category
9009 value)))))))))
9011 (defun org-refresh-stats-properties ()
9012 "Refresh stats text properties in the buffer."
9013 (org-with-silent-modifications
9014 (org-with-point-at 1
9015 (let ((regexp (concat org-outline-regexp-bol
9016 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9017 (while (re-search-forward regexp nil t)
9018 (let* ((numerator (string-to-number (match-string 1)))
9019 (denominator (and (match-end 2)
9020 (string-to-number (match-string 2))))
9021 (stats (cond ((not denominator) numerator) ;percent
9022 ((= denominator 0) 0)
9023 (t (/ (* numerator 100) denominator)))))
9024 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9025 'org-stats stats)))))))
9027 (defun org-refresh-effort-properties ()
9028 "Refresh effort properties"
9029 (org-refresh-properties
9030 org-effort-property
9031 '((effort . identity)
9032 (effort-minutes . org-duration-to-minutes))))
9034 ;;;; Link Stuff
9036 ;;; Link abbreviations
9038 (defun org-link-expand-abbrev (link)
9039 "Apply replacements as defined in `org-link-abbrev-alist'."
9040 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9041 (let* ((key (match-string 1 link))
9042 (as (or (assoc key org-link-abbrev-alist-local)
9043 (assoc key org-link-abbrev-alist)))
9044 (tag (and (match-end 2) (match-string 3 link)))
9045 rpl)
9046 (if (not as)
9047 link
9048 (setq rpl (cdr as))
9049 (cond
9050 ((symbolp rpl) (funcall rpl tag))
9051 ((string-match "%(\\([^)]+\\))" rpl)
9052 (replace-match
9053 (save-match-data
9054 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9055 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9056 ((string-match "%h" rpl)
9057 (replace-match (url-hexify-string (or tag "")) t t rpl))
9058 (t (concat rpl tag)))))
9059 link))
9061 ;;; Storing and inserting links
9063 (defvar org-insert-link-history nil
9064 "Minibuffer history for links inserted with `org-insert-link'.")
9066 (defvar org-stored-links nil
9067 "Contains the links stored with `org-store-link'.")
9069 (defvar org-store-link-plist nil
9070 "Plist with info about the most recently link created with `org-store-link'.")
9072 (defun org-store-link-functions ()
9073 "Return a list of functions that are called to create and store a link.
9074 The functions defined in the :store property of
9075 `org-link-parameters'.
9077 Each function will be called in turn until one returns a non-nil
9078 value. Each function should check if it is responsible for
9079 creating this link (for example by looking at the major mode).
9080 If not, it must exit and return nil. If yes, it should return
9081 a non-nil value after calling `org-store-link-props' with a list
9082 of properties and values. Special properties are:
9084 :type The link prefix, like \"http\". This must be given.
9085 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9086 This is obligatory as well.
9087 :description Optional default description for the second pair
9088 of brackets in an Org mode link. The user can still change
9089 this when inserting this link into an Org mode buffer.
9091 In addition to these, any additional properties can be specified
9092 and then used in capture templates."
9093 (cl-loop for link in org-link-parameters
9094 with store-func
9095 do (setq store-func (org-link-get-parameter (car link) :store))
9096 if store-func
9097 collect store-func))
9099 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9100 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9102 ;;;###autoload
9103 (defun org-store-link (arg &optional interactive?)
9104 "Store an org-link to the current location.
9105 \\<org-mode-map>
9106 This link is added to `org-stored-links' and can later be inserted
9107 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9109 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9110 A single
9111 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9112 `org-gnus-prefer-web-links' for links to Usenet articles.
9114 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9115 skipping storing functions that are not
9116 part of Org core.
9118 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9119 prefix ARG forces storing a link for each line in the
9120 active region.
9122 Assume the function is called interactively if INTERACTIVE? is
9123 non-nil."
9124 (interactive "P\np")
9125 (org-load-modules-maybe)
9126 (if (and (equal arg '(64)) (org-region-active-p))
9127 (save-excursion
9128 (let ((end (region-end)))
9129 (goto-char (region-beginning))
9130 (set-mark (point))
9131 (while (< (point-at-eol) end)
9132 (move-end-of-line 1) (activate-mark)
9133 (let (current-prefix-arg)
9134 (call-interactively 'org-store-link))
9135 (move-beginning-of-line 2)
9136 (set-mark (point)))))
9137 (setq org-store-link-plist nil)
9138 (let (link cpltxt desc description search txt custom-id agenda-link)
9139 (cond
9140 ;; Store a link using an external link type, if any function is
9141 ;; available. If more than one can generate a link from current
9142 ;; location, ask which one to use.
9143 ((and (not (equal arg '(16)))
9144 (let ((results-alist nil))
9145 (dolist (f (org-store-link-functions))
9146 (when (funcall f)
9147 ;; XXX: return value is not link's plist, so we
9148 ;; store the new value before it is modified. It
9149 ;; would be cleaner to ask store link functions to
9150 ;; return the plist instead.
9151 (push (cons f (copy-sequence org-store-link-plist))
9152 results-alist)))
9153 (pcase results-alist
9154 (`nil nil)
9155 (`((,_ . ,_)) t) ;single choice: nothing to do
9156 (`((,name . ,_) . ,_)
9157 ;; Reinstate link plist associated to the chosen
9158 ;; function.
9159 (apply #'org-store-link-props
9160 (cdr (assoc-string
9161 (completing-read
9162 "Which function for creating the link? "
9163 (mapcar #'car results-alist)
9164 nil t (symbol-name name))
9165 results-alist)))
9166 t))))
9167 (setq link (plist-get org-store-link-plist :link))
9168 (setq desc (or (plist-get org-store-link-plist :description)
9169 link)))
9171 ;; Store a link from a source code buffer.
9172 ((org-src-edit-buffer-p)
9173 (let ((coderef-format (org-src-coderef-format)))
9174 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9175 (setq link (format "(%s)" (match-string-no-properties 3))))
9176 (interactive?
9177 (let ((label (read-string "Code line label: ")))
9178 (end-of-line)
9179 (setq link (format coderef-format label))
9180 (let ((gc (- 79 (length link))))
9181 (if (< (current-column) gc)
9182 (org-move-to-column gc t)
9183 (insert " ")))
9184 (insert link)
9185 (setq link (concat "(" label ")"))
9186 (setq desc nil)))
9187 (t (setq link nil)))))
9189 ;; We are in the agenda, link to referenced location
9190 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9191 (let ((m (or (get-text-property (point) 'org-hd-marker)
9192 (get-text-property (point) 'org-marker))))
9193 (when m
9194 (org-with-point-at m
9195 (setq agenda-link (org-store-link nil interactive?))))))
9197 ((eq major-mode 'calendar-mode)
9198 (let ((cd (calendar-cursor-to-date)))
9199 (setq link
9200 (format-time-string
9201 (car org-time-stamp-formats)
9202 (apply 'encode-time
9203 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9204 nil nil nil))))
9205 (org-store-link-props :type "calendar" :date cd)))
9207 ((eq major-mode 'help-mode)
9208 (setq link (concat "help:" (save-excursion
9209 (goto-char (point-min))
9210 (looking-at "^[^ ]+")
9211 (match-string 0))))
9212 (org-store-link-props :type "help"))
9214 ((eq major-mode 'w3-mode)
9215 (setq cpltxt (if (and (buffer-name)
9216 (not (string-match "Untitled" (buffer-name))))
9217 (buffer-name)
9218 (url-view-url t))
9219 link (url-view-url t))
9220 (org-store-link-props :type "w3" :url (url-view-url t)))
9222 ((eq major-mode 'image-mode)
9223 (setq cpltxt (concat "file:"
9224 (abbreviate-file-name buffer-file-name))
9225 link cpltxt)
9226 (org-store-link-props :type "image" :file buffer-file-name))
9228 ;; In dired, store a link to the file of the current line
9229 ((derived-mode-p 'dired-mode)
9230 (let ((file (dired-get-filename nil t)))
9231 (setq file (if file
9232 (abbreviate-file-name
9233 (expand-file-name (dired-get-filename nil t)))
9234 ;; otherwise, no file so use current directory.
9235 default-directory))
9236 (setq cpltxt (concat "file:" file)
9237 link cpltxt)))
9239 ((setq search (run-hook-with-args-until-success
9240 'org-create-file-search-functions))
9241 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9242 "::" search))
9243 (setq cpltxt (or description link)))
9245 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9246 (org-with-limited-levels
9247 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9248 (cond
9249 ;; Store a link using the target at point
9250 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9251 (setq cpltxt
9252 (concat "file:"
9253 (abbreviate-file-name
9254 (buffer-file-name (buffer-base-buffer)))
9255 "::" (match-string 1))
9256 link cpltxt))
9257 ((and (featurep 'org-id)
9258 (or (eq org-id-link-to-org-use-id t)
9259 (and interactive?
9260 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9261 (and (eq org-id-link-to-org-use-id
9262 'create-if-interactive-and-no-custom-id)
9263 (not custom-id))))
9264 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9265 ;; Store a link using the ID at point
9266 (setq link (condition-case nil
9267 (prog1 (org-id-store-link)
9268 (setq desc (or (plist-get org-store-link-plist
9269 :description)
9270 "")))
9271 (error
9272 ;; Probably before first headline, link only to file
9273 (concat "file:"
9274 (abbreviate-file-name
9275 (buffer-file-name (buffer-base-buffer))))))))
9277 ;; Just link to current headline
9278 (setq cpltxt (concat "file:"
9279 (abbreviate-file-name
9280 (buffer-file-name (buffer-base-buffer)))))
9281 ;; Add a context search string
9282 (when (org-xor org-context-in-file-links
9283 (equal arg '(4)))
9284 (let* ((element (org-element-at-point))
9285 (name (org-element-property :name element)))
9286 (setq txt (cond
9287 ((org-at-heading-p) nil)
9288 (name)
9289 ((org-region-active-p)
9290 (buffer-substring (region-beginning) (region-end)))))
9291 (when (or (null txt) (string-match "\\S-" txt))
9292 (setq cpltxt
9293 (concat cpltxt "::"
9294 (condition-case nil
9295 (org-make-org-heading-search-string txt)
9296 (error "")))
9297 desc (or name
9298 (nth 4 (ignore-errors (org-heading-components)))
9299 "NONE")))))
9300 (when (string-match "::\\'" cpltxt)
9301 (setq cpltxt (substring cpltxt 0 -2)))
9302 (setq link cpltxt)))))
9304 ((buffer-file-name (buffer-base-buffer))
9305 ;; Just link to this file here.
9306 (setq cpltxt (concat "file:"
9307 (abbreviate-file-name
9308 (buffer-file-name (buffer-base-buffer)))))
9309 ;; Add a context string.
9310 (when (org-xor org-context-in-file-links
9311 (equal arg '(4)))
9312 (setq txt (if (org-region-active-p)
9313 (buffer-substring (region-beginning) (region-end))
9314 (buffer-substring (point-at-bol) (point-at-eol))))
9315 ;; Only use search option if there is some text.
9316 (when (string-match "\\S-" txt)
9317 (setq cpltxt
9318 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9319 desc "NONE")))
9320 (setq link cpltxt))
9322 (interactive?
9323 (user-error "No method for storing a link from this buffer"))
9325 (t (setq link nil)))
9327 ;; We're done setting link and desc, clean up
9328 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9329 (setq link (or link cpltxt)
9330 desc (or desc cpltxt))
9331 (cond ((not desc))
9332 ((equal desc "NONE") (setq desc nil))
9333 (t (setq desc
9334 (replace-regexp-in-string
9335 org-bracket-link-analytic-regexp
9336 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9337 desc))))
9338 ;; Return the link
9339 (if (not (and interactive? link))
9340 (or agenda-link (and link (org-make-link-string link desc)))
9341 (push (list link desc) org-stored-links)
9342 (message "Stored: %s" (or desc link))
9343 (when custom-id
9344 (setq link (concat "file:" (abbreviate-file-name
9345 (buffer-file-name)) "::#" custom-id))
9346 (push (list link desc) org-stored-links))
9347 (car org-stored-links)))))
9349 (defun org-store-link-props (&rest plist)
9350 "Store link properties.
9351 The properties are pre-processed by extracting names, addresses
9352 and dates."
9353 (let ((x (plist-get plist :from)))
9354 (when x
9355 (let ((adr (mail-extract-address-components x)))
9356 (setq plist (plist-put plist :fromname (car adr)))
9357 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9358 (let ((x (plist-get plist :to)))
9359 (when x
9360 (let ((adr (mail-extract-address-components x)))
9361 (setq plist (plist-put plist :toname (car adr)))
9362 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9363 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9364 (when x
9365 (setq plist (plist-put plist :date-timestamp
9366 (format-time-string
9367 (org-time-stamp-format t) x)))
9368 (setq plist (plist-put plist :date-timestamp-inactive
9369 (format-time-string
9370 (org-time-stamp-format t t) x)))))
9371 (let ((from (plist-get plist :from))
9372 (to (plist-get plist :to)))
9373 (when (and from to org-from-is-user-regexp)
9374 (setq plist
9375 (plist-put plist :fromto
9376 (if (string-match org-from-is-user-regexp from)
9377 (concat "to %t")
9378 (concat "from %f"))))))
9379 (setq org-store-link-plist plist))
9381 (defun org-add-link-props (&rest plist)
9382 "Add these properties to the link property list."
9383 (let (key value)
9384 (while plist
9385 (setq key (pop plist) value (pop plist))
9386 (setq org-store-link-plist
9387 (plist-put org-store-link-plist key value)))))
9389 (defun org-email-link-description (&optional fmt)
9390 "Return the description part of an email link.
9391 This takes information from `org-store-link-plist' and formats it
9392 according to FMT (default from `org-email-link-description-format')."
9393 (setq fmt (or fmt org-email-link-description-format))
9394 (let* ((p org-store-link-plist)
9395 (to (plist-get p :toaddress))
9396 (from (plist-get p :fromaddress))
9397 (table
9398 (list
9399 (cons "%c" (plist-get p :fromto))
9400 (cons "%F" (plist-get p :from))
9401 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9402 (cons "%T" (plist-get p :to))
9403 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9404 (cons "%s" (plist-get p :subject))
9405 (cons "%d" (plist-get p :date))
9406 (cons "%m" (plist-get p :message-id)))))
9407 (when (string-match "%c" fmt)
9408 ;; Check if the user wrote this message
9409 (if (and org-from-is-user-regexp from to
9410 (save-match-data (string-match org-from-is-user-regexp from)))
9411 (setq fmt (replace-match "to %t" t t fmt))
9412 (setq fmt (replace-match "from %f" t t fmt))))
9413 (org-replace-escapes fmt table)))
9415 (defun org-make-org-heading-search-string (&optional string)
9416 "Make search string for the current headline or STRING."
9417 (let ((s (or string
9418 (and (derived-mode-p 'org-mode)
9419 (save-excursion
9420 (org-back-to-heading t)
9421 (org-element-property :raw-value (org-element-at-point))))))
9422 (lines org-context-in-file-links))
9423 (unless string (setq s (concat "*" s))) ;Add * for headlines
9424 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9425 (when (and string (integerp lines) (> lines 0))
9426 (let ((slines (org-split-string s "\n")))
9427 (when (< lines (length slines))
9428 (setq s (mapconcat
9429 'identity
9430 (reverse (nthcdr (- (length slines) lines)
9431 (reverse slines))) "\n")))))
9432 (mapconcat #'identity (split-string s) " ")))
9434 (defconst org-link-escape-chars
9435 ;;%20 %5B %5D %25
9436 '(?\s ?\[ ?\] ?%)
9437 "List of characters that should be escaped in a link when stored to Org.
9438 This is the list that is used for internal purposes.")
9440 (defun org-make-link-string (link &optional description)
9441 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9442 (unless (org-string-nw-p link) (error "Empty link"))
9443 (let ((uri (cond ((string-match org-link-types-re link)
9444 (concat (match-string 1 link)
9445 (org-link-escape (substring link (match-end 1)))))
9446 ((or (file-name-absolute-p link)
9447 (string-match-p "\\`\\.\\.?/" link))
9448 (org-link-escape link))
9449 ;; For readability, do not encode space characters
9450 ;; in fuzzy links.
9451 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9452 (description
9453 (and (org-string-nw-p description)
9454 ;; Remove brackets from description, as they are fatal.
9455 (replace-regexp-in-string
9456 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9457 (org-trim description)))))
9458 (format "[[%s]%s]"
9460 (if description (format "[%s]" description) ""))))
9462 (defun org-link-escape (text &optional table merge)
9463 "Return percent escaped representation of TEXT.
9464 TEXT is a string with the text to escape.
9465 Optional argument TABLE is a list with characters that should be
9466 escaped. When nil, `org-link-escape-chars' is used.
9467 If optional argument MERGE is set, merge TABLE into
9468 `org-link-escape-chars'."
9469 (let ((characters-to-encode
9470 (cond ((null table) org-link-escape-chars)
9471 (merge (append org-link-escape-chars table))
9472 (t table))))
9473 (mapconcat
9474 (lambda (c)
9475 (if (or (memq c characters-to-encode)
9476 (and org-url-hexify-p (or (< c 32) (> c 126))))
9477 (mapconcat (lambda (e) (format "%%%.2X" e))
9478 (or (encode-coding-char c 'utf-8)
9479 (error "Unable to percent escape character: %c" c))
9481 (char-to-string c)))
9482 text "")))
9484 (defun org-link-unescape (str)
9485 "Unhex hexified Unicode parts in string STR.
9486 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9487 reciprocal of `org-link-escape', which see."
9488 (if (org-string-nw-p str)
9489 (replace-regexp-in-string
9490 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9491 str))
9493 (defun org-link-unescape-compound (hex)
9494 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9495 Note: this function also decodes single byte encodings like
9496 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9497 (save-match-data
9498 (let* ((bytes (cdr (split-string hex "%")))
9499 (ret "")
9500 (eat 0)
9501 (sum 0))
9502 (while bytes
9503 (let* ((val (string-to-number (pop bytes) 16))
9504 (shift-xor
9505 (if (= 0 eat)
9506 (cond
9507 ((>= val 252) (cons 6 252))
9508 ((>= val 248) (cons 5 248))
9509 ((>= val 240) (cons 4 240))
9510 ((>= val 224) (cons 3 224))
9511 ((>= val 192) (cons 2 192))
9512 (t (cons 0 0)))
9513 (cons 6 128))))
9514 (when (>= val 192) (setq eat (car shift-xor)))
9515 (setq val (logxor val (cdr shift-xor)))
9516 (setq sum (+ (lsh sum (car shift-xor)) val))
9517 (when (> eat 0) (setq eat (- eat 1)))
9518 (cond
9519 ((= 0 eat) ;multi byte
9520 (setq ret (concat ret (char-to-string sum)))
9521 (setq sum 0))
9522 ((not bytes) ; single byte(s)
9523 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9524 ret)))
9526 (defun org-link-unescape-single-byte-sequence (hex)
9527 "Unhexify hex-encoded single byte character sequences."
9528 (mapconcat (lambda (byte)
9529 (char-to-string (string-to-number byte 16)))
9530 (cdr (split-string hex "%")) ""))
9532 (defun org-fixup-message-id-for-http (s)
9533 "Replace special characters in a message id, so it can be used in an http query."
9534 (when (string-match "%" s)
9535 (setq s (mapconcat (lambda (c)
9536 (if (eq c ?%)
9537 "%25"
9538 (char-to-string c)))
9539 s "")))
9540 (while (string-match "<" s)
9541 (setq s (replace-match "%3C" t t s)))
9542 (while (string-match ">" s)
9543 (setq s (replace-match "%3E" t t s)))
9544 (while (string-match "@" s)
9545 (setq s (replace-match "%40" t t s)))
9548 (defun org-link-prettify (link)
9549 "Return a human-readable representation of LINK.
9550 The car of LINK must be a raw link.
9551 The cdr of LINK must be either a link description or nil."
9552 (let ((desc (or (cadr link) "<no description>")))
9553 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9554 "<" (car link) ">")))
9556 ;;;###autoload
9557 (defun org-insert-link-global ()
9558 "Insert a link like Org mode does.
9559 This command can be called in any mode to insert a link in Org syntax."
9560 (interactive)
9561 (org-load-modules-maybe)
9562 (org-run-like-in-org-mode 'org-insert-link))
9564 (defun org-insert-all-links (arg &optional pre post)
9565 "Insert all links in `org-stored-links'.
9566 When a universal prefix, do not delete the links from `org-stored-links'.
9567 When `ARG' is a number, insert the last N link(s).
9568 `PRE' and `POST' are optional arguments to define a string to
9569 prepend or to append."
9570 (interactive "P")
9571 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9572 (links (copy-sequence org-stored-links))
9573 (pr (or pre "- "))
9574 (po (or post "\n"))
9575 (cnt 1) l)
9576 (if (null org-stored-links)
9577 (message "No link to insert")
9578 (while (and (or (listp arg) (>= arg cnt))
9579 (setq l (if (listp arg)
9580 (pop links)
9581 (pop org-stored-links))))
9582 (setq cnt (1+ cnt))
9583 (insert pr)
9584 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9585 (insert po)))))
9587 (defun org-insert-last-stored-link (arg)
9588 "Insert the last link stored in `org-stored-links'."
9589 (interactive "p")
9590 (org-insert-all-links arg "" "\n"))
9592 (defun org-link-fontify-links-to-this-file ()
9593 "Fontify links to the current file in `org-stored-links'."
9594 (let ((f (buffer-file-name)) a b)
9595 (setq a (mapcar (lambda(l)
9596 (let ((ll (car l)))
9597 (when (and (string-match "^file:\\(.+\\)::" ll)
9598 (equal f (expand-file-name (match-string 1 ll))))
9599 ll)))
9600 org-stored-links))
9601 (when (featurep 'org-id)
9602 (setq b (mapcar (lambda(l)
9603 (let ((ll (car l)))
9604 (when (and (string-match "^id:\\(.+\\)$" ll)
9605 (equal f (expand-file-name
9606 (or (org-id-find-id-file
9607 (match-string 1 ll)) ""))))
9608 ll)))
9609 org-stored-links)))
9610 (mapcar (lambda(l)
9611 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9612 (delq nil (append a b)))))
9614 (defvar org--links-history nil)
9615 (defun org-insert-link (&optional complete-file link-location default-description)
9616 "Insert a link. At the prompt, enter the link.
9618 Completion can be used to insert any of the link protocol prefixes in use.
9620 The history can be used to select a link previously stored with
9621 `org-store-link'. When the empty string is entered (i.e. if you just
9622 press `RET' at the prompt), the link defaults to the most recently
9623 stored link. As `SPC' triggers completion in the minibuffer, you need to
9624 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9626 You will also be prompted for a description, and if one is given, it will
9627 be displayed in the buffer instead of the link.
9629 If there is already a link at point, this command will allow you to edit
9630 link and description parts.
9632 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9633 file name can be
9634 selected using completion. The path to the file will be relative to the
9635 current directory if the file is in the current directory or a subdirectory.
9636 Otherwise, the link will be the absolute path as completed in the minibuffer
9637 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9638 option `org-link-file-path-type'.
9640 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9641 absolute path even if the file is in
9642 the current directory or below.
9644 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9645 prefix negates `org-keep-stored-link-after-insertion'.
9647 If the LINK-LOCATION parameter is non-nil, this value will be used as
9648 the link location instead of reading one interactively.
9650 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9651 be used as the default description. Otherwise, if
9652 `org-make-link-description-function' is non-nil, this function
9653 will be called with the link target, and the result will be the
9654 default link description. When called non-interactivily, don't
9655 allow to edit the default description."
9656 (interactive "P")
9657 (let* ((wcf (current-window-configuration))
9658 (origbuf (current-buffer))
9659 (region (when (org-region-active-p)
9660 (buffer-substring (region-beginning) (region-end))))
9661 (remove (and region (list (region-beginning) (region-end))))
9662 (desc region)
9663 (link link-location)
9664 (abbrevs org-link-abbrev-alist-local)
9665 entry all-prefixes auto-desc)
9666 (cond
9667 (link-location) ; specified by arg, just use it.
9668 ((org-in-regexp org-bracket-link-regexp 1)
9669 ;; We do have a link at point, and we are going to edit it.
9670 (setq remove (list (match-beginning 0) (match-end 0)))
9671 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9672 (setq link (read-string "Link: "
9673 (org-link-unescape
9674 (match-string-no-properties 1)))))
9675 ((or (org-in-regexp org-angle-link-re)
9676 (org-in-regexp org-plain-link-re))
9677 ;; Convert to bracket link
9678 (setq remove (list (match-beginning 0) (match-end 0))
9679 link (read-string "Link: "
9680 (org-unbracket-string "<" ">" (match-string 0)))))
9681 ((member complete-file '((4) (16)))
9682 ;; Completing read for file names.
9683 (setq link (org-file-complete-link complete-file)))
9685 ;; Read link, with completion for stored links.
9686 (org-link-fontify-links-to-this-file)
9687 (org-switch-to-buffer-other-window "*Org Links*")
9688 (with-current-buffer "*Org Links*"
9689 (erase-buffer)
9690 (insert "Insert a link.
9691 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9692 (when org-stored-links
9693 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9694 (insert (mapconcat 'org-link-prettify
9695 (reverse org-stored-links) "\n")))
9696 (goto-char (point-min)))
9697 (let ((cw (selected-window)))
9698 (select-window (get-buffer-window "*Org Links*" 'visible))
9699 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9700 (unless (pos-visible-in-window-p (point-max))
9701 (org-fit-window-to-buffer))
9702 (and (window-live-p cw) (select-window cw)))
9703 (setq all-prefixes (append (mapcar 'car abbrevs)
9704 (mapcar 'car org-link-abbrev-alist)
9705 (org-link-types)))
9706 (unwind-protect
9707 ;; Fake a link history, containing the stored links.
9708 (let ((org--links-history
9709 (append (mapcar #'car org-stored-links)
9710 org-insert-link-history)))
9711 (setq link
9712 (org-completing-read
9713 "Link: "
9714 (append
9715 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9716 (mapcar #'car org-stored-links))
9717 nil nil nil
9718 'org--links-history
9719 (caar org-stored-links)))
9720 (unless (org-string-nw-p link) (user-error "No link selected"))
9721 (dolist (l org-stored-links)
9722 (when (equal link (cadr l))
9723 (setq link (car l))
9724 (setq auto-desc t)))
9725 (when (or (member link all-prefixes)
9726 (and (equal ":" (substring link -1))
9727 (member (substring link 0 -1) all-prefixes)
9728 (setq link (substring link 0 -1))))
9729 (setq link (with-current-buffer origbuf
9730 (org-link-try-special-completion link)))))
9731 (set-window-configuration wcf)
9732 (kill-buffer "*Org Links*"))
9733 (setq entry (assoc link org-stored-links))
9734 (or entry (push link org-insert-link-history))
9735 (setq desc (or desc (nth 1 entry)))))
9737 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9738 (not org-keep-stored-link-after-insertion))
9739 (setq org-stored-links (delq (assoc link org-stored-links)
9740 org-stored-links)))
9742 (when (and (string-match org-plain-link-re link)
9743 (not (string-match org-ts-regexp link)))
9744 ;; URL-like link, normalize the use of angular brackets.
9745 (setq link (org-unbracket-string "<" ">" link)))
9747 ;; Check if we are linking to the current file with a search
9748 ;; option If yes, simplify the link by using only the search
9749 ;; option.
9750 (when (and buffer-file-name
9751 (let ((case-fold-search nil))
9752 (string-match "\\`file:\\(.+?\\)::" link)))
9753 (let ((path (match-string-no-properties 1 link))
9754 (search (substring-no-properties link (match-end 0))))
9755 (save-match-data
9756 (when (equal (file-truename buffer-file-name) (file-truename path))
9757 ;; We are linking to this same file, with a search option
9758 (setq link search)))))
9760 ;; Check if we can/should use a relative path. If yes, simplify
9761 ;; the link.
9762 (let ((case-fold-search nil))
9763 (when (string-match "\\`\\(file\\|docview\\):" link)
9764 (let* ((type (match-string-no-properties 0 link))
9765 (path-start (match-end 0))
9766 (search (and (string-match "::\\(.*\\)\\'" link)
9767 (match-string 1 link)))
9768 (path
9769 (if search
9770 (substring-no-properties
9771 link path-start (match-beginning 0))
9772 (substring-no-properties link (match-end 0))))
9773 (origpath path))
9774 (cond
9775 ((or (eq org-link-file-path-type 'absolute)
9776 (equal complete-file '(16)))
9777 (setq path (abbreviate-file-name (expand-file-name path))))
9778 ((eq org-link-file-path-type 'noabbrev)
9779 (setq path (expand-file-name path)))
9780 ((eq org-link-file-path-type 'relative)
9781 (setq path (file-relative-name path)))
9783 (save-match-data
9784 (if (string-match (concat "^" (regexp-quote
9785 (expand-file-name
9786 (file-name-as-directory
9787 default-directory))))
9788 (expand-file-name path))
9789 ;; We are linking a file with relative path name.
9790 (setq path (substring (expand-file-name path)
9791 (match-end 0)))
9792 (setq path (abbreviate-file-name (expand-file-name path)))))))
9793 (setq link (concat type path (and search (concat "::" search))))
9794 (when (equal desc origpath)
9795 (setq desc path)))))
9797 (unless auto-desc
9798 (let ((initial-input
9799 (cond
9800 (default-description)
9801 ((not org-make-link-description-function) desc)
9802 (t (condition-case nil
9803 (funcall org-make-link-description-function link desc)
9804 (error
9805 (message "Can't get link description from `%s'"
9806 (symbol-name org-make-link-description-function))
9807 (sit-for 2)
9808 nil))))))
9809 (setq desc (if (called-interactively-p 'any)
9810 (read-string "Description: " initial-input)
9811 initial-input))))
9813 (unless (string-match "\\S-" desc) (setq desc nil))
9814 (when remove (apply 'delete-region remove))
9815 (insert (org-make-link-string link desc))
9816 ;; Redisplay so as the new link has proper invisible characters.
9817 (sit-for 0)))
9819 (defun org-link-try-special-completion (type)
9820 "If there is completion support for link type TYPE, offer it."
9821 (let ((fun (org-link-get-parameter type :complete)))
9822 (if (functionp fun)
9823 (funcall fun)
9824 (read-string "Link (no completion support): " (concat type ":")))))
9826 (defun org-file-complete-link (&optional arg)
9827 "Create a file link using completion."
9828 (let ((file (read-file-name "File: "))
9829 (pwd (file-name-as-directory (expand-file-name ".")))
9830 (pwd1 (file-name-as-directory (abbreviate-file-name
9831 (expand-file-name ".")))))
9832 (cond ((equal arg '(16))
9833 (concat "file:"
9834 (abbreviate-file-name (expand-file-name file))))
9835 ((string-match
9836 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9837 (concat "file:" (match-string 1 file)))
9838 ((string-match
9839 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9840 (expand-file-name file))
9841 (concat "file:"
9842 (match-string 1 (expand-file-name file))))
9843 (t (concat "file:" file)))))
9846 ;;; Opening/following a link
9848 (defvar org-link-search-failed nil)
9850 (defvar org-open-link-functions nil
9851 "Hook for functions finding a plain text link.
9852 These functions must take a single argument, the link content.
9853 They will be called for links that look like [[link text][description]]
9854 when LINK TEXT does not have a protocol like \"http:\" and does not look
9855 like a filename (e.g. \"./blue.png\").
9857 These functions will be called *before* Org attempts to resolve the
9858 link by doing text searches in the current buffer - so if you want a
9859 link \"[[target]]\" to still find \"<<target>>\", your function should
9860 handle this as a special case.
9862 When the function does handle the link, it must return a non-nil value.
9863 If it decides that it is not responsible for this link, it must return
9864 nil to indicate that that Org can continue with other options like
9865 exact and fuzzy text search.")
9867 (defun org-next-link (&optional search-backward)
9868 "Move forward to the next link.
9869 If the link is in hidden text, expose it."
9870 (interactive "P")
9871 (when (and org-link-search-failed (eq this-command last-command))
9872 (goto-char (point-min))
9873 (message "Link search wrapped back to beginning of buffer"))
9874 (setq org-link-search-failed nil)
9875 (let* ((pos (point))
9876 (ct (org-context))
9877 (a (assq :link ct))
9878 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9879 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9880 ((looking-at org-any-link-re)
9881 ;; Don't stay stuck at link without an org-link face
9882 (forward-char (if search-backward -1 1))))
9883 (if (funcall srch-fun org-any-link-re nil t)
9884 (progn
9885 (goto-char (match-beginning 0))
9886 (when (org-invisible-p) (org-show-context)))
9887 (goto-char pos)
9888 (setq org-link-search-failed t)
9889 (message "No further link found"))))
9891 (defun org-previous-link ()
9892 "Move backward to the previous link.
9893 If the link is in hidden text, expose it."
9894 (interactive)
9895 (funcall 'org-next-link t))
9897 (defun org-translate-link (s)
9898 "Translate a link string if a translation function has been defined."
9899 (with-temp-buffer
9900 (insert (org-trim s))
9901 (org-trim (org-element-interpret-data (org-element-context)))))
9903 (defun org-translate-link-from-planner (type path)
9904 "Translate a link from Emacs Planner syntax so that Org can follow it.
9905 This is still an experimental function, your mileage may vary."
9906 (cond
9907 ((member type '("http" "https" "news" "ftp"))
9908 ;; standard Internet links are the same.
9909 nil)
9910 ((and (equal type "irc") (string-match "^//" path))
9911 ;; Planner has two / at the beginning of an irc link, we have 1.
9912 ;; We should have zero, actually....
9913 (setq path (substring path 1)))
9914 ((and (equal type "lisp") (string-match "^/" path))
9915 ;; Planner has a slash, we do not.
9916 (setq type "elisp" path (substring path 1)))
9917 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9918 ;; A typical message link. Planner has the id after the final slash,
9919 ;; we separate it with a hash mark
9920 (setq path (concat (match-string 1 path) "#"
9921 (org-unbracket-string "<" ">" (match-string 2 path))))))
9922 (cons type path))
9924 (defun org-find-file-at-mouse (ev)
9925 "Open file link or URL at mouse."
9926 (interactive "e")
9927 (mouse-set-point ev)
9928 (org-open-at-point 'in-emacs))
9930 (defun org-open-at-mouse (ev)
9931 "Open file link or URL at mouse.
9932 See the docstring of `org-open-file' for details."
9933 (interactive "e")
9934 (mouse-set-point ev)
9935 (when (eq major-mode 'org-agenda-mode)
9936 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9937 (org-open-at-point))
9939 (defvar org-window-config-before-follow-link nil
9940 "The window configuration before following a link.
9941 This is saved in case the need arises to restore it.")
9943 ;;;###autoload
9944 (defun org-open-at-point-global ()
9945 "Follow a link or time-stamp like Org mode does.
9946 This command can be called in any mode to follow an external link
9947 or a time-stamp that has Org mode syntax. Its behavior is
9948 undefined when called on internal links (e.g., fuzzy links).
9949 Raise an error when there is nothing to follow. "
9950 (interactive)
9951 (cond ((org-in-regexp org-any-link-re)
9952 (org-open-link-from-string (match-string-no-properties 0)))
9953 ((or (org-in-regexp org-ts-regexp-both nil t)
9954 (org-in-regexp org-tsr-regexp-both nil t))
9955 (org-follow-timestamp-link))
9956 (t (user-error "No link found"))))
9958 ;;;###autoload
9959 (defun org-open-link-from-string (s &optional arg reference-buffer)
9960 "Open a link in the string S, as if it was in Org mode."
9961 (interactive "sLink: \nP")
9962 (let ((reference-buffer (or reference-buffer (current-buffer))))
9963 (with-temp-buffer
9964 (let ((org-inhibit-startup (not reference-buffer)))
9965 (org-mode)
9966 (insert s)
9967 (goto-char (point-min))
9968 (when reference-buffer
9969 (setq org-link-abbrev-alist-local
9970 (with-current-buffer reference-buffer
9971 org-link-abbrev-alist-local)))
9972 (org-open-at-point arg reference-buffer)))))
9974 (defvar org-open-at-point-functions nil
9975 "Hook that is run when following a link at point.
9977 Functions in this hook must return t if they identify and follow
9978 a link at point. If they don't find anything interesting at point,
9979 they must return nil.")
9981 (defvar org-link-search-inhibit-query nil)
9982 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9983 (defun org--open-doi-link (path)
9984 "Open a \"doi\" type link.
9985 PATH is a the path to search for, as a string."
9986 (browse-url (url-encode-url (concat org-doi-server-url path))))
9988 (defun org--open-elisp-link (path)
9989 "Open a \"elisp\" type link.
9990 PATH is the sexp to evaluate, as a string."
9991 (let ((cmd path))
9992 (if (or (and (org-string-nw-p
9993 org-confirm-elisp-link-not-regexp)
9994 (string-match-p org-confirm-elisp-link-not-regexp cmd))
9995 (not org-confirm-elisp-link-function)
9996 (funcall org-confirm-elisp-link-function
9997 (format "Execute \"%s\" as elisp? "
9998 (org-add-props cmd nil 'face 'org-warning))))
9999 (message "%s => %s" cmd
10000 (if (eq (string-to-char cmd) ?\()
10001 (eval (read cmd))
10002 (call-interactively (read cmd))))
10003 (user-error "Abort"))))
10005 (defun org--open-help-link (path)
10006 "Open a \"help\" type link.
10007 PATH is a symbol name, as a string."
10008 (pcase (intern path)
10009 ((and (pred fboundp) variable) (describe-function variable))
10010 ((and (pred boundp) function) (describe-variable function))
10011 (name (user-error "Unknown function or variable: %s" name))))
10013 (defun org--open-shell-link (path)
10014 "Open a \"shell\" type link.
10015 PATH is the command to execute, as a string."
10016 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10017 (cmd path))
10018 (if (or (and (org-string-nw-p
10019 org-confirm-shell-link-not-regexp)
10020 (string-match
10021 org-confirm-shell-link-not-regexp cmd))
10022 (not org-confirm-shell-link-function)
10023 (funcall org-confirm-shell-link-function
10024 (format "Execute \"%s\" in shell? "
10025 (org-add-props cmd nil
10026 'face 'org-warning))))
10027 (progn
10028 (message "Executing %s" cmd)
10029 (shell-command cmd buf)
10030 (when (featurep 'midnight)
10031 (setq clean-buffer-list-kill-buffer-names
10032 (cons (buffer-name buf)
10033 clean-buffer-list-kill-buffer-names))))
10034 (user-error "Abort"))))
10036 (defun org-open-at-point (&optional arg reference-buffer)
10037 "Open link, timestamp, footnote or tags at point.
10039 When point is on a link, follow it. Normally, files will be
10040 opened by an appropriate application. If the optional prefix
10041 argument ARG is non-nil, Emacs will visit the file. With
10042 a double prefix argument, try to open outside of Emacs, in the
10043 application the system uses for this file type.
10045 When point is on a timestamp, open the agenda at the day
10046 specified.
10048 When point is a footnote definition, move to the first reference
10049 found. If it is on a reference, move to the associated
10050 definition.
10052 When point is on a headline, display a list of every link in the
10053 entry, so it is possible to pick one, or all, of them. If point
10054 is on a tag, call `org-tags-view' instead.
10056 When optional argument REFERENCE-BUFFER is non-nil, it should
10057 specify a buffer from where the link search should happen. This
10058 is used internally by `org-open-link-from-string'.
10060 On top of syntactically correct links, this function will also
10061 try to open links and time-stamps in comments, example
10062 blocks... i.e., whenever point is on something looking like
10063 a timestamp or a link."
10064 (interactive "P")
10065 ;; On a code block, open block's results.
10066 (unless (call-interactively 'org-babel-open-src-block-result)
10067 (org-load-modules-maybe)
10068 (setq org-window-config-before-follow-link (current-window-configuration))
10069 (org-remove-occur-highlights nil nil t)
10070 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10071 (let* ((context
10072 ;; Only consider supported types, even if they are not
10073 ;; the closest one.
10074 (org-element-lineage
10075 (org-element-context)
10076 '(clock footnote-definition footnote-reference headline
10077 inlinetask link timestamp)
10079 (type (org-element-type context))
10080 (value (org-element-property :value context)))
10081 (cond
10082 ;; On a headline or an inlinetask, but not on a timestamp,
10083 ;; a link, a footnote reference.
10084 ((memq type '(headline inlinetask))
10085 (org-match-line org-complex-heading-regexp)
10086 (if (and (match-beginning 5)
10087 (>= (point) (match-beginning 5))
10088 (< (point) (match-end 5)))
10089 ;; On tags.
10090 (org-tags-view arg (substring (match-string 5) 0 -1))
10091 ;; Not on tags.
10092 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10093 (`(nil . ,_)
10094 (require 'org-attach)
10095 (org-attach-reveal 'if-exists))
10096 (`(,links . ,links-end)
10097 (dolist (link (if (stringp links) (list links) links))
10098 (search-forward link nil links-end)
10099 (goto-char (match-beginning 0))
10100 (org-open-at-point))))))
10101 ;; On a footnote reference or at definition's label.
10102 ((or (eq type 'footnote-reference)
10103 (and (eq type 'footnote-definition)
10104 (save-excursion
10105 ;; Do not validate action when point is on the
10106 ;; spaces right after the footnote label, in
10107 ;; order to be on par with behaviour on links.
10108 (skip-chars-forward " \t")
10109 (let ((begin
10110 (org-element-property :contents-begin context)))
10111 (if begin (< (point) begin)
10112 (= (org-element-property :post-affiliated context)
10113 (line-beginning-position)))))))
10114 (org-footnote-action))
10115 ;; No valid context. Ignore catch-all types like `headline'.
10116 ;; If point is on something looking like a link or
10117 ;; a time-stamp, try opening it. It may be useful in
10118 ;; comments, example blocks...
10119 ((memq type '(footnote-definition headline inlinetask nil))
10120 (call-interactively #'org-open-at-point-global))
10121 ;; On a clock line, make sure point is on the timestamp
10122 ;; before opening it.
10123 ((and (eq type 'clock)
10124 value
10125 (>= (point) (org-element-property :begin value))
10126 (<= (point) (org-element-property :end value)))
10127 (org-follow-timestamp-link))
10128 ;; Do nothing on white spaces after an object.
10129 ((>= (point)
10130 (save-excursion
10131 (goto-char (org-element-property :end context))
10132 (skip-chars-backward " \t")
10133 (point)))
10134 (user-error "No link found"))
10135 ((eq type 'timestamp) (org-follow-timestamp-link))
10136 ((eq type 'link)
10137 (let ((type (org-element-property :type context))
10138 (path (org-link-unescape (org-element-property :path context))))
10139 ;; Switch back to REFERENCE-BUFFER needed when called in
10140 ;; a temporary buffer through `org-open-link-from-string'.
10141 (with-current-buffer (or reference-buffer (current-buffer))
10142 (cond
10143 ((equal type "file")
10144 (if (string-match "[*?{]" (file-name-nondirectory path))
10145 (dired path)
10146 ;; Look into `org-link-parameters' in order to find
10147 ;; a DEDICATED-FUNCTION to open file. The function
10148 ;; will be applied on raw link instead of parsed
10149 ;; link due to the limitation in `org-add-link-type'
10150 ;; ("open" function called with a single argument).
10151 ;; If no such function is found, fallback to
10152 ;; `org-open-file'.
10153 (let* ((option (org-element-property :search-option context))
10154 (app (org-element-property :application context))
10155 (dedicated-function
10156 (org-link-get-parameter
10157 (if app (concat type "+" app) type)
10158 :follow)))
10159 (if dedicated-function
10160 (funcall dedicated-function
10161 (concat path
10162 (and option (concat "::" option))))
10163 (apply #'org-open-file
10164 path
10165 (cond (arg)
10166 ((equal app "emacs") 'emacs)
10167 ((equal app "sys") 'system))
10168 (cond ((not option) nil)
10169 ((string-match-p "\\`[0-9]+\\'" option)
10170 (list (string-to-number option)))
10171 (t (list nil
10172 (org-link-unescape option)))))))))
10173 ((functionp (org-link-get-parameter type :follow))
10174 (funcall (org-link-get-parameter type :follow) path))
10175 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10176 (unless (run-hook-with-args-until-success
10177 'org-open-link-functions path)
10178 (if (not arg) (org-mark-ring-push)
10179 (switch-to-buffer-other-window
10180 (org-get-buffer-for-internal-link (current-buffer))))
10181 (let ((destination
10182 (org-with-wide-buffer
10183 (if (equal type "radio")
10184 (org-search-radio-target
10185 (org-element-property :path context))
10186 (org-link-search
10187 (if (member type '("custom-id" "coderef"))
10188 (org-element-property :raw-link context)
10189 path)
10190 ;; Prevent fuzzy links from matching
10191 ;; themselves.
10192 (and (equal type "fuzzy")
10193 (+ 2 (org-element-property :begin context)))))
10194 (point))))
10195 (unless (and (<= (point-min) destination)
10196 (>= (point-max) destination))
10197 (widen))
10198 (goto-char destination))))
10199 (t (browse-url-at-point))))))
10200 (t (user-error "No link found")))))
10201 (run-hook-with-args 'org-follow-link-hook)))
10203 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10204 "Offer links in the current entry and return the selected link.
10205 If there is only one link, return it.
10206 If NTH is an integer, return the NTH link found.
10207 If ZERO is a string, check also this string for a link, and if
10208 there is one, return it."
10209 (with-current-buffer buffer
10210 (org-with-wide-buffer
10211 (goto-char marker)
10212 (let ((cnt ?0)
10213 have-zero end links link c)
10214 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10215 (push (match-string 0 zero) links)
10216 (setq cnt (1- cnt) have-zero t))
10217 (save-excursion
10218 (org-back-to-heading t)
10219 (setq end (save-excursion (outline-next-heading) (point)))
10220 (while (re-search-forward org-any-link-re end t)
10221 (push (match-string 0) links))
10222 (setq links (org-uniquify (reverse links))))
10223 (cond
10224 ((null links)
10225 (message "No links"))
10226 ((equal (length links) 1)
10227 (setq link (car links)))
10228 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10229 (setq link (nth (if have-zero nth (1- nth)) links)))
10230 (t ; we have to select a link
10231 (save-excursion
10232 (save-window-excursion
10233 (delete-other-windows)
10234 (with-output-to-temp-buffer "*Select Link*"
10235 (dolist (l links)
10236 (cond
10237 ((not (string-match org-bracket-link-regexp l))
10238 (princ (format "[%c] %s\n" (cl-incf cnt)
10239 (org-unbracket-string "<" ">" l))))
10240 ((match-end 3)
10241 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10242 (match-string 3 l) (match-string 1 l))))
10243 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10244 (match-string 1 l)))))))
10245 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10246 (message "Select link to open, RET to open all:")
10247 (setq c (read-char-exclusive))
10248 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10249 (when (equal c ?q) (user-error "Abort"))
10250 (if (equal c ?\C-m)
10251 (setq link links)
10252 (setq nth (- c ?0))
10253 (when have-zero (setq nth (1+ nth)))
10254 (unless (and (integerp nth) (>= (length links) nth))
10255 (user-error "Invalid link selection"))
10256 (setq link (nth (1- nth) links)))))
10257 (cons link end)))))
10259 ;; TODO: These functions are deprecated since `org-open-at-point'
10260 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10261 (defun org-open-file-with-system (path)
10262 "Open file at PATH using the system way of opening it."
10263 (org-open-file path 'system))
10264 (defun org-open-file-with-emacs (path)
10265 "Open file at PATH in Emacs."
10266 (org-open-file path 'emacs))
10269 ;;; File search
10271 (defvar org-create-file-search-functions nil
10272 "List of functions to construct the right search string for a file link.
10273 These functions are called in turn with point at the location to
10274 which the link should point.
10276 A function in the hook should first test if it would like to
10277 handle this file type, for example by checking the `major-mode'
10278 or the file extension. If it decides not to handle this file, it
10279 should just return nil to give other functions a chance. If it
10280 does handle the file, it must return the search string to be used
10281 when following the link. The search string will be part of the
10282 file link, given after a double colon, and `org-open-at-point'
10283 will automatically search for it. If special measures must be
10284 taken to make the search successful, another function should be
10285 added to the companion hook `org-execute-file-search-functions',
10286 which see.
10288 A function in this hook may also use `setq' to set the variable
10289 `description' to provide a suggestion for the descriptive text to
10290 be used for this link when it gets inserted into an Org buffer
10291 with \\[org-insert-link].")
10293 (defvar org-execute-file-search-functions nil
10294 "List of functions to execute a file search triggered by a link.
10296 Functions added to this hook must accept a single argument, the
10297 search string that was part of the file link, the part after the
10298 double colon. The function must first check if it would like to
10299 handle this search, for example by checking the `major-mode' or
10300 the file extension. If it decides not to handle this search, it
10301 should just return nil to give other functions a chance. If it
10302 does handle the search, it must return a non-nil value to keep
10303 other functions from trying.
10305 Each function can access the current prefix argument through the
10306 variable `current-prefix-arg'. Note that a single prefix is used
10307 to force opening a link in Emacs, so it may be good to only use a
10308 numeric or double prefix to guide the search function.
10310 In case this is needed, a function in this hook can also restore
10311 the window configuration before `org-open-at-point' was called using:
10313 (set-window-configuration org-window-config-before-follow-link)")
10315 (defun org-search-radio-target (target)
10316 "Search a radio target matching TARGET in current buffer.
10317 White spaces are not significant."
10318 (let ((re (format "<<<%s>>>"
10319 (mapconcat #'regexp-quote
10320 (split-string target)
10321 "[ \t]+\\(?:\n[ \t]*\\)?")))
10322 (origin (point)))
10323 (goto-char (point-min))
10324 (catch :radio-match
10325 (while (re-search-forward re nil t)
10326 (backward-char)
10327 (let ((object (org-element-context)))
10328 (when (eq (org-element-type object) 'radio-target)
10329 (goto-char (org-element-property :begin object))
10330 (org-show-context 'link-search)
10331 (throw :radio-match nil))))
10332 (goto-char origin)
10333 (user-error "No match for radio target: %s" target))))
10335 (defun org-link-search (s &optional avoid-pos stealth)
10336 "Search for a search string S.
10338 If S starts with \"#\", it triggers a custom ID search.
10340 If S is enclosed within parenthesis, it initiates a coderef
10341 search.
10343 If S is surrounded by forward slashes, it is interpreted as
10344 a regular expression. In Org mode files, this will create an
10345 `org-occur' sparse tree. In ordinary files, `occur' will be used
10346 to list matches. If the current buffer is in `dired-mode', grep
10347 will be used to search in all files.
10349 When AVOID-POS is given, ignore matches near that position.
10351 When optional argument STEALTH is non-nil, do not modify
10352 visibility around point, thus ignoring `org-show-context-detail'
10353 variable.
10355 Search is case-insensitive and ignores white spaces. Return type
10356 of matched result, which is either `dedicated' or `fuzzy'."
10357 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10358 (let* ((case-fold-search t)
10359 (origin (point))
10360 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10361 (starred (eq (string-to-char normalized) ?*))
10362 (words (split-string (if starred (substring s 1) s)))
10363 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10364 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10365 type)
10366 (cond
10367 ;; Check if there are any special search functions.
10368 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10369 ((eq (string-to-char s) ?#)
10370 ;; Look for a custom ID S if S starts with "#".
10371 (let* ((id (substring normalized 1))
10372 (match (org-find-property "CUSTOM_ID" id)))
10373 (if match (progn (goto-char match) (setf type 'dedicated))
10374 (error "No match for custom ID: %s" id))))
10375 ((string-match "\\`(\\(.*\\))\\'" normalized)
10376 ;; Look for coderef targets if S is enclosed within parenthesis.
10377 (let ((coderef (match-string-no-properties 1 normalized))
10378 (re (substring s-single-re 1 -1)))
10379 (goto-char (point-min))
10380 (catch :coderef-match
10381 (while (re-search-forward re nil t)
10382 (let ((element (org-element-at-point)))
10383 (when (and (memq (org-element-type element)
10384 '(example-block src-block))
10385 ;; Build proper regexp according to current
10386 ;; block's label format.
10387 (let ((label-fmt
10388 (regexp-quote
10389 (or (org-element-property :label-fmt element)
10390 org-coderef-label-format))))
10391 (save-excursion
10392 (beginning-of-line)
10393 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10394 (format label-fmt coderef))))))
10395 (setq type 'dedicated)
10396 (goto-char (match-beginning 1))
10397 (throw :coderef-match nil))))
10398 (goto-char origin)
10399 (error "No match for coderef: %s" coderef))))
10400 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10401 ;; Look for a regular expression.
10402 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10403 (match-string 1 s)))
10404 ;; From here, we handle fuzzy links.
10406 ;; Look for targets, only if not in a headline search.
10407 ((and (not starred)
10408 (let ((target (format "<<%s>>" s-multi-re)))
10409 (catch :target-match
10410 (goto-char (point-min))
10411 (while (re-search-forward target nil t)
10412 (backward-char)
10413 (let ((context (org-element-context)))
10414 (when (eq (org-element-type context) 'target)
10415 (setq type 'dedicated)
10416 (goto-char (org-element-property :begin context))
10417 (throw :target-match t))))
10418 nil))))
10419 ;; Look for elements named after S, only if not in a headline
10420 ;; search.
10421 ((and (not starred)
10422 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10423 (catch :name-match
10424 (goto-char (point-min))
10425 (while (re-search-forward name nil t)
10426 (let ((element (org-element-at-point)))
10427 (when (equal words
10428 (split-string
10429 (org-element-property :name element)))
10430 (setq type 'dedicated)
10431 (beginning-of-line)
10432 (throw :name-match t))))
10433 nil))))
10434 ;; Regular text search. Prefer headlines in Org mode buffers.
10435 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10436 ;; statistics cookies and tags.
10437 ((and (derived-mode-p 'org-mode)
10438 (let ((title-re
10439 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10440 org-outline-regexp-bol
10441 org-comment-string
10442 (mapconcat #'regexp-quote words ".+")))
10443 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10444 (comment-re (eval-when-compile
10445 (format "\\`%s[ \t]+" org-comment-string))))
10446 (goto-char (point-min))
10447 (catch :found
10448 (while (re-search-forward title-re nil t)
10449 (when (equal words
10450 (split-string
10451 (replace-regexp-in-string
10452 cookie-re ""
10453 (replace-regexp-in-string
10454 comment-re "" (org-get-heading t t t)))))
10455 (throw :found t)))
10456 nil)))
10457 (beginning-of-line)
10458 (setq type 'dedicated))
10459 ;; Offer to create non-existent headline depending on
10460 ;; `org-link-search-must-match-exact-headline'.
10461 ((and (derived-mode-p 'org-mode)
10462 (not org-link-search-inhibit-query)
10463 (eq org-link-search-must-match-exact-headline 'query-to-create)
10464 (yes-or-no-p "No match - create this as a new heading? "))
10465 (goto-char (point-max))
10466 (unless (bolp) (newline))
10467 (org-insert-heading nil t t)
10468 (insert s "\n")
10469 (beginning-of-line 0))
10470 ;; Only headlines are looked after. No need to process
10471 ;; further: throw an error.
10472 ((and (derived-mode-p 'org-mode)
10473 (or starred org-link-search-must-match-exact-headline))
10474 (goto-char origin)
10475 (error "No match for fuzzy expression: %s" normalized))
10476 ;; Regular text search.
10477 ((catch :fuzzy-match
10478 (goto-char (point-min))
10479 (while (re-search-forward s-multi-re nil t)
10480 ;; Skip match if it contains AVOID-POS or it is included in
10481 ;; a link with a description but outside the description.
10482 (unless (or (and avoid-pos
10483 (<= (match-beginning 0) avoid-pos)
10484 (> (match-end 0) avoid-pos))
10485 (and (save-match-data
10486 (org-in-regexp org-bracket-link-regexp))
10487 (match-beginning 3)
10488 (or (> (match-beginning 3) (point))
10489 (<= (match-end 3) (point)))
10490 (org-element-lineage
10491 (save-match-data (org-element-context))
10492 '(link) t)))
10493 (goto-char (match-beginning 0))
10494 (setq type 'fuzzy)
10495 (throw :fuzzy-match t)))
10496 nil))
10497 ;; All failed. Throw an error.
10498 (t (goto-char origin)
10499 (error "No match for fuzzy expression: %s" normalized)))
10500 ;; Disclose surroundings of match, if appropriate.
10501 (when (and (derived-mode-p 'org-mode) (not stealth))
10502 (org-show-context 'link-search))
10503 type))
10505 (defun org-get-buffer-for-internal-link (buffer)
10506 "Return a buffer to be used for displaying the link target of internal links."
10507 (cond
10508 ((not org-display-internal-link-with-indirect-buffer)
10509 buffer)
10510 ((string-suffix-p "(Clone)" (buffer-name buffer))
10511 (message "Buffer is already a clone, not making another one")
10512 ;; we also do not modify visibility in this case
10513 buffer)
10514 (t ; make a new indirect buffer for displaying the link
10515 (let* ((bn (buffer-name buffer))
10516 (ibn (concat bn "(Clone)"))
10517 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10518 (with-current-buffer ib (org-overview))
10519 ib))))
10521 (defun org-do-occur (regexp &optional cleanup)
10522 "Call the Emacs command `occur'.
10523 If CLEANUP is non-nil, remove the printout of the regular expression
10524 in the *Occur* buffer. This is useful if the regex is long and not useful
10525 to read."
10526 (occur regexp)
10527 (when cleanup
10528 (let ((cwin (selected-window)) win beg end)
10529 (when (setq win (get-buffer-window "*Occur*"))
10530 (select-window win))
10531 (goto-char (point-min))
10532 (when (re-search-forward "match[a-z]+" nil t)
10533 (setq beg (match-end 0))
10534 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10535 (setq end (1- (match-beginning 0)))))
10536 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10537 (goto-char (point-min))
10538 (select-window cwin))))
10540 ;;; The mark ring for links jumps
10542 (defvar org-mark-ring nil
10543 "Mark ring for positions before jumps in Org mode.")
10544 (defvar org-mark-ring-last-goto nil
10545 "Last position in the mark ring used to go back.")
10546 ;; Fill and close the ring
10547 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10548 (dotimes (_ org-mark-ring-length)
10549 (push (make-marker) org-mark-ring))
10550 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10551 org-mark-ring)
10553 (defun org-mark-ring-push (&optional pos buffer)
10554 "Put the current position or POS into the mark ring and rotate it."
10555 (interactive)
10556 (setq pos (or pos (point)))
10557 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10558 (move-marker (car org-mark-ring)
10559 (or pos (point))
10560 (or buffer (current-buffer)))
10561 (message "%s"
10562 (substitute-command-keys
10563 "Position saved to mark ring, go back with \
10564 `\\[org-mark-ring-goto]'.")))
10566 (defun org-mark-ring-goto (&optional n)
10567 "Jump to the previous position in the mark ring.
10568 With prefix arg N, jump back that many stored positions. When
10569 called several times in succession, walk through the entire ring.
10570 Org mode commands jumping to a different position in the current file,
10571 or to another Org file, automatically push the old position onto the ring."
10572 (interactive "p")
10573 (let (p m)
10574 (if (eq last-command this-command)
10575 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10576 (setq p org-mark-ring))
10577 (setq org-mark-ring-last-goto p)
10578 (setq m (car p))
10579 (pop-to-buffer-same-window (marker-buffer m))
10580 (goto-char m)
10581 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10583 (defun org-add-angle-brackets (s)
10584 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10585 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10588 ;;; Following specific links
10590 (defvar org-agenda-buffer-tmp-name)
10591 (defvar org-agenda-start-on-weekday)
10592 (defun org-follow-timestamp-link ()
10593 "Open an agenda view for the time-stamp date/range at point."
10594 (cond
10595 ((org-at-date-range-p t)
10596 (let ((org-agenda-start-on-weekday)
10597 (t1 (match-string 1))
10598 (t2 (match-string 2)) tt1 tt2)
10599 (setq tt1 (time-to-days (org-time-string-to-time t1))
10600 tt2 (time-to-days (org-time-string-to-time t2)))
10601 (let ((org-agenda-buffer-tmp-name
10602 (format "*Org Agenda(a:%s)"
10603 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10604 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10605 ((org-at-timestamp-p 'lax)
10606 (let ((org-agenda-buffer-tmp-name
10607 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10608 (org-agenda-list nil (time-to-days (org-time-string-to-time
10609 (substring (match-string 1) 0 10)))
10610 1)))
10611 (t (error "This should not happen"))))
10614 ;;; Following file links
10615 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10616 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10617 (declare-function mailcap-mime-info
10618 "mailcap" (string &optional request no-decode))
10619 (defvar org-wait nil)
10620 (defun org-open-file (path &optional in-emacs line search)
10621 "Open the file at PATH.
10622 First, this expands any special file name abbreviations. Then the
10623 configuration variable `org-file-apps' is checked if it contains an
10624 entry for this file type, and if yes, the corresponding command is launched.
10626 If no application is found, Emacs simply visits the file.
10628 With optional prefix argument IN-EMACS, Emacs will visit the file.
10629 With a double \\[universal-argument] \\[universal-argument] \
10630 prefix arg, Org tries to avoid opening in Emacs
10631 and to use an external application to visit the file.
10633 Optional LINE specifies a line to go to, optional SEARCH a string
10634 to search for. If LINE or SEARCH is given, the file will be
10635 opened in Emacs, unless an entry from org-file-apps that makes
10636 use of groups in a regexp matches.
10638 If you want to change the way frames are used when following a
10639 link, please customize `org-link-frame-setup'.
10641 If the file does not exist, an error is thrown."
10642 (let* ((file (if (equal path "")
10643 buffer-file-name
10644 (substitute-in-file-name (expand-file-name path))))
10645 (file-apps (append org-file-apps (org-default-apps)))
10646 (apps (cl-remove-if
10647 'org-file-apps-entry-match-against-dlink-p file-apps))
10648 (apps-dlink (cl-remove-if-not
10649 'org-file-apps-entry-match-against-dlink-p file-apps))
10650 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10651 (dirp (unless remp (file-directory-p file)))
10652 (file (if (and dirp org-open-directory-means-index-dot-org)
10653 (concat (file-name-as-directory file) "index.org")
10654 file))
10655 (a-m-a-p (assq 'auto-mode apps))
10656 (dfile (downcase file))
10657 ;; Reconstruct the original link from the PATH, LINE and
10658 ;; SEARCH args.
10659 (link (cond (line (concat file "::" (number-to-string line)))
10660 (search (concat file "::" search))
10661 (t file)))
10662 (dlink (downcase link))
10663 (ext
10664 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10665 (match-string 1 dfile)))
10666 (save-position-maybe
10667 (let ((old-buffer (current-buffer))
10668 (old-pos (point))
10669 (old-mode major-mode))
10670 (lambda ()
10671 (and (derived-mode-p 'org-mode)
10672 (eq old-mode 'org-mode)
10673 (or (not (eq old-buffer (current-buffer)))
10674 (not (eq old-pos (point))))
10675 (org-mark-ring-push old-pos old-buffer)))))
10676 cmd link-match-data)
10677 (cond
10678 ((member in-emacs '((16) system))
10679 (setq cmd (cdr (assq 'system apps))))
10680 (in-emacs (setq cmd 'emacs))
10682 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10683 (and dirp (cdr (assq 'directory apps)))
10684 ;; First, try matching against apps-dlink if we
10685 ;; get a match here, store the match data for
10686 ;; later.
10687 (let ((match (assoc-default dlink apps-dlink
10688 'string-match)))
10689 (if match
10690 (progn (setq link-match-data (match-data))
10691 match)
10692 (progn (setq in-emacs (or in-emacs line search))
10693 nil))) ; if we have no match in apps-dlink,
10694 ; always open the file in emacs if line or search
10695 ; is given (for backwards compatibility)
10696 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10697 'string-match)
10698 (cdr (assoc ext apps))
10699 (cdr (assq t apps))))))
10700 (when (eq cmd 'system)
10701 (setq cmd (cdr (assq 'system apps))))
10702 (when (eq cmd 'default)
10703 (setq cmd (cdr (assoc t apps))))
10704 (when (eq cmd 'mailcap)
10705 (require 'mailcap)
10706 (mailcap-parse-mailcaps)
10707 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10708 (command (mailcap-mime-info mime-type)))
10709 (if (stringp command)
10710 (setq cmd command)
10711 (setq cmd 'emacs))))
10712 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10713 (not (file-exists-p file))
10714 (not org-open-non-existing-files))
10715 (user-error "No such file: %s" file))
10716 (cond
10717 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10718 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10719 (while (string-match "['\"]%s['\"]" cmd)
10720 (setq cmd (replace-match "%s" t t cmd)))
10721 (setq cmd (replace-regexp-in-string
10722 "%s"
10723 (shell-quote-argument (convert-standard-filename file))
10725 nil t))
10727 ;; Replace "%1", "%2" etc. in command with group matches from regex
10728 (save-match-data
10729 (let ((match-index 1)
10730 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10731 (set-match-data link-match-data)
10732 (while (<= match-index number-of-groups)
10733 (let ((regex (concat "%" (number-to-string match-index)))
10734 (replace-with (match-string match-index dlink)))
10735 (while (string-match regex cmd)
10736 (setq cmd (replace-match replace-with t t cmd))))
10737 (setq match-index (+ match-index 1)))))
10739 (save-window-excursion
10740 (message "Running %s...done" cmd)
10741 (start-process-shell-command cmd nil cmd)
10742 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10743 ((or (stringp cmd)
10744 (eq cmd 'emacs))
10745 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10746 (widen)
10747 (cond (line (org-goto-line line)
10748 (when (derived-mode-p 'org-mode) (org-reveal)))
10749 (search (condition-case err
10750 (org-link-search search)
10751 ;; Save position before error-ing out so user
10752 ;; can easily move back to the original buffer.
10753 (error (funcall save-position-maybe)
10754 (error (nth 1 err)))))))
10755 ((functionp cmd)
10756 (save-match-data
10757 (set-match-data link-match-data)
10758 (condition-case nil
10759 (funcall cmd file link)
10760 ;; FIXME: Remove this check when most default installations
10761 ;; of Emacs have at least Org 9.0.
10762 ((debug wrong-number-of-arguments wrong-type-argument
10763 invalid-function)
10764 (user-error "Please see Org News for version 9.0 about \
10765 `org-file-apps'--Lisp error: %S" cmd)))))
10766 ((consp cmd)
10767 ;; FIXME: Remove this check when most default installations of
10768 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10769 ;; fall back to `org-link-frame-setup' for an old usage of
10770 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10771 (user-error "Please see Org News for version 9.0 about \
10772 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10773 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10774 (funcall save-position-maybe)))
10776 (defun org-file-apps-entry-match-against-dlink-p (entry)
10777 "This function returns non-nil if `entry' uses a regular
10778 expression which should be matched against the whole link by
10779 org-open-file.
10781 It assumes that is the case when the entry uses a regular
10782 expression which has at least one grouping construct and the
10783 action is either a lisp form or a command string containing
10784 `%1', i.e. using at least one subexpression match as a
10785 parameter."
10786 (let ((selector (car entry))
10787 (action (cdr entry)))
10788 (if (stringp selector)
10789 (and (> (regexp-opt-depth selector) 0)
10790 (or (and (stringp action)
10791 (string-match "%[0-9]" action))
10792 (consp action)))
10793 nil)))
10795 (defun org-default-apps ()
10796 "Return the default applications for this operating system."
10797 (cond
10798 ((eq system-type 'darwin)
10799 org-file-apps-defaults-macosx)
10800 ((eq system-type 'windows-nt)
10801 org-file-apps-defaults-windowsnt)
10802 (t org-file-apps-defaults-gnu)))
10804 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10805 "Convert extensions to regular expressions in the cars of LIST.
10806 Also, weed out any non-string entries, because the return value is used
10807 only for regexp matching.
10808 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10809 point to the symbol `emacs', indicating that the file should
10810 be opened in Emacs."
10811 (append
10812 (delq nil
10813 (mapcar (lambda (x)
10814 (unless (not (stringp (car x)))
10815 (if (string-match "\\W" (car x))
10817 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10818 list))
10819 (when add-auto-mode
10820 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10822 (defvar ange-ftp-name-format)
10823 (defun org-file-remote-p (file)
10824 "Test whether FILE specifies a location on a remote system.
10825 Return non-nil if the location is indeed remote.
10827 For example, the filename \"/user@host:/foo\" specifies a location
10828 on the system \"/user@host:\"."
10829 (cond ((fboundp 'file-remote-p)
10830 (file-remote-p file))
10831 ((fboundp 'tramp-handle-file-remote-p)
10832 (tramp-handle-file-remote-p file))
10833 ((and (boundp 'ange-ftp-name-format)
10834 (string-match (car ange-ftp-name-format) file))
10835 t)))
10838 ;;;; Refiling
10840 (defun org-get-org-file ()
10841 "Read a filename, with default directory `org-directory'."
10842 (let ((default (or org-default-notes-file remember-data-file)))
10843 (read-file-name (format "File name [%s]: " default)
10844 (file-name-as-directory org-directory)
10845 default)))
10847 (defun org-notes-order-reversed-p ()
10848 "Check if the current file should receive notes in reversed order."
10849 (cond
10850 ((not org-reverse-note-order) nil)
10851 ((eq t org-reverse-note-order) t)
10852 ((not (listp org-reverse-note-order)) nil)
10853 (t (catch 'exit
10854 (dolist (entry org-reverse-note-order)
10855 (when (string-match (car entry) buffer-file-name)
10856 (throw 'exit (cdr entry))))))))
10858 (defvar org-refile-target-table nil
10859 "The list of refile targets, created by `org-refile'.")
10861 (defvar org-agenda-new-buffers nil
10862 "Buffers created to visit agenda files.")
10864 (defvar org-refile-cache nil
10865 "Cache for refile targets.")
10867 (defvar org-refile-markers nil
10868 "All the markers used for caching refile locations.")
10870 (defun org-refile-marker (pos)
10871 "Get a new refile marker, but only if caching is in use."
10872 (if (not org-refile-use-cache)
10874 (let ((m (make-marker)))
10875 (move-marker m pos)
10876 (push m org-refile-markers)
10877 m)))
10879 (defun org-refile-cache-clear ()
10880 "Clear the refile cache and disable all the markers."
10881 (dolist (m org-refile-markers) (move-marker m nil))
10882 (setq org-refile-markers nil)
10883 (setq org-refile-cache nil)
10884 (message "Refile cache has been cleared"))
10886 (defun org-refile-cache-check-set (set)
10887 "Check if all the markers in the cache still have live buffers."
10888 (let (marker)
10889 (catch 'exit
10890 (while (and set (setq marker (nth 3 (pop set))))
10891 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10892 (when (and marker (null (marker-buffer marker)))
10893 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10894 (sit-for 3)
10895 (throw 'exit nil)))
10896 t)))
10898 (defun org-refile-cache-put (set &rest identifiers)
10899 "Push the refile targets SET into the cache, under IDENTIFIERS."
10900 (let* ((key (sha1 (prin1-to-string identifiers)))
10901 (entry (assoc key org-refile-cache)))
10902 (if entry
10903 (setcdr entry set)
10904 (push (cons key set) org-refile-cache))))
10906 (defun org-refile-cache-get (&rest identifiers)
10907 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10908 (cond
10909 ((not org-refile-cache) nil)
10910 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10912 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10913 org-refile-cache))))
10914 (and set (org-refile-cache-check-set set) set)))))
10916 (defvar org-outline-path-cache nil
10917 "Alist between buffer positions and outline paths.
10918 It value is an alist (POSITION . PATH) where POSITION is the
10919 buffer position at the beginning of an entry and PATH is a list
10920 of strings describing the outline path for that entry, in reverse
10921 order.")
10923 (defun org-refile-get-targets (&optional default-buffer)
10924 "Produce a table with refile targets."
10925 (let ((case-fold-search nil)
10926 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10927 (entries (or org-refile-targets '((nil . (:level . 1)))))
10928 targets tgs files desc descre)
10929 (message "Getting targets...")
10930 (with-current-buffer (or default-buffer (current-buffer))
10931 (dolist (entry entries)
10932 (setq files (car entry) desc (cdr entry))
10933 (cond
10934 ((null files) (setq files (list (current-buffer))))
10935 ((eq files 'org-agenda-files)
10936 (setq files (org-agenda-files 'unrestricted)))
10937 ((and (symbolp files) (fboundp files))
10938 (setq files (funcall files)))
10939 ((and (symbolp files) (boundp files))
10940 (setq files (symbol-value files))))
10941 (when (stringp files) (setq files (list files)))
10942 (cond
10943 ((eq (car desc) :tag)
10944 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10945 ((eq (car desc) :todo)
10946 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10947 ((eq (car desc) :regexp)
10948 (setq descre (cdr desc)))
10949 ((eq (car desc) :level)
10950 (setq descre (concat "^\\*\\{" (number-to-string
10951 (if org-odd-levels-only
10952 (1- (* 2 (cdr desc)))
10953 (cdr desc)))
10954 "\\}[ \t]")))
10955 ((eq (car desc) :maxlevel)
10956 (setq descre (concat "^\\*\\{1," (number-to-string
10957 (if org-odd-levels-only
10958 (1- (* 2 (cdr desc)))
10959 (cdr desc)))
10960 "\\}[ \t]")))
10961 (t (error "Bad refiling target description %s" desc)))
10962 (dolist (f files)
10963 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10965 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10966 (progn
10967 (when (bufferp f)
10968 (setq f (buffer-file-name (buffer-base-buffer f))))
10969 (setq f (and f (expand-file-name f)))
10970 (when (eq org-refile-use-outline-path 'file)
10971 (push (list (file-name-nondirectory f) f nil nil) tgs))
10972 (when (eq org-refile-use-outline-path 'buffer-name)
10973 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10974 (when (eq org-refile-use-outline-path 'full-file-path)
10975 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10976 (org-with-wide-buffer
10977 (goto-char (point-min))
10978 (setq org-outline-path-cache nil)
10979 (while (re-search-forward descre nil t)
10980 (beginning-of-line)
10981 (let ((case-fold-search nil))
10982 (looking-at org-complex-heading-regexp))
10983 (let ((begin (point))
10984 (heading (match-string-no-properties 4)))
10985 (unless (or (and
10986 org-refile-target-verify-function
10987 (not
10988 (funcall org-refile-target-verify-function)))
10989 (not heading))
10990 (let ((re (format org-complex-heading-regexp-format
10991 (regexp-quote heading)))
10992 (target
10993 (if (not org-refile-use-outline-path) heading
10994 (mapconcat
10995 #'identity
10996 (append
10997 (pcase org-refile-use-outline-path
10998 (`file (list (file-name-nondirectory
10999 (buffer-file-name
11000 (buffer-base-buffer)))))
11001 (`full-file-path
11002 (list (buffer-file-name
11003 (buffer-base-buffer))))
11004 (`buffer-name
11005 (list (buffer-name
11006 (buffer-base-buffer))))
11007 (_ nil))
11008 (mapcar (lambda (s) (replace-regexp-in-string
11009 "/" "\\/" s nil t))
11010 (org-get-outline-path t t)))
11011 "/"))))
11012 (push (list target f re (org-refile-marker (point)))
11013 tgs)))
11014 (when (= (point) begin)
11015 ;; Verification function has not moved point.
11016 (end-of-line)))))))
11017 (when org-refile-use-cache
11018 (org-refile-cache-put tgs (buffer-file-name) descre))
11019 (setq targets (append tgs targets))))))
11020 (message "Getting targets...done")
11021 (delete-dups (nreverse targets))))
11023 (defun org--get-outline-path-1 (&optional use-cache)
11024 "Return outline path to current headline.
11026 Outline path is a list of strings, in reverse order. When
11027 optional argument USE-CACHE is non-nil, make use of a cache. See
11028 `org-get-outline-path' for details.
11030 Assume buffer is widened and point is on a headline."
11031 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11032 (let ((p (point))
11033 (heading (let ((case-fold-search nil))
11034 (looking-at org-complex-heading-regexp)
11035 (if (not (match-end 4)) ""
11036 ;; Remove statistics cookies.
11037 (org-trim
11038 (org-link-display-format
11039 (replace-regexp-in-string
11040 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11041 (match-string-no-properties 4))))))))
11042 (if (org-up-heading-safe)
11043 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11044 (when use-cache
11045 (push (cons p path) org-outline-path-cache))
11046 path)
11047 ;; This is a new root node. Since we assume we are moving
11048 ;; forward, we can drop previous cache so as to limit number
11049 ;; of associations there.
11050 (let ((path (list heading)))
11051 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11052 path)))))
11054 (defun org-get-outline-path (&optional with-self use-cache)
11055 "Return the outline path to the current entry.
11057 An outline path is a list of ancestors for current headline, as
11058 a list of strings. Statistics cookies are removed and links are
11059 replaced with their description, if any, or their path otherwise.
11061 When optional argument WITH-SELF is non-nil, the path also
11062 includes the current headline.
11064 When optional argument USE-CACHE is non-nil, cache outline paths
11065 between calls to this function so as to avoid backtracking. This
11066 argument is useful when planning to find more than one outline
11067 path in the same document. In that case, there are two
11068 conditions to satisfy:
11069 - `org-outline-path-cache' is set to nil before starting the
11070 process;
11071 - outline paths are computed by increasing buffer positions."
11072 (org-with-wide-buffer
11073 (and (or (and with-self (org-back-to-heading t))
11074 (org-up-heading-safe))
11075 (reverse (org--get-outline-path-1 use-cache)))))
11077 (defun org-format-outline-path (path &optional width prefix separator)
11078 "Format the outline path PATH for display.
11079 WIDTH is the maximum number of characters that is available.
11080 PREFIX is a prefix to be included in the returned string,
11081 such as the file name.
11082 SEPARATOR is inserted between the different parts of the path,
11083 the default is \"/\"."
11084 (setq width (or width 79))
11085 (setq path (delq nil path))
11086 (unless (> width 0)
11087 (user-error "Argument `width' must be positive"))
11088 (setq separator (or separator "/"))
11089 (let* ((org-odd-levels-only nil)
11090 (fpath (concat
11091 prefix (and prefix path separator)
11092 (mapconcat
11093 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11094 (cl-loop for head in path
11095 for n from 0
11096 collect (org-add-props
11097 head nil 'face
11098 (nth (% n org-n-level-faces) org-level-faces)))
11099 separator))))
11100 (when (> (length fpath) width)
11101 (if (< width 7)
11102 ;; It's unlikely that `width' will be this small, but don't
11103 ;; waste characters by adding ".." if it is.
11104 (setq fpath (substring fpath 0 width))
11105 (setf (substring fpath (- width 2)) "..")))
11106 fpath))
11108 (defun org-display-outline-path (&optional file current separator just-return-string)
11109 "Display the current outline path in the echo area.
11111 If FILE is non-nil, prepend the output with the file name.
11112 If CURRENT is non-nil, append the current heading to the output.
11113 SEPARATOR is passed through to `org-format-outline-path'. It separates
11114 the different parts of the path and defaults to \"/\".
11115 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11116 (interactive "P")
11117 (let* (case-fold-search
11118 (bfn (buffer-file-name (buffer-base-buffer)))
11119 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11120 res)
11121 (when current (setq path (append path
11122 (save-excursion
11123 (org-back-to-heading t)
11124 (when (looking-at org-complex-heading-regexp)
11125 (list (match-string 4)))))))
11126 (setq res
11127 (org-format-outline-path
11128 path
11129 (1- (frame-width))
11130 (and file bfn (concat (file-name-nondirectory bfn) separator))
11131 separator))
11132 (if just-return-string
11133 (org-no-properties res)
11134 (org-unlogged-message "%s" res))))
11136 (defvar org-refile-history nil
11137 "History for refiling operations.")
11139 (defvar org-after-refile-insert-hook nil
11140 "Hook run after `org-refile' has inserted its stuff at the new location.
11141 Note that this is still *before* the stuff will be removed from
11142 the *old* location.")
11144 (defvar org-capture-last-stored-marker)
11145 (defvar org-refile-keep nil
11146 "Non-nil means `org-refile' will copy instead of refile.")
11148 (defun org-copy ()
11149 "Like `org-refile', but copy."
11150 (interactive)
11151 (let ((org-refile-keep t))
11152 (funcall 'org-refile nil nil nil "Copy")))
11154 (defun org-refile (&optional arg default-buffer rfloc msg)
11155 "Move the entry or entries at point to another heading.
11157 The list of target headings is compiled using the information in
11158 `org-refile-targets', which see.
11160 At the target location, the entry is filed as a subitem of the
11161 target heading. Depending on `org-reverse-note-order', the new
11162 subitem will either be the first or the last subitem.
11164 If there is an active region, all entries in that region will be
11165 refiled. However, the region must fulfill the requirement that
11166 the first heading sets the top-level of the moved text.
11168 With a `\\[universal-argument]' ARG, the command will only visit the target \
11169 location
11170 and not actually move anything.
11172 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11173 location where the last
11174 refiling operation has put the subtree.
11176 With a numeric prefix argument of `2', refile to the running clock.
11178 With a numeric prefix argument of `3', emulate `org-refile-keep'
11179 being set to t and copy to the target location, don't move it.
11180 Beware that keeping refiled entries may result in duplicated ID
11181 properties.
11183 RFLOC can be a refile location obtained in a different way.
11185 MSG is a string to replace \"Refile\" in the default prompt with
11186 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11188 See also `org-refile-use-outline-path'.
11190 If you are using target caching (see `org-refile-use-cache'), you
11191 have to clear the target cache in order to find new targets.
11192 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11193 prefix argument (`C-u C-u C-u C-c C-w')."
11194 (interactive "P")
11195 (if (member arg '(0 (64)))
11196 (org-refile-cache-clear)
11197 (let* ((actionmsg (cond (msg msg)
11198 ((equal arg 3) "Refile (and keep)")
11199 (t "Refile")))
11200 (regionp (org-region-active-p))
11201 (region-start (and regionp (region-beginning)))
11202 (region-end (and regionp (region-end)))
11203 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11204 pos it nbuf file level reversed)
11205 (setq last-command nil)
11206 (when regionp
11207 (goto-char region-start)
11208 (or (bolp) (goto-char (point-at-bol)))
11209 (setq region-start (point))
11210 (unless (or (org-kill-is-subtree-p
11211 (buffer-substring region-start region-end))
11212 (prog1 org-refile-active-region-within-subtree
11213 (let ((s (point-at-eol)))
11214 (org-toggle-heading)
11215 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11216 (user-error "The region is not a (sequence of) subtree(s)")))
11217 (if (equal arg '(16))
11218 (org-refile-goto-last-stored)
11219 (when (or
11220 (and (equal arg 2)
11221 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11222 (prog1
11223 (setq it (list (or org-clock-heading "running clock")
11224 (buffer-file-name
11225 (marker-buffer org-clock-hd-marker))
11227 (marker-position org-clock-hd-marker)))
11228 (setq arg nil)))
11229 (setq it
11230 (or rfloc
11231 (let (heading-text)
11232 (save-excursion
11233 (unless (and arg (listp arg))
11234 (org-back-to-heading t)
11235 (setq heading-text
11236 (replace-regexp-in-string
11237 org-bracket-link-regexp
11238 "\\3"
11239 (or (nth 4 (org-heading-components))
11240 ""))))
11241 (org-refile-get-location
11242 (cond ((and arg (listp arg)) "Goto")
11243 (regionp (concat actionmsg " region to"))
11244 (t (concat actionmsg " subtree \""
11245 heading-text "\" to")))
11246 default-buffer
11247 (and (not (equal '(4) arg))
11248 org-refile-allow-creating-parent-nodes)))))))
11249 (setq file (nth 1 it)
11250 pos (nth 3 it))
11251 (when (and (not arg)
11253 (equal (buffer-file-name) file)
11254 (if regionp
11255 (and (>= pos region-start)
11256 (<= pos region-end))
11257 (and (>= pos (point))
11258 (< pos (save-excursion
11259 (org-end-of-subtree t t))))))
11260 (error "Cannot refile to position inside the tree or region"))
11261 (setq nbuf (or (find-buffer-visiting file)
11262 (find-file-noselect file)))
11263 (if (and arg (not (equal arg 3)))
11264 (progn
11265 (pop-to-buffer-same-window nbuf)
11266 (goto-char (cond (pos)
11267 ((org-notes-order-reversed-p) (point-min))
11268 (t (point-max))))
11269 (org-show-context 'org-goto))
11270 (if regionp
11271 (progn
11272 (org-kill-new (buffer-substring region-start region-end))
11273 (org-save-markers-in-region region-start region-end))
11274 (org-copy-subtree 1 nil t))
11275 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11276 (find-file-noselect file)))
11277 (setq reversed (org-notes-order-reversed-p))
11278 (org-with-wide-buffer
11279 (if pos
11280 (progn
11281 (goto-char pos)
11282 (setq level (org-get-valid-level (funcall outline-level) 1))
11283 (goto-char
11284 (if reversed
11285 (or (outline-next-heading) (point-max))
11286 (or (save-excursion (org-get-next-sibling))
11287 (org-end-of-subtree t t)
11288 (point-max)))))
11289 (setq level 1)
11290 (if (not reversed)
11291 (goto-char (point-max))
11292 (goto-char (point-min))
11293 (or (outline-next-heading) (goto-char (point-max)))))
11294 (unless (bolp) (newline))
11295 (org-paste-subtree level nil nil t)
11296 (when org-log-refile
11297 (org-add-log-setup 'refile nil nil org-log-refile)
11298 (unless (eq org-log-refile 'note)
11299 (save-excursion (org-add-log-note))))
11300 (and org-auto-align-tags
11301 (let ((org-loop-over-headlines-in-active-region nil))
11302 (org-set-tags nil t)))
11303 (let ((bookmark-name (plist-get org-bookmark-names-plist
11304 :last-refile)))
11305 (when bookmark-name
11306 (with-demoted-errors
11307 (bookmark-set bookmark-name))))
11308 ;; If we are refiling for capture, make sure that the
11309 ;; last-capture pointers point here
11310 (when (bound-and-true-p org-capture-is-refiling)
11311 (let ((bookmark-name (plist-get org-bookmark-names-plist
11312 :last-capture-marker)))
11313 (when bookmark-name
11314 (with-demoted-errors
11315 (bookmark-set bookmark-name))))
11316 (move-marker org-capture-last-stored-marker (point)))
11317 (when (fboundp 'deactivate-mark) (deactivate-mark))
11318 (run-hooks 'org-after-refile-insert-hook)))
11319 (unless org-refile-keep
11320 (if regionp
11321 (delete-region (point) (+ (point) (- region-end region-start)))
11322 (org-preserve-local-variables
11323 (delete-region
11324 (and (org-back-to-heading t) (point))
11325 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11326 (when (featurep 'org-inlinetask)
11327 (org-inlinetask-remove-END-maybe))
11328 (setq org-markers-to-move nil)
11329 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11331 (defun org-refile-goto-last-stored ()
11332 "Go to the location where the last refile was stored."
11333 (interactive)
11334 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11335 (message "This is the location of the last refile"))
11337 (defun org-refile--get-location (refloc tbl)
11338 "When user refile to REFLOC, find the associated target in TBL.
11339 Also check `org-refile-target-table'."
11340 (car (delq
11342 (mapcar
11343 (lambda (r) (or (assoc r tbl)
11344 (assoc r org-refile-target-table)))
11345 (list (replace-regexp-in-string "/$" "" refloc)
11346 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11348 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11349 "Prompt the user for a refile location, using PROMPT.
11350 PROMPT should not be suffixed with a colon and a space, because
11351 this function appends the default value from
11352 `org-refile-history' automatically, if that is not empty."
11353 (let ((org-refile-targets org-refile-targets)
11354 (org-refile-use-outline-path org-refile-use-outline-path))
11355 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11356 (unless org-refile-target-table
11357 (user-error "No refile targets"))
11358 (let* ((cbuf (current-buffer))
11359 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11360 (cfunc (if (and org-refile-use-outline-path
11361 org-outline-path-complete-in-steps)
11362 #'org-olpath-completing-read
11363 #'completing-read))
11364 (extra (if org-refile-use-outline-path "/" ""))
11365 (cbnex (concat (buffer-name) extra))
11366 (filename (and cfn (expand-file-name cfn)))
11367 (tbl (mapcar
11368 (lambda (x)
11369 (if (and (not (member org-refile-use-outline-path
11370 '(file full-file-path)))
11371 (not (equal filename (nth 1 x))))
11372 (cons (concat (car x) extra " ("
11373 (file-name-nondirectory (nth 1 x)) ")")
11374 (cdr x))
11375 (cons (concat (car x) extra) (cdr x))))
11376 org-refile-target-table))
11377 (completion-ignore-case t)
11378 cdef
11379 (prompt (concat prompt
11380 (or (and (car org-refile-history)
11381 (concat " (default " (car org-refile-history) ")"))
11382 (and (assoc cbnex tbl) (setq cdef cbnex)
11383 (concat " (default " cbnex ")"))) ": "))
11384 pa answ parent-target child parent old-hist)
11385 (setq old-hist org-refile-history)
11386 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11387 nil 'org-refile-history (or cdef (car org-refile-history))))
11388 (if (setq pa (org-refile--get-location answ tbl))
11389 (progn
11390 (org-refile-check-position pa)
11391 (when (or (not org-refile-history)
11392 (not (eq old-hist org-refile-history))
11393 (not (equal (car pa) (car org-refile-history))))
11394 (setq org-refile-history
11395 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11396 org-refile-history
11397 (cdr org-refile-history))))
11398 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11399 (pop org-refile-history)))
11401 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11402 (progn
11403 (setq parent (match-string 1 answ)
11404 child (match-string 2 answ))
11405 (setq parent-target (org-refile--get-location parent tbl))
11406 (when (and parent-target
11407 (or (eq new-nodes t)
11408 (and (eq new-nodes 'confirm)
11409 (y-or-n-p (format "Create new node \"%s\"? "
11410 child)))))
11411 (org-refile-new-child parent-target child)))
11412 (user-error "Invalid target location")))))
11414 (declare-function org-string-nw-p "org-macs" (s))
11415 (defun org-refile-check-position (refile-pointer)
11416 "Check if the refile pointer matches the headline to which it points."
11417 (let* ((file (nth 1 refile-pointer))
11418 (re (nth 2 refile-pointer))
11419 (pos (nth 3 refile-pointer))
11420 buffer)
11421 (if (and (not (markerp pos)) (not file))
11422 (user-error "Please indicate a target file in the refile path")
11423 (when (org-string-nw-p re)
11424 (setq buffer (if (markerp pos)
11425 (marker-buffer pos)
11426 (or (find-buffer-visiting file)
11427 (find-file-noselect file))))
11428 (with-current-buffer buffer
11429 (org-with-wide-buffer
11430 (goto-char pos)
11431 (beginning-of-line 1)
11432 (unless (looking-at-p re)
11433 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11435 (defun org-refile-new-child (parent-target child)
11436 "Use refile target PARENT-TARGET to add new CHILD below it."
11437 (unless parent-target
11438 (error "Cannot find parent for new node"))
11439 (let ((file (nth 1 parent-target))
11440 (pos (nth 3 parent-target))
11441 level)
11442 (with-current-buffer (or (find-buffer-visiting file)
11443 (find-file-noselect file))
11444 (org-with-wide-buffer
11445 (if pos
11446 (goto-char pos)
11447 (goto-char (point-max))
11448 (unless (bolp) (newline)))
11449 (when (looking-at org-outline-regexp)
11450 (setq level (funcall outline-level))
11451 (org-end-of-subtree t t))
11452 (org-back-over-empty-lines)
11453 (insert "\n" (make-string
11454 (if pos (org-get-valid-level level 1) 1) ?*)
11455 " " child "\n")
11456 (beginning-of-line 0)
11457 (list (concat (car parent-target) "/" child) file "" (point))))))
11459 (defun org-olpath-completing-read (prompt collection &rest args)
11460 "Read an outline path like a file name."
11461 (let ((thetable collection))
11462 (apply #'completing-read
11463 prompt
11464 (lambda (string predicate &optional flag)
11465 (cond
11466 ((eq flag nil) (try-completion string thetable))
11467 ((eq flag t)
11468 (let ((l (length string)))
11469 (mapcar (lambda (x)
11470 (let ((r (substring x l))
11471 (f (if (string-match " ([^)]*)$" x)
11472 (match-string 0 x)
11473 "")))
11474 (if (string-match "/" r)
11475 (concat string (substring r 0 (match-end 0)) f)
11476 x)))
11477 (all-completions string thetable predicate))))
11478 ;; Exact match?
11479 ((eq flag 'lambda) (assoc string thetable))))
11480 args)))
11482 ;;;; Dynamic blocks
11484 (defun org-find-dblock (name)
11485 "Find the first dynamic block with name NAME in the buffer.
11486 If not found, stay at current position and return nil."
11487 (let ((case-fold-search t) pos)
11488 (save-excursion
11489 (goto-char (point-min))
11490 (setq pos (and (re-search-forward
11491 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11492 (match-beginning 0))))
11493 (when pos (goto-char pos))
11494 pos))
11496 (defun org-create-dblock (plist)
11497 "Create a dynamic block section, with parameters taken from PLIST.
11498 PLIST must contain a :name entry which is used as the name of the block."
11499 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11500 (end-of-line 1)
11501 (newline))
11502 (let ((col (current-column))
11503 (name (plist-get plist :name)))
11504 (insert "#+BEGIN: " name)
11505 (while plist
11506 (if (eq (car plist) :name)
11507 (setq plist (cddr plist))
11508 (insert " " (prin1-to-string (pop plist)))))
11509 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11510 (beginning-of-line -2)))
11512 (defun org-prepare-dblock ()
11513 "Prepare dynamic block for refresh.
11514 This empties the block, puts the cursor at the insert position and returns
11515 the property list including an extra property :name with the block name."
11516 (unless (looking-at org-dblock-start-re)
11517 (user-error "Not at a dynamic block"))
11518 (let* ((begdel (1+ (match-end 0)))
11519 (name (org-no-properties (match-string 1)))
11520 (params (append (list :name name)
11521 (read (concat "(" (match-string 3) ")")))))
11522 (save-excursion
11523 (beginning-of-line 1)
11524 (skip-chars-forward " \t")
11525 (setq params (plist-put params :indentation-column (current-column))))
11526 (unless (re-search-forward org-dblock-end-re nil t)
11527 (error "Dynamic block not terminated"))
11528 (setq params
11529 (append params
11530 (list :content (buffer-substring
11531 begdel (match-beginning 0)))))
11532 (delete-region begdel (match-beginning 0))
11533 (goto-char begdel)
11534 (open-line 1)
11535 params))
11537 (defun org-map-dblocks (&optional command)
11538 "Apply COMMAND to all dynamic blocks in the current buffer.
11539 If COMMAND is not given, use `org-update-dblock'."
11540 (let ((cmd (or command 'org-update-dblock)))
11541 (save-excursion
11542 (goto-char (point-min))
11543 (while (re-search-forward org-dblock-start-re nil t)
11544 (goto-char (match-beginning 0))
11545 (save-excursion
11546 (condition-case nil
11547 (funcall cmd)
11548 (error (message "Error during update of dynamic block"))))
11549 (unless (re-search-forward org-dblock-end-re nil t)
11550 (error "Dynamic block not terminated"))))))
11552 (defun org-dblock-update (&optional arg)
11553 "User command for updating dynamic blocks.
11554 Update the dynamic block at point. With prefix ARG, update all dynamic
11555 blocks in the buffer."
11556 (interactive "P")
11557 (if arg
11558 (org-update-all-dblocks)
11559 (or (looking-at org-dblock-start-re)
11560 (org-beginning-of-dblock))
11561 (org-update-dblock)))
11563 (defun org-update-dblock ()
11564 "Update the dynamic block at point.
11565 This means to empty the block, parse for parameters and then call
11566 the correct writing function."
11567 (interactive)
11568 (save-excursion
11569 (let* ((win (selected-window))
11570 (pos (point))
11571 (line (org-current-line))
11572 (params (org-prepare-dblock))
11573 (name (plist-get params :name))
11574 (indent (plist-get params :indentation-column))
11575 (cmd (intern (concat "org-dblock-write:" name))))
11576 (message "Updating dynamic block `%s' at line %d..." name line)
11577 (funcall cmd params)
11578 (message "Updating dynamic block `%s' at line %d...done" name line)
11579 (goto-char pos)
11580 (when (and indent (> indent 0))
11581 (setq indent (make-string indent ?\ ))
11582 (save-excursion
11583 (select-window win)
11584 (org-beginning-of-dblock)
11585 (forward-line 1)
11586 (while (not (looking-at org-dblock-end-re))
11587 (insert indent)
11588 (beginning-of-line 2))
11589 (when (looking-at org-dblock-end-re)
11590 (and (looking-at "[ \t]+")
11591 (replace-match ""))
11592 (insert indent)))))))
11594 (defun org-beginning-of-dblock ()
11595 "Find the beginning of the dynamic block at point.
11596 Error if there is no such block at point."
11597 (let ((pos (point))
11598 beg)
11599 (end-of-line 1)
11600 (if (and (re-search-backward org-dblock-start-re nil t)
11601 (setq beg (match-beginning 0))
11602 (re-search-forward org-dblock-end-re nil t)
11603 (> (match-end 0) pos))
11604 (goto-char beg)
11605 (goto-char pos)
11606 (error "Not in a dynamic block"))))
11608 (defun org-update-all-dblocks ()
11609 "Update all dynamic blocks in the buffer.
11610 This function can be used in a hook."
11611 (interactive)
11612 (when (derived-mode-p 'org-mode)
11613 (org-map-dblocks 'org-update-dblock)))
11616 ;;;; Completion
11618 (declare-function org-export-backend-options "ox" (cl-x) t)
11619 (defun org-get-export-keywords ()
11620 "Return a list of all currently understood export keywords.
11621 Export keywords include options, block names, attributes and
11622 keywords relative to each registered export back-end."
11623 (let (keywords)
11624 (dolist (backend
11625 (bound-and-true-p org-export-registered-backends)
11626 (delq nil keywords))
11627 ;; Back-end name (for keywords, like #+LATEX:)
11628 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11629 (dolist (option-entry (org-export-backend-options backend))
11630 ;; Back-end options.
11631 (push (nth 1 option-entry) keywords)))))
11633 (defconst org-options-keywords
11634 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11635 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11636 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11637 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11638 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11640 (defcustom org-structure-template-alist
11641 '((?a . "export ascii")
11642 (?c . "center")
11643 (?C . "comment")
11644 (?e . "example")
11645 (?E . "export")
11646 (?h . "export html")
11647 (?l . "export latex")
11648 (?q . "quote")
11649 (?s . "src")
11650 (?v . "verse"))
11651 "Structure completion elements.
11652 This is an alist of characters and values. When
11653 `org-insert-structure-template' is called, an additional key is
11654 read. The key is first looked up in this alist, and the
11655 corresponding structure is inserted, with \"#+BEGIN_\" and
11656 \"#+END_\" added automatically."
11657 :group 'org-edit-structure
11658 :type '(repeat
11659 (cons (character :tag "Key")
11660 (string :tag "Template")))
11661 :package-version '(Org . "9.2"))
11663 (defun org-insert-structure-template (type)
11664 "Insert a block structure of the type #+begin_foo/#+end_foo.
11665 First read a character, which can be one of the keys in
11666 `org-structure-template-alist'. When it is <TAB>, prompt the
11667 user for a string to use. With an active region, wrap the region
11668 in the block. Otherwise, insert an empty block."
11669 (interactive
11670 (list
11671 (let* ((key (read-key "Key: "))
11672 (struct-string
11673 (or (cdr (assq key org-structure-template-alist))
11674 (and (= key ?\t)
11675 (read-string "Structure type: "))
11676 (user-error "`%c' has no structure definition" key))))
11677 struct-string)))
11678 (let* ((region? (use-region-p))
11679 (s (if region? (region-beginning) (point)))
11680 (e (copy-marker (if region? (region-end) (point)) t))
11681 column)
11682 (when (string-match-p
11683 (concat "\\`" (regexp-opt '("example" "export" "src")))
11684 type)
11685 (org-escape-code-in-region s e))
11686 (goto-char s)
11687 (setq column (current-indentation))
11688 (beginning-of-line)
11689 (indent-to column)
11690 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11691 (goto-char e)
11692 (if (bolp)
11693 (progn
11694 (skip-chars-backward " \n\t")
11695 (forward-line))
11696 (end-of-line)
11697 (insert "\n"))
11698 (indent-to column)
11699 (insert (format "#+end_%s\n"
11700 (car (split-string type))))
11701 (when (or (not region?)
11702 (string-match-p "src\\|\\`export\\'" type))
11703 (goto-char s)
11704 (end-of-line))
11705 (set-marker e nil)))
11707 ;;;; TODO, DEADLINE, Comments
11709 (defun org-toggle-comment ()
11710 "Change the COMMENT state of an entry."
11711 (interactive)
11712 (save-excursion
11713 (org-back-to-heading)
11714 (let ((case-fold-search nil))
11715 (looking-at org-complex-heading-regexp))
11716 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11717 (skip-chars-forward " \t")
11718 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11719 (if (org-in-commented-heading-p t)
11720 (delete-region (point)
11721 (progn (search-forward " " (line-end-position) 'move)
11722 (skip-chars-forward " \t")
11723 (point)))
11724 (insert org-comment-string)
11725 (unless (eolp) (insert " ")))))
11727 (defvar org-last-todo-state-is-todo nil
11728 "This is non-nil when the last TODO state change led to a TODO state.
11729 If the last change removed the TODO tag or switched to DONE, then
11730 this is nil.")
11732 (defvar org-setting-tags nil) ; dynamically skipped
11734 (defvar org-todo-setup-filter-hook nil
11735 "Hook for functions that pre-filter todo specs.
11736 Each function takes a todo spec and returns either nil or the spec
11737 transformed into canonical form." )
11739 (defvar org-todo-get-default-hook nil
11740 "Hook for functions that get a default item for todo.
11741 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11742 nil or a string to be used for the todo mark." )
11744 (defvar org-agenda-headline-snapshot-before-repeat)
11746 (defun org-current-effective-time ()
11747 "Return current time adjusted for `org-extend-today-until' variable."
11748 (let* ((ct (org-current-time))
11749 (dct (decode-time ct))
11750 (ct1
11751 (cond
11752 (org-use-last-clock-out-time-as-effective-time
11753 (or (org-clock-get-last-clock-out-time) ct))
11754 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11755 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11756 (t ct))))
11757 ct1))
11759 (defun org-todo-yesterday (&optional arg)
11760 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11761 (interactive "P")
11762 (if (eq major-mode 'org-agenda-mode)
11763 (apply 'org-agenda-todo-yesterday arg)
11764 (let* ((org-use-effective-time t)
11765 (hour (nth 2 (decode-time (org-current-time))))
11766 (org-extend-today-until (1+ hour)))
11767 (org-todo arg))))
11769 (defvar org-block-entry-blocking ""
11770 "First entry preventing the TODO state change.")
11772 (defun org-cancel-repeater ()
11773 "Cancel a repeater by setting its numeric value to zero."
11774 (interactive)
11775 (save-excursion
11776 (org-back-to-heading t)
11777 (let ((bound1 (point))
11778 (bound0 (save-excursion (outline-next-heading) (point))))
11779 (when (and (re-search-forward
11780 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11781 org-deadline-time-regexp "\\)\\|\\("
11782 org-ts-regexp "\\)")
11783 bound0 t)
11784 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11785 bound1 t))
11786 (replace-match "0" t nil nil 1)))))
11788 (defvar org-state)
11789 (defvar org-blocked-by-checkboxes)
11790 (defun org-todo (&optional arg)
11791 "Change the TODO state of an item.
11793 The state of an item is given by a keyword at the start of the heading,
11794 like
11795 *** TODO Write paper
11796 *** DONE Call mom
11798 The different keywords are specified in the variable `org-todo-keywords'.
11799 By default the available states are \"TODO\" and \"DONE\". So, for this
11800 example: when the item starts with TODO, it is changed to DONE.
11801 When it starts with DONE, the DONE is removed. And when neither TODO nor
11802 DONE are present, add TODO at the beginning of the heading.
11804 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11805 state.
11806 With numeric prefix ARG, switch to that state.
11807 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11808 next set of TODO \
11809 keywords (nextset).
11810 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11811 prefix, circumvent any state blocking.
11812 With a numeric prefix arg of 0, inhibit note taking for the change.
11813 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11815 When called through ELisp, arg is also interpreted in the following way:
11816 `none' -> empty state
11817 \"\" -> switch to empty state
11818 `done' -> switch to DONE
11819 `nextset' -> switch to the next set of keywords
11820 `previousset' -> switch to the previous set of keywords
11821 \"WAITING\" -> switch to the specified keyword, but only if it
11822 really is a member of `org-todo-keywords'."
11823 (interactive "P")
11824 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11825 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11826 'region-start-level 'region))
11827 org-loop-over-headlines-in-active-region)
11828 (org-map-entries
11829 `(org-todo ,arg)
11830 org-loop-over-headlines-in-active-region
11831 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11832 (when (equal arg '(16)) (setq arg 'nextset))
11833 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11834 (let ((org-blocker-hook org-blocker-hook)
11835 commentp
11836 case-fold-search)
11837 (when (equal arg '(64))
11838 (setq arg nil org-blocker-hook nil))
11839 (when (and org-blocker-hook
11840 (or org-inhibit-blocking
11841 (org-entry-get nil "NOBLOCKING")))
11842 (setq org-blocker-hook nil))
11843 (save-excursion
11844 (catch 'exit
11845 (org-back-to-heading t)
11846 (when (org-in-commented-heading-p t)
11847 (org-toggle-comment)
11848 (setq commentp t))
11849 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11850 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11851 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11852 (let* ((match-data (match-data))
11853 (startpos (copy-marker (line-beginning-position)))
11854 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11855 (org-log-done org-log-done)
11856 (org-log-repeat org-log-repeat)
11857 (org-todo-log-states org-todo-log-states)
11858 (org-inhibit-logging
11859 (if (equal arg 0)
11860 (progn (setq arg nil) 'note) org-inhibit-logging))
11861 (this (match-string 1))
11862 (hl-pos (match-beginning 0))
11863 (head (org-get-todo-sequence-head this))
11864 (ass (assoc head org-todo-kwd-alist))
11865 (interpret (nth 1 ass))
11866 (done-word (nth 3 ass))
11867 (final-done-word (nth 4 ass))
11868 (org-last-state (or this ""))
11869 (completion-ignore-case t)
11870 (member (member this org-todo-keywords-1))
11871 (tail (cdr member))
11872 (org-state (cond
11873 ((and org-todo-key-trigger
11874 (or (and (equal arg '(4))
11875 (eq org-use-fast-todo-selection 'prefix))
11876 (and (not arg) org-use-fast-todo-selection
11877 (not (eq org-use-fast-todo-selection
11878 'prefix)))))
11879 ;; Use fast selection.
11880 (org-fast-todo-selection))
11881 ((and (equal arg '(4))
11882 (or (not org-use-fast-todo-selection)
11883 (not org-todo-key-trigger)))
11884 ;; Read a state with completion.
11885 (completing-read
11886 "State: " (mapcar #'list org-todo-keywords-1)
11887 nil t))
11888 ((eq arg 'right)
11889 (if this
11890 (if tail (car tail) nil)
11891 (car org-todo-keywords-1)))
11892 ((eq arg 'left)
11893 (unless (equal member org-todo-keywords-1)
11894 (if this
11895 (nth (- (length org-todo-keywords-1)
11896 (length tail) 2)
11897 org-todo-keywords-1)
11898 (org-last org-todo-keywords-1))))
11899 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11900 (setq arg nil))) ;hack to fall back to cycling
11901 (arg
11902 ;; User or caller requests a specific state.
11903 (cond
11904 ((equal arg "") nil)
11905 ((eq arg 'none) nil)
11906 ((eq arg 'done) (or done-word (car org-done-keywords)))
11907 ((eq arg 'nextset)
11908 (or (car (cdr (member head org-todo-heads)))
11909 (car org-todo-heads)))
11910 ((eq arg 'previousset)
11911 (let ((org-todo-heads (reverse org-todo-heads)))
11912 (or (car (cdr (member head org-todo-heads)))
11913 (car org-todo-heads))))
11914 ((car (member arg org-todo-keywords-1)))
11915 ((stringp arg)
11916 (user-error "State `%s' not valid in this file" arg))
11917 ((nth (1- (prefix-numeric-value arg))
11918 org-todo-keywords-1))))
11919 ((null member) (or head (car org-todo-keywords-1)))
11920 ((equal this final-done-word) nil) ;-> make empty
11921 ((null tail) nil) ;-> first entry
11922 ((memq interpret '(type priority))
11923 (if (eq this-command last-command)
11924 (car tail)
11925 (if (> (length tail) 0)
11926 (or done-word (car org-done-keywords))
11927 nil)))
11929 (car tail))))
11930 (org-state (or
11931 (run-hook-with-args-until-success
11932 'org-todo-get-default-hook org-state org-last-state)
11933 org-state))
11934 (next (if org-state (concat " " org-state " ") " "))
11935 (change-plist (list :type 'todo-state-change :from this :to org-state
11936 :position startpos))
11937 dolog now-done-p)
11938 (when org-blocker-hook
11939 (let (org-blocked-by-checkboxes block-reason)
11940 (setq org-last-todo-state-is-todo
11941 (not (member this org-done-keywords)))
11942 (unless (save-excursion
11943 (save-match-data
11944 (org-with-wide-buffer
11945 (run-hook-with-args-until-failure
11946 'org-blocker-hook change-plist))))
11947 (setq block-reason (if org-blocked-by-checkboxes
11948 "contained checkboxes"
11949 (format "\"%s\"" org-block-entry-blocking)))
11950 (if (called-interactively-p 'interactive)
11951 (user-error "TODO state change from %s to %s blocked (by %s)"
11952 this org-state block-reason)
11953 ;; Fail silently.
11954 (message "TODO state change from %s to %s blocked (by %s)"
11955 this org-state block-reason)
11956 (throw 'exit nil)))))
11957 (store-match-data match-data)
11958 (replace-match next t t)
11959 (cond ((equal this org-state)
11960 (message "TODO state was already %s" (org-trim next)))
11961 ((not (pos-visible-in-window-p hl-pos))
11962 (message "TODO state changed to %s" (org-trim next))))
11963 (unless head
11964 (setq head (org-get-todo-sequence-head org-state)
11965 ass (assoc head org-todo-kwd-alist)
11966 interpret (nth 1 ass)
11967 done-word (nth 3 ass)
11968 final-done-word (nth 4 ass)))
11969 (when (memq arg '(nextset previousset))
11970 (message "Keyword-Set %d/%d: %s"
11971 (- (length org-todo-sets) -1
11972 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11973 (length org-todo-sets)
11974 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11975 (setq org-last-todo-state-is-todo
11976 (not (member org-state org-done-keywords)))
11977 (setq now-done-p (and (member org-state org-done-keywords)
11978 (not (member this org-done-keywords))))
11979 (and logging (org-local-logging logging))
11980 (when (and (or org-todo-log-states org-log-done)
11981 (not (eq org-inhibit-logging t))
11982 (not (memq arg '(nextset previousset))))
11983 ;; We need to look at recording a time and note.
11984 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11985 (nth 2 (assoc this org-todo-log-states))))
11986 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11987 (setq dolog 'time))
11988 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
11989 (and org-state
11990 (member org-state org-not-done-keywords)
11991 (not (member this org-not-done-keywords))))
11992 ;; This is now a todo state and was not one before
11993 ;; If there was a CLOSED time stamp, get rid of it.
11994 (org-add-planning-info nil nil 'closed))
11995 (when (and now-done-p org-log-done)
11996 ;; It is now done, and it was not done before.
11997 (org-add-planning-info 'closed (org-current-effective-time))
11998 (when (and (not dolog) (eq 'note org-log-done))
11999 (org-add-log-setup 'done org-state this 'note)))
12000 (when (and org-state dolog)
12001 ;; This is a non-nil state, and we need to log it.
12002 (org-add-log-setup 'state org-state this dolog)))
12003 ;; Fixup tag positioning.
12004 (org-todo-trigger-tag-changes org-state)
12005 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12006 (when org-provide-todo-statistics
12007 (org-update-parent-todo-statistics))
12008 (run-hooks 'org-after-todo-state-change-hook)
12009 (when (and arg (not (member org-state org-done-keywords)))
12010 (setq head (org-get-todo-sequence-head org-state)))
12011 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12012 ;; Do we need to trigger a repeat?
12013 (when now-done-p
12014 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12015 ;; This is for the agenda, take a snapshot of the headline.
12016 (save-match-data
12017 (setq org-agenda-headline-snapshot-before-repeat
12018 (org-get-heading))))
12019 (org-auto-repeat-maybe org-state))
12020 ;; Fixup cursor location if close to the keyword.
12021 (when (and (outline-on-heading-p)
12022 (not (bolp))
12023 (save-excursion (beginning-of-line 1)
12024 (looking-at org-todo-line-regexp))
12025 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12026 (goto-char (or (match-end 2) (match-end 1)))
12027 (and (looking-at " ") (just-one-space)))
12028 (when org-trigger-hook
12029 (save-excursion
12030 (run-hook-with-args 'org-trigger-hook change-plist)))
12031 (when commentp (org-toggle-comment))))))))
12033 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12034 "Block turning an entry into a TODO, using the hierarchy.
12035 This checks whether the current task should be blocked from state
12036 changes. Such blocking occurs when:
12038 1. The task has children which are not all in a completed state.
12040 2. A task has a parent with the property :ORDERED:, and there
12041 are siblings prior to the current task with incomplete
12042 status.
12044 3. The parent of the task is blocked because it has siblings that should
12045 be done first, or is child of a block grandparent TODO entry."
12047 (if (not org-enforce-todo-dependencies)
12048 t ; if locally turned off don't block
12049 (catch 'dont-block
12050 ;; If this is not a todo state change, or if this entry is already DONE,
12051 ;; do not block
12052 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12053 (member (plist-get change-plist :from)
12054 (cons 'done org-done-keywords))
12055 (member (plist-get change-plist :to)
12056 (cons 'todo org-not-done-keywords))
12057 (not (plist-get change-plist :to)))
12058 (throw 'dont-block t))
12059 ;; If this task has children, and any are undone, it's blocked
12060 (save-excursion
12061 (org-back-to-heading t)
12062 (let ((this-level (funcall outline-level)))
12063 (outline-next-heading)
12064 (let ((child-level (funcall outline-level)))
12065 (while (and (not (eobp))
12066 (> child-level this-level))
12067 ;; this todo has children, check whether they are all
12068 ;; completed
12069 (when (and (not (org-entry-is-done-p))
12070 (org-entry-is-todo-p))
12071 (setq org-block-entry-blocking (org-get-heading))
12072 (throw 'dont-block nil))
12073 (outline-next-heading)
12074 (setq child-level (funcall outline-level))))))
12075 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12076 ;; any previous siblings are undone, it's blocked
12077 (save-excursion
12078 (org-back-to-heading t)
12079 (let* ((pos (point))
12080 (parent-pos (and (org-up-heading-safe) (point)))
12081 (case-fold-search nil))
12082 (unless parent-pos (throw 'dont-block t)) ; no parent
12083 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12084 (forward-line 1)
12085 (re-search-forward org-not-done-heading-regexp pos t))
12086 (setq org-block-entry-blocking (match-string 0))
12087 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12088 ;; Search further up the hierarchy, to see if an ancestor is blocked
12089 (while t
12090 (goto-char parent-pos)
12091 (unless (looking-at org-not-done-heading-regexp)
12092 (throw 'dont-block t)) ; do not block, parent is not a TODO
12093 (setq pos (point))
12094 (setq parent-pos (and (org-up-heading-safe) (point)))
12095 (unless parent-pos (throw 'dont-block t)) ; no parent
12096 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12097 (forward-line 1)
12098 (re-search-forward org-not-done-heading-regexp pos t)
12099 (setq org-block-entry-blocking (org-get-heading)))
12100 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12102 (defcustom org-track-ordered-property-with-tag nil
12103 "Should the ORDERED property also be shown as a tag?
12104 The ORDERED property decides if an entry should require subtasks to be
12105 completed in sequence. Since a property is not very visible, setting
12106 this option means that toggling the ORDERED property with the command
12107 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12108 not relevant for the behavior, but it makes things more visible.
12110 Note that toggling the tag with tags commands will not change the property
12111 and therefore not influence behavior!
12113 This can be t, meaning the tag ORDERED should be used, It can also be a
12114 string to select a different tag for this task."
12115 :group 'org-todo
12116 :type '(choice
12117 (const :tag "No tracking" nil)
12118 (const :tag "Track with ORDERED tag" t)
12119 (string :tag "Use other tag")))
12121 (defun org-toggle-ordered-property ()
12122 "Toggle the ORDERED property of the current entry.
12123 For better visibility, you can track the value of this property with a tag.
12124 See variable `org-track-ordered-property-with-tag'."
12125 (interactive)
12126 (let* ((t1 org-track-ordered-property-with-tag)
12127 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12128 (save-excursion
12129 (org-back-to-heading)
12130 (if (org-entry-get nil "ORDERED")
12131 (progn
12132 (org-delete-property "ORDERED")
12133 (and tag (org-toggle-tag tag 'off))
12134 (message "Subtasks can be completed in arbitrary order"))
12135 (org-entry-put nil "ORDERED" "t")
12136 (and tag (org-toggle-tag tag 'on))
12137 (message "Subtasks must be completed in sequence")))))
12139 (defun org-block-todo-from-checkboxes (change-plist)
12140 "Block turning an entry into a TODO, using checkboxes.
12141 This checks whether the current task should be blocked from state
12142 changes because there are unchecked boxes in this entry."
12143 (if (not org-enforce-todo-checkbox-dependencies)
12144 t ; if locally turned off don't block
12145 (catch 'dont-block
12146 ;; If this is not a todo state change, or if this entry is already DONE,
12147 ;; do not block
12148 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12149 (member (plist-get change-plist :from)
12150 (cons 'done org-done-keywords))
12151 (member (plist-get change-plist :to)
12152 (cons 'todo org-not-done-keywords))
12153 (not (plist-get change-plist :to)))
12154 (throw 'dont-block t))
12155 ;; If this task has checkboxes that are not checked, it's blocked
12156 (save-excursion
12157 (org-back-to-heading t)
12158 (let ((beg (point)) end)
12159 (outline-next-heading)
12160 (setq end (point))
12161 (goto-char beg)
12162 (when (org-list-search-forward
12163 (concat (org-item-beginning-re)
12164 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12165 "\\[[- ]\\]")
12166 end t)
12167 (when (boundp 'org-blocked-by-checkboxes)
12168 (setq org-blocked-by-checkboxes t))
12169 (throw 'dont-block nil))))
12170 t))) ; do not block
12172 (defun org-entry-blocked-p ()
12173 "Non-nil if entry at point is blocked."
12174 (and (not (org-entry-get nil "NOBLOCKING"))
12175 (member (org-entry-get nil "TODO") org-not-done-keywords)
12176 (not (run-hook-with-args-until-failure
12177 'org-blocker-hook
12178 (list :type 'todo-state-change
12179 :position (point)
12180 :from 'todo
12181 :to 'done)))))
12183 (defun org-update-statistics-cookies (all)
12184 "Update the statistics cookie, either from TODO or from checkboxes.
12185 This should be called with the cursor in a line with a statistics
12186 cookie. When called with a \\[universal-argument] prefix, update
12187 all statistics cookies in the buffer."
12188 (interactive "P")
12189 (if all
12190 (progn
12191 (org-update-checkbox-count 'all)
12192 (org-map-entries 'org-update-parent-todo-statistics))
12193 (if (not (org-at-heading-p))
12194 (org-update-checkbox-count)
12195 (let ((pos (point-marker))
12196 end l1 l2)
12197 (ignore-errors (org-back-to-heading t))
12198 (if (not (org-at-heading-p))
12199 (org-update-checkbox-count)
12200 (setq l1 (org-outline-level))
12201 (setq end (save-excursion
12202 (outline-next-heading)
12203 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12204 (point)))
12205 (if (and (save-excursion
12206 (re-search-forward
12207 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12208 (not (save-excursion (re-search-forward
12209 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12210 (org-update-checkbox-count)
12211 (if (and l2 (> l2 l1))
12212 (progn
12213 (goto-char end)
12214 (org-update-parent-todo-statistics))
12215 (goto-char pos)
12216 (beginning-of-line 1)
12217 (while (re-search-forward
12218 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12219 (point-at-eol) t)
12220 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12221 (goto-char pos)
12222 (move-marker pos nil)))))
12224 (defvar org-entry-property-inherited-from) ;; defined below
12225 (defun org-update-parent-todo-statistics ()
12226 "Update any statistics cookie in the parent of the current headline.
12227 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12228 the entire subtree and this will travel up the hierarchy and update
12229 statistics everywhere."
12230 (let* ((prop (save-excursion (org-up-heading-safe)
12231 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12232 (recursive (or (not org-hierarchical-todo-statistics)
12233 (and prop (string-match "\\<recursive\\>" prop))))
12234 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12236 (first t)
12237 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12238 level ltoggle l1 new ndel
12239 (cnt-all 0) (cnt-done 0) is-percent kwd
12240 checkbox-beg cookie-present)
12241 (catch 'exit
12242 (save-excursion
12243 (beginning-of-line 1)
12244 (setq ltoggle (funcall outline-level))
12245 ;; Three situations are to consider:
12247 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12248 ;; to the top-level ancestor on the headline;
12250 ;; 2. If parent has "recursive" property, repeat up to the
12251 ;; headline setting that property, taking inheritance into
12252 ;; account;
12254 ;; 3. Else, move up to direct parent and proceed only once.
12255 (while (and (setq level (org-up-heading-safe))
12256 (or recursive first)
12257 (>= (point) lim))
12258 (setq first nil cookie-present nil)
12259 (unless (and level
12260 (not (string-match
12261 "\\<checkbox\\>"
12262 (downcase (or (org-entry-get nil "COOKIE_DATA")
12263 "")))))
12264 (throw 'exit nil))
12265 (while (re-search-forward box-re (point-at-eol) t)
12266 (setq cnt-all 0 cnt-done 0 cookie-present t)
12267 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12268 (save-match-data
12269 (unless (outline-next-heading) (throw 'exit nil))
12270 (while (and (looking-at org-complex-heading-regexp)
12271 (> (setq l1 (length (match-string 1))) level))
12272 (setq kwd (and (or recursive (= l1 ltoggle))
12273 (match-string 2)))
12274 (if (or (eq org-provide-todo-statistics 'all-headlines)
12275 (and (eq org-provide-todo-statistics t)
12276 (or (member kwd org-done-keywords)))
12277 (and (listp org-provide-todo-statistics)
12278 (stringp (car org-provide-todo-statistics))
12279 (or (member kwd org-provide-todo-statistics)
12280 (member kwd org-done-keywords)))
12281 (and (listp org-provide-todo-statistics)
12282 (listp (car org-provide-todo-statistics))
12283 (or (member kwd (car org-provide-todo-statistics))
12284 (and (member kwd org-done-keywords)
12285 (member kwd (cadr org-provide-todo-statistics))))))
12286 (setq cnt-all (1+ cnt-all))
12287 (and (eq org-provide-todo-statistics t)
12289 (setq cnt-all (1+ cnt-all))))
12290 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12291 (member kwd org-done-keywords))
12292 (and (listp org-provide-todo-statistics)
12293 (listp (car org-provide-todo-statistics))
12294 (member kwd org-done-keywords)
12295 (member kwd (cadr org-provide-todo-statistics)))
12296 (and (listp org-provide-todo-statistics)
12297 (stringp (car org-provide-todo-statistics))
12298 (member kwd org-done-keywords)))
12299 (setq cnt-done (1+ cnt-done)))
12300 (outline-next-heading)))
12301 (setq new
12302 (if is-percent
12303 (format "[%d%%]" (floor (* 100.0 cnt-done)
12304 (max 1 cnt-all)))
12305 (format "[%d/%d]" cnt-done cnt-all))
12306 ndel (- (match-end 0) checkbox-beg))
12307 (goto-char checkbox-beg)
12308 (insert new)
12309 (delete-region (point) (+ (point) ndel))
12310 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12311 (when cookie-present
12312 (run-hook-with-args 'org-after-todo-statistics-hook
12313 cnt-done (- cnt-all cnt-done))))))
12314 (run-hooks 'org-todo-statistics-hook)))
12316 (defvar org-after-todo-statistics-hook nil
12317 "Hook that is called after a TODO statistics cookie has been updated.
12318 Each function is called with two arguments: the number of not-done entries
12319 and the number of done entries.
12321 For example, the following function, when added to this hook, will switch
12322 an entry to DONE when all children are done, and back to TODO when new
12323 entries are set to a TODO status. Note that this hook is only called
12324 when there is a statistics cookie in the headline!
12326 (defun org-summary-todo (n-done n-not-done)
12327 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12328 (let (org-log-done org-log-states) ; turn off logging
12329 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12332 (defvar org-todo-statistics-hook nil
12333 "Hook that is run whenever Org thinks TODO statistics should be updated.
12334 This hook runs even if there is no statistics cookie present, in which case
12335 `org-after-todo-statistics-hook' would not run.")
12337 (defun org-todo-trigger-tag-changes (state)
12338 "Apply the changes defined in `org-todo-state-tags-triggers'."
12339 (let ((l org-todo-state-tags-triggers)
12340 changes)
12341 (when (or (not state) (equal state ""))
12342 (setq changes (append changes (cdr (assoc "" l)))))
12343 (when (and (stringp state) (> (length state) 0))
12344 (setq changes (append changes (cdr (assoc state l)))))
12345 (when (member state org-not-done-keywords)
12346 (setq changes (append changes (cdr (assq 'todo l)))))
12347 (when (member state org-done-keywords)
12348 (setq changes (append changes (cdr (assq 'done l)))))
12349 (dolist (c changes)
12350 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12352 (defun org-local-logging (value)
12353 "Get logging settings from a property VALUE."
12354 ;; Directly set the variables, they are already local.
12355 (setq org-log-done nil
12356 org-log-repeat nil
12357 org-todo-log-states nil)
12358 (dolist (w (split-string value))
12359 (let (a)
12360 (cond
12361 ((setq a (assoc w org-startup-options))
12362 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12363 (set (nth 1 a) (nth 2 a))))
12364 ((setq a (org-extract-log-state-settings w))
12365 (and (member (car a) org-todo-keywords-1)
12366 (push a org-todo-log-states)))))))
12368 (defun org-get-todo-sequence-head (kwd)
12369 "Return the head of the TODO sequence to which KWD belongs.
12370 If KWD is not set, check if there is a text property remembering the
12371 right sequence."
12372 (let (p)
12373 (cond
12374 ((not kwd)
12375 (or (get-text-property (point-at-bol) 'org-todo-head)
12376 (progn
12377 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12378 nil (point-at-eol)))
12379 (get-text-property p 'org-todo-head))))
12380 ((not (member kwd org-todo-keywords-1))
12381 (car org-todo-keywords-1))
12382 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12384 (defun org-fast-todo-selection ()
12385 "Fast TODO keyword selection with single keys.
12386 Returns the new TODO keyword, or nil if no state change should occur."
12387 (let* ((fulltable org-todo-key-alist)
12388 (done-keywords org-done-keywords) ;; needed for the faces.
12389 (maxlen (apply 'max (mapcar
12390 (lambda (x)
12391 (if (stringp (car x)) (string-width (car x)) 0))
12392 fulltable)))
12393 (expert nil)
12394 (fwidth (+ maxlen 3 1 3))
12395 (ncol (/ (- (window-width) 4) fwidth))
12396 tg cnt e c tbl
12397 groups ingroup)
12398 (save-excursion
12399 (save-window-excursion
12400 (if expert
12401 (set-buffer (get-buffer-create " *Org todo*"))
12402 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12403 (erase-buffer)
12404 (setq-local org-done-keywords done-keywords)
12405 (setq tbl fulltable cnt 0)
12406 (while (setq e (pop tbl))
12407 (cond
12408 ((equal e '(:startgroup))
12409 (push '() groups) (setq ingroup t)
12410 (unless (= cnt 0)
12411 (setq cnt 0)
12412 (insert "\n"))
12413 (insert "{ "))
12414 ((equal e '(:endgroup))
12415 (setq ingroup nil cnt 0)
12416 (insert "}\n"))
12417 ((equal e '(:newline))
12418 (unless (= cnt 0)
12419 (setq cnt 0)
12420 (insert "\n")
12421 (setq e (car tbl))
12422 (while (equal (car tbl) '(:newline))
12423 (insert "\n")
12424 (setq tbl (cdr tbl)))))
12426 (setq tg (car e) c (cdr e))
12427 (when ingroup (push tg (car groups)))
12428 (setq tg (org-add-props tg nil 'face
12429 (org-get-todo-face tg)))
12430 (when (and (= cnt 0) (not ingroup)) (insert " "))
12431 (insert "[" c "] " tg (make-string
12432 (- fwidth 4 (length tg)) ?\ ))
12433 (when (= (setq cnt (1+ cnt)) ncol)
12434 (insert "\n")
12435 (when ingroup (insert " "))
12436 (setq cnt 0)))))
12437 (insert "\n")
12438 (goto-char (point-min))
12439 (unless expert (org-fit-window-to-buffer))
12440 (message "[a-z..]:Set [SPC]:clear")
12441 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12442 (cond
12443 ((or (= c ?\C-g)
12444 (and (= c ?q) (not (rassoc c fulltable))))
12445 (setq quit-flag t))
12446 ((= c ?\ ) nil)
12447 ((setq e (rassoc c fulltable) tg (car e))
12449 (t (setq quit-flag t)))))))
12451 (defun org-entry-is-todo-p ()
12452 (member (org-get-todo-state) org-not-done-keywords))
12454 (defun org-entry-is-done-p ()
12455 (member (org-get-todo-state) org-done-keywords))
12457 (defun org-get-todo-state ()
12458 "Return the TODO keyword of the current subtree."
12459 (save-excursion
12460 (org-back-to-heading t)
12461 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12462 (match-end 2)
12463 (match-string 2))))
12465 (defun org-at-date-range-p (&optional inactive-ok)
12466 "Non-nil if point is inside a date range.
12468 When optional argument INACTIVE-OK is non-nil, also consider
12469 inactive time ranges.
12471 When this function returns a non-nil value, match data is set
12472 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12473 on INACTIVE-OK."
12474 (interactive)
12475 (save-excursion
12476 (catch 'exit
12477 (let ((pos (point)))
12478 (skip-chars-backward "^[<\r\n")
12479 (skip-chars-backward "<[")
12480 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12481 (>= (match-end 0) pos)
12482 (throw 'exit t))
12483 (skip-chars-backward "^<[\r\n")
12484 (skip-chars-backward "<[")
12485 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12486 (>= (match-end 0) pos)
12487 (throw 'exit t)))
12488 nil)))
12490 (defun org-get-repeat (&optional timestamp)
12491 "Check if there is a time-stamp with repeater in this entry.
12493 Return the repeater, as a string, or nil. Also return nil when
12494 this function is called before first heading.
12496 When optional argument TIMESTAMP is a string, extract the
12497 repeater from there instead."
12498 (save-match-data
12499 (cond (timestamp
12500 (and (string-match org-repeat-re timestamp)
12501 (match-string-no-properties 1 timestamp)))
12502 ((org-before-first-heading-p) nil)
12504 (save-excursion
12505 (org-back-to-heading t)
12506 (let ((end (org-entry-end-position)))
12507 (catch :repeat
12508 (while (re-search-forward org-repeat-re end t)
12509 (when (save-match-data (org-at-timestamp-p 'agenda))
12510 (throw :repeat (match-string-no-properties 1)))))))))))
12512 (defvar org-last-changed-timestamp)
12513 (defvar org-last-inserted-timestamp)
12514 (defvar org-log-post-message)
12515 (defvar org-log-note-purpose)
12516 (defvar org-log-note-how nil)
12517 (defvar org-log-note-extra)
12518 (defun org-auto-repeat-maybe (done-word)
12519 "Check if the current headline contains a repeated time-stamp.
12521 If yes, set TODO state back to what it was and change the base date
12522 of repeating deadline/scheduled time stamps to new date.
12524 This function is run automatically after each state change to a DONE state."
12525 (let* ((repeat (org-get-repeat))
12526 (aa (assoc org-last-state org-todo-kwd-alist))
12527 (interpret (nth 1 aa))
12528 (head (nth 2 aa))
12529 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12530 (msg "Entry repeats: ")
12531 (org-log-done nil)
12532 (org-todo-log-states nil)
12533 (end (copy-marker (org-entry-end-position))))
12534 (unwind-protect
12535 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12536 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12537 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12538 (and (stringp org-todo-repeat-to-state)
12539 org-todo-repeat-to-state)
12540 (and org-todo-repeat-to-state org-last-state))))
12541 (org-todo (cond
12542 ((and to-state (member to-state org-todo-keywords-1))
12543 to-state)
12544 ((eq interpret 'type) org-last-state)
12545 (head)
12546 (t 'none))))
12547 (org-back-to-heading t)
12548 (org-add-planning-info nil nil 'closed)
12549 ;; When `org-log-repeat' is non-nil or entry contains
12550 ;; a clock, set LAST_REPEAT property.
12551 (when (or org-log-repeat
12552 (catch :clock
12553 (save-excursion
12554 (while (re-search-forward org-clock-line-re end t)
12555 (when (org-at-clock-log-p) (throw :clock t))))))
12556 (org-entry-put nil "LAST_REPEAT" (format-time-string
12557 (org-time-stamp-format t t)
12558 (current-time))))
12559 (when org-log-repeat
12560 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12561 (memq 'org-add-log-note post-command-hook))
12562 ;; We are already setup for some record.
12563 (when (eq org-log-repeat 'note)
12564 ;; Make sure we take a note, not only a time stamp.
12565 (setq org-log-note-how 'note))
12566 ;; Set up for taking a record.
12567 (org-add-log-setup 'state
12568 (or done-word (car org-done-keywords))
12569 org-last-state
12570 org-log-repeat)))
12571 (let ((planning-re (regexp-opt
12572 (list org-scheduled-string org-deadline-string))))
12573 (while (re-search-forward org-ts-regexp end t)
12574 (let* ((ts (match-string 0))
12575 (planning? (org-at-planning-p))
12576 (type (if (not planning?) "Plain:"
12577 (save-excursion
12578 (re-search-backward
12579 planning-re (line-beginning-position) t)
12580 (match-string 0)))))
12581 (cond
12582 ;; Ignore fake time-stamps (e.g., within comments).
12583 ((not (org-at-timestamp-p 'agenda)))
12584 ;; Time-stamps without a repeater are usually
12585 ;; skipped. However, a SCHEDULED time-stamp without
12586 ;; one is removed, as they are no longer relevant.
12587 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12588 ts))
12589 (when (equal type org-scheduled-string)
12590 (org-remove-timestamp-with-keyword type)))
12592 (let ((n (string-to-number (match-string 2 ts)))
12593 (what (match-string 3 ts)))
12594 (when (equal what "w") (setq n (* n 7) what "d"))
12595 (when (and (equal what "h")
12596 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12597 ts)))
12598 (user-error
12599 "Cannot repeat in Repeat in %d hour(s) because no hour \
12600 has been set"
12602 ;; Preparation, see if we need to modify the start
12603 ;; date for the change.
12604 (when (match-end 1)
12605 (let ((time (save-match-data
12606 (org-time-string-to-time ts))))
12607 (cond
12608 ((equal (match-string 1 ts) ".")
12609 ;; Shift starting date to today
12610 (org-timestamp-change
12611 (- (org-today) (time-to-days time))
12612 'day))
12613 ((equal (match-string 1 ts) "+")
12614 (let ((nshiftmax 10)
12615 (nshift 0))
12616 (while (or (= nshift 0)
12617 (not (time-less-p (current-time) time)))
12618 (when (= (cl-incf nshift) nshiftmax)
12619 (or (y-or-n-p
12620 (format "%d repeater intervals were not \
12621 enough to shift date past today. Continue? "
12622 nshift))
12623 (user-error "Abort")))
12624 (org-timestamp-change n (cdr (assoc what whata)))
12625 (org-in-regexp org-ts-regexp3)
12626 (setq ts (match-string 1))
12627 (setq time
12628 (save-match-data
12629 (org-time-string-to-time ts)))))
12630 (org-timestamp-change (- n) (cdr (assoc what whata)))
12631 ;; Rematch, so that we have everything in place
12632 ;; for the real shift.
12633 (org-in-regexp org-ts-regexp3)
12634 (setq ts (match-string 1))
12635 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12636 ts)))))
12637 (save-excursion
12638 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12639 (setq msg
12640 (concat
12641 msg type " " org-last-changed-timestamp " "))))))))
12642 (setq org-log-post-message msg)
12643 (message "%s" msg))
12644 (set-marker end nil))))
12646 (defun org-show-todo-tree (arg)
12647 "Make a compact tree which shows all headlines marked with TODO.
12648 The tree will show the lines where the regexp matches, and all higher
12649 headlines above the match.
12650 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12651 With a numeric prefix N, construct a sparse tree for the Nth element
12652 of `org-todo-keywords-1'."
12653 (interactive "P")
12654 (let ((case-fold-search nil)
12655 (kwd-re
12656 (cond ((null arg) org-not-done-regexp)
12657 ((equal arg '(4))
12658 (let ((kwd
12659 (completing-read "Keyword (or KWD1|KWD2|...): "
12660 (mapcar #'list org-todo-keywords-1))))
12661 (concat "\\("
12662 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12663 "\\)\\>")))
12664 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12665 (regexp-quote (nth (1- (prefix-numeric-value arg))
12666 org-todo-keywords-1)))
12667 (t (user-error "Invalid prefix argument: %s" arg)))))
12668 (message "%d TODO entries found"
12669 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12671 (defun org--deadline-or-schedule (arg type time)
12672 "Insert DEADLINE or SCHEDULE information in current entry.
12673 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12674 `org-schedule' for information about ARG and TIME arguments."
12675 (let* ((deadline? (eq type 'deadline))
12676 (keyword (if deadline? org-deadline-string org-scheduled-string))
12677 (log (if deadline? org-log-redeadline org-log-reschedule))
12678 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12679 (old-date-time (and old-date (org-time-string-to-time old-date)))
12680 ;; Save repeater cookie from either TIME or current scheduled
12681 ;; time stamp. We are going to insert it back at the end of
12682 ;; the process.
12683 (repeater (or (and (org-string-nw-p time)
12684 ;; We use `org-repeat-re' because we need
12685 ;; to tell the difference between a real
12686 ;; repeater and a time delta, e.g. "+2d".
12687 (string-match org-repeat-re time)
12688 (match-string 1 time))
12689 (and (org-string-nw-p old-date)
12690 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12691 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12692 old-date)
12693 (match-string 1 old-date)))))
12694 (pcase arg
12695 (`(4)
12696 (when (and old-date log)
12697 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12698 nil old-date log))
12699 (org-remove-timestamp-with-keyword keyword)
12700 (message (if deadline? "Item no longer has a deadline."
12701 "Item is no longer scheduled.")))
12702 (`(16)
12703 (save-excursion
12704 (org-back-to-heading t)
12705 (let ((regexp (if deadline? org-deadline-time-regexp
12706 org-scheduled-time-regexp)))
12707 (if (not (re-search-forward regexp (line-end-position 2) t))
12708 (user-error (if deadline? "No deadline information to update"
12709 "No scheduled information to update"))
12710 (let* ((rpl0 (match-string 1))
12711 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12712 (msg (if deadline? "Warn starting from" "Delay until")))
12713 (replace-match
12714 (concat keyword
12715 " <" rpl
12716 (format " -%dd"
12717 (abs (- (time-to-days
12718 (save-match-data
12719 (org-read-date
12720 nil t nil msg old-date-time)))
12721 (time-to-days old-date-time))))
12722 ">") t t))))))
12724 (org-add-planning-info type time 'closed)
12725 (when (and old-date
12727 (not (equal old-date org-last-inserted-timestamp)))
12728 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12729 org-last-inserted-timestamp
12730 old-date
12731 log))
12732 (when repeater
12733 (save-excursion
12734 (org-back-to-heading t)
12735 (when (re-search-forward
12736 (concat keyword " " org-last-inserted-timestamp)
12737 (line-end-position 2)
12739 (goto-char (1- (match-end 0)))
12740 (insert " " repeater)
12741 (setq org-last-inserted-timestamp
12742 (concat (substring org-last-inserted-timestamp 0 -1)
12743 " " repeater
12744 (substring org-last-inserted-timestamp -1))))))
12745 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12746 org-last-inserted-timestamp)))))
12748 (defun org-deadline (arg &optional time)
12749 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12750 With one universal prefix argument, remove any deadline from the item.
12751 With two universal prefix arguments, prompt for a warning delay.
12752 With argument TIME, set the deadline at the corresponding date. TIME
12753 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12754 (interactive "P")
12755 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12756 (org-map-entries
12757 (lambda () (org--deadline-or-schedule arg 'deadline time))
12759 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12760 'region-start-level
12761 'region)
12762 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12763 (org--deadline-or-schedule arg 'deadline time)))
12765 (defun org-schedule (arg &optional time)
12766 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12767 With one universal prefix argument, remove any scheduling date from the item.
12768 With two universal prefix arguments, prompt for a delay cookie.
12769 With argument TIME, scheduled at the corresponding date. TIME can
12770 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12771 (interactive "P")
12772 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12773 (org-map-entries
12774 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12776 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12777 'region-start-level
12778 'region)
12779 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12780 (org--deadline-or-schedule arg 'scheduled time)))
12782 (defun org-get-scheduled-time (pom &optional inherit)
12783 "Get the scheduled time as a time tuple, of a format suitable
12784 for calling org-schedule with, or if there is no scheduling,
12785 returns nil."
12786 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12787 (when time
12788 (apply 'encode-time (org-parse-time-string time)))))
12790 (defun org-get-deadline-time (pom &optional inherit)
12791 "Get the deadline as a time tuple, of a format suitable for
12792 calling org-deadline with, or if there is no scheduling, returns
12793 nil."
12794 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12795 (when time
12796 (apply 'encode-time (org-parse-time-string time)))))
12798 (defun org-remove-timestamp-with-keyword (keyword)
12799 "Remove all time stamps with KEYWORD in the current entry."
12800 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12801 beg)
12802 (save-excursion
12803 (org-back-to-heading t)
12804 (setq beg (point))
12805 (outline-next-heading)
12806 (while (re-search-backward re beg t)
12807 (replace-match "")
12808 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12809 (equal (char-before) ?\ ))
12810 (backward-delete-char 1)
12811 (when (string-match "^[ \t]*$" (buffer-substring
12812 (point-at-bol) (point-at-eol)))
12813 (delete-region (point-at-bol)
12814 (min (point-max) (1+ (point-at-eol))))))))))
12816 (defvar org-time-was-given) ; dynamically scoped parameter
12817 (defvar org-end-time-was-given) ; dynamically scoped parameter
12819 (defun org-at-planning-p ()
12820 "Non-nil when point is on a planning info line."
12821 ;; This is as accurate and faster than `org-element-at-point' since
12822 ;; planning info location is fixed in the section.
12823 (org-with-wide-buffer
12824 (beginning-of-line)
12825 (and (looking-at-p org-planning-line-re)
12826 (eq (point)
12827 (ignore-errors
12828 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12829 (org-back-to-heading t)
12830 (org-with-limited-levels (org-back-to-heading t)))
12831 (line-beginning-position 2))))))
12833 (defun org-add-planning-info (what &optional time &rest remove)
12834 "Insert new timestamp with keyword in the planning line.
12835 WHAT indicates what kind of time stamp to add. It is a symbol
12836 among `closed', `deadline', `scheduled' and nil. TIME indicates
12837 the time to use. If none is given, the user is prompted for
12838 a date. REMOVE indicates what kind of entries to remove. An old
12839 WHAT entry will also be removed."
12840 (let (org-time-was-given org-end-time-was-given default-time default-input)
12841 (catch 'exit
12842 (when (and (memq what '(scheduled deadline))
12843 (or (not time)
12844 (and (stringp time)
12845 (string-match "^[-+]+[0-9]" time))))
12846 ;; Try to get a default date/time from existing timestamp
12847 (save-excursion
12848 (org-back-to-heading t)
12849 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12850 (when (re-search-forward (if (eq what 'scheduled)
12851 org-scheduled-time-regexp
12852 org-deadline-time-regexp)
12853 end t)
12854 (setq ts (match-string 1)
12855 default-time (apply 'encode-time (org-parse-time-string ts))
12856 default-input (and ts (org-get-compact-tod ts)))))))
12857 (when what
12858 (setq time
12859 (if (stringp time)
12860 ;; This is a string (relative or absolute), set
12861 ;; proper date.
12862 (apply #'encode-time
12863 (org-read-date-analyze
12864 time default-time (decode-time default-time)))
12865 ;; If necessary, get the time from the user
12866 (or time (org-read-date nil 'to-time nil nil
12867 default-time default-input)))))
12869 (org-with-wide-buffer
12870 (org-back-to-heading t)
12871 (forward-line)
12872 (unless (bolp) (insert "\n"))
12873 (cond ((looking-at-p org-planning-line-re)
12874 ;; Move to current indentation.
12875 (skip-chars-forward " \t")
12876 ;; Check if we have to remove something.
12877 (dolist (type (if what (cons what remove) remove))
12878 (save-excursion
12879 (when (re-search-forward
12880 (cl-case type
12881 (closed org-closed-time-regexp)
12882 (deadline org-deadline-time-regexp)
12883 (scheduled org-scheduled-time-regexp)
12884 (otherwise
12885 (error "Invalid planning type: %s" type)))
12886 (line-end-position) t)
12887 ;; Delete until next keyword or end of line.
12888 (delete-region
12889 (match-beginning 0)
12890 (if (re-search-forward org-keyword-time-not-clock-regexp
12891 (line-end-position)
12893 (match-beginning 0)
12894 (line-end-position))))))
12895 ;; If there is nothing more to add and no more keyword
12896 ;; is left, remove the line completely.
12897 (if (and (looking-at-p "[ \t]*$") (not what))
12898 (delete-region (line-beginning-position)
12899 (line-beginning-position 2))
12900 ;; If we removed last keyword, do not leave trailing
12901 ;; white space at the end of line.
12902 (let ((p (point)))
12903 (save-excursion
12904 (end-of-line)
12905 (unless (= (skip-chars-backward " \t" p) 0)
12906 (delete-region (point) (line-end-position)))))))
12907 ((not what) (throw 'exit nil)) ; Nothing to do.
12908 (t (insert-before-markers "\n")
12909 (backward-char 1)
12910 (when org-adapt-indentation
12911 (indent-to-column (1+ (org-outline-level))))))
12912 (when what
12913 ;; Insert planning keyword.
12914 (insert (cl-case what
12915 (closed org-closed-string)
12916 (deadline org-deadline-string)
12917 (scheduled org-scheduled-string)
12918 (otherwise (error "Invalid planning type: %s" what)))
12919 " ")
12920 ;; Insert associated timestamp.
12921 (let ((ts (org-insert-time-stamp
12922 time
12923 (or org-time-was-given
12924 (and (eq what 'closed) org-log-done-with-time))
12925 (eq what 'closed)
12926 nil nil (list org-end-time-was-given))))
12927 (unless (eolp) (insert " "))
12928 ts))))))
12930 (defvar org-log-note-marker (make-marker)
12931 "Marker pointing at the entry where the note is to be inserted.")
12932 (defvar org-log-note-purpose nil)
12933 (defvar org-log-note-state nil)
12934 (defvar org-log-note-previous-state nil)
12935 (defvar org-log-note-extra nil)
12936 (defvar org-log-note-window-configuration nil)
12937 (defvar org-log-note-return-to (make-marker))
12938 (defvar org-log-note-effective-time nil
12939 "Remembered current time so that dynamically scoped
12940 `org-extend-today-until' affects timestamps in state change log")
12942 (defvar org-log-post-message nil
12943 "Message to be displayed after a log note has been stored.
12944 The auto-repeater uses this.")
12946 (defun org-add-note ()
12947 "Add a note to the current entry.
12948 This is done in the same way as adding a state change note."
12949 (interactive)
12950 (org-add-log-setup 'note))
12952 (defun org-log-beginning (&optional create)
12953 "Return expected start of log notes in current entry.
12954 When optional argument CREATE is non-nil, the function creates
12955 a drawer to store notes, if necessary. Returned position ignores
12956 narrowing."
12957 (org-with-wide-buffer
12958 (let ((drawer (org-log-into-drawer)))
12959 (cond
12960 (drawer
12961 (org-end-of-meta-data)
12962 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
12963 (end (if (org-at-heading-p) (point)
12964 (save-excursion (outline-next-heading) (point))))
12965 (case-fold-search t))
12966 (catch 'exit
12967 ;; Try to find existing drawer.
12968 (while (re-search-forward regexp end t)
12969 (let ((element (org-element-at-point)))
12970 (when (eq (org-element-type element) 'drawer)
12971 (let ((cend (org-element-property :contents-end element)))
12972 (when (and (not org-log-states-order-reversed) cend)
12973 (goto-char cend)))
12974 (throw 'exit nil))))
12975 ;; No drawer found. Create one, if permitted.
12976 (when create
12977 (unless (bolp) (insert "\n"))
12978 (let ((beg (point)))
12979 (insert ":" drawer ":\n:END:\n")
12980 (org-indent-region beg (point))
12981 (org-flag-region
12982 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
12983 (end-of-line -1)))))
12985 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
12986 (skip-chars-forward " \t\n")
12987 (beginning-of-line)
12988 (unless org-log-states-order-reversed
12989 (org-skip-over-state-notes)
12990 (skip-chars-backward " \t\n")
12991 (forward-line)))))
12992 (if (bolp) (point) (line-beginning-position 2))))
12994 (defun org-add-log-setup (&optional purpose state prev-state how extra)
12995 "Set up the post command hook to take a note.
12996 If this is about to TODO state change, the new state is expected in STATE.
12997 HOW is an indicator what kind of note should be created.
12998 EXTRA is additional text that will be inserted into the notes buffer."
12999 (move-marker org-log-note-marker (point))
13000 (setq org-log-note-purpose purpose
13001 org-log-note-state state
13002 org-log-note-previous-state prev-state
13003 org-log-note-how how
13004 org-log-note-extra extra
13005 org-log-note-effective-time (org-current-effective-time))
13006 (add-hook 'post-command-hook 'org-add-log-note 'append))
13008 (defun org-skip-over-state-notes ()
13009 "Skip past the list of State notes in an entry."
13010 (when (ignore-errors (goto-char (org-in-item-p)))
13011 (let* ((struct (org-list-struct))
13012 (prevs (org-list-prevs-alist struct))
13013 (regexp
13014 (concat "[ \t]*- +"
13015 (replace-regexp-in-string
13016 " +" " +"
13017 (org-replace-escapes
13018 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13019 `(("%d" . ,org-ts-regexp-inactive)
13020 ("%D" . ,org-ts-regexp)
13021 ("%s" . "\"\\S-+\"")
13022 ("%S" . "\"\\S-+\"")
13023 ("%t" . ,org-ts-regexp-inactive)
13024 ("%T" . ,org-ts-regexp)
13025 ("%u" . ".*?")
13026 ("%U" . ".*?")))))))
13027 (while (looking-at-p regexp)
13028 (goto-char (or (org-list-get-next-item (point) struct prevs)
13029 (org-list-get-item-end (point) struct)))))))
13031 (defun org-add-log-note (&optional _purpose)
13032 "Pop up a window for taking a note, and add this note later."
13033 (remove-hook 'post-command-hook 'org-add-log-note)
13034 (setq org-log-note-window-configuration (current-window-configuration))
13035 (delete-other-windows)
13036 (move-marker org-log-note-return-to (point))
13037 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13038 (goto-char org-log-note-marker)
13039 (org-switch-to-buffer-other-window "*Org Note*")
13040 (erase-buffer)
13041 (if (memq org-log-note-how '(time state))
13042 (org-store-log-note)
13043 (let ((org-inhibit-startup t)) (org-mode))
13044 (insert (format "# Insert note for %s.
13045 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13046 (cond
13047 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13048 ((eq org-log-note-purpose 'done) "closed todo item")
13049 ((eq org-log-note-purpose 'state)
13050 (format "state change from \"%s\" to \"%s\""
13051 (or org-log-note-previous-state "")
13052 (or org-log-note-state "")))
13053 ((eq org-log-note-purpose 'reschedule)
13054 "rescheduling")
13055 ((eq org-log-note-purpose 'delschedule)
13056 "no longer scheduled")
13057 ((eq org-log-note-purpose 'redeadline)
13058 "changing deadline")
13059 ((eq org-log-note-purpose 'deldeadline)
13060 "removing deadline")
13061 ((eq org-log-note-purpose 'refile)
13062 "refiling")
13063 ((eq org-log-note-purpose 'note)
13064 "this entry")
13065 (t (error "This should not happen")))))
13066 (when org-log-note-extra (insert org-log-note-extra))
13067 (setq-local org-finish-function 'org-store-log-note)
13068 (run-hooks 'org-log-buffer-setup-hook)))
13070 (defvar org-note-abort nil) ; dynamically scoped
13071 (defun org-store-log-note ()
13072 "Finish taking a log note, and insert it to where it belongs."
13073 (let ((txt (prog1 (buffer-string)
13074 (kill-buffer)))
13075 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13076 lines)
13077 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13078 (setq txt (replace-match "" t t txt)))
13079 (when (string-match "\\s-+\\'" txt)
13080 (setq txt (replace-match "" t t txt)))
13081 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13082 (when (org-string-nw-p note)
13083 (setq note
13084 (org-replace-escapes
13085 note
13086 (list (cons "%u" (user-login-name))
13087 (cons "%U" user-full-name)
13088 (cons "%t" (format-time-string
13089 (org-time-stamp-format 'long 'inactive)
13090 org-log-note-effective-time))
13091 (cons "%T" (format-time-string
13092 (org-time-stamp-format 'long nil)
13093 org-log-note-effective-time))
13094 (cons "%d" (format-time-string
13095 (org-time-stamp-format nil 'inactive)
13096 org-log-note-effective-time))
13097 (cons "%D" (format-time-string
13098 (org-time-stamp-format nil nil)
13099 org-log-note-effective-time))
13100 (cons "%s" (cond
13101 ((not org-log-note-state) "")
13102 ((string-match-p org-ts-regexp
13103 org-log-note-state)
13104 (format "\"[%s]\""
13105 (substring org-log-note-state 1 -1)))
13106 (t (format "\"%s\"" org-log-note-state))))
13107 (cons "%S"
13108 (cond
13109 ((not org-log-note-previous-state) "")
13110 ((string-match-p org-ts-regexp
13111 org-log-note-previous-state)
13112 (format "\"[%s]\""
13113 (substring
13114 org-log-note-previous-state 1 -1)))
13115 (t (format "\"%s\""
13116 org-log-note-previous-state)))))))
13117 (when lines (setq note (concat note " \\\\")))
13118 (push note lines))
13119 (when (and lines (not org-note-abort))
13120 (with-current-buffer (marker-buffer org-log-note-marker)
13121 (org-with-wide-buffer
13122 ;; Find location for the new note.
13123 (goto-char org-log-note-marker)
13124 (set-marker org-log-note-marker nil)
13125 ;; Note associated to a clock is to be located right after
13126 ;; the clock. Do not move point.
13127 (unless (eq org-log-note-purpose 'clock-out)
13128 (goto-char (org-log-beginning t)))
13129 ;; Make sure point is at the beginning of an empty line.
13130 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13131 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13132 ;; In an existing list, add a new item at the top level.
13133 ;; Otherwise, indent line like a regular one.
13134 (let ((itemp (org-in-item-p)))
13135 (if itemp
13136 (indent-line-to
13137 (let ((struct (save-excursion
13138 (goto-char itemp) (org-list-struct))))
13139 (org-list-get-ind (org-list-get-top-point struct) struct)))
13140 (org-indent-line)))
13141 (insert (org-list-bullet-string "-") (pop lines))
13142 (let ((ind (org-list-item-body-column (line-beginning-position))))
13143 (dolist (line lines)
13144 (insert "\n")
13145 (indent-line-to ind)
13146 (insert line)))
13147 (message "Note stored")
13148 (org-back-to-heading t))
13149 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13150 ;; from within `org-add-log-note' because `buffer-undo-list'
13151 ;; is then modified outside of `org-with-remote-undo'.
13152 (when (eq this-command 'org-agenda-todo)
13153 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13154 ;; Don't add undo information when called from `org-agenda-todo'.
13155 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13156 (set-window-configuration org-log-note-window-configuration)
13157 (with-current-buffer (marker-buffer org-log-note-return-to)
13158 (goto-char org-log-note-return-to))
13159 (move-marker org-log-note-return-to nil)
13160 (when org-log-post-message (message "%s" org-log-post-message))))
13162 (defun org-remove-empty-drawer-at (pos)
13163 "Remove an empty drawer at position POS.
13164 POS may also be a marker."
13165 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13166 (org-with-wide-buffer
13167 (goto-char pos)
13168 (let ((drawer (org-element-at-point)))
13169 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13170 (not (org-element-property :contents-begin drawer)))
13171 (delete-region (org-element-property :begin drawer)
13172 (progn (goto-char (org-element-property :end drawer))
13173 (skip-chars-backward " \r\t\n")
13174 (forward-line)
13175 (point))))))))
13177 (defvar org-ts-type nil)
13178 (defun org-sparse-tree (&optional arg type)
13179 "Create a sparse tree, prompt for the details.
13180 This command can create sparse trees. You first need to select the type
13181 of match used to create the tree:
13183 t Show all TODO entries.
13184 T Show entries with a specific TODO keyword.
13185 m Show entries selected by a tags/property match.
13186 p Enter a property name and its value (both with completion on existing
13187 names/values) and show entries with that property.
13188 r Show entries matching a regular expression (`/' can be used as well).
13189 b Show deadlines and scheduled items before a date.
13190 a Show deadlines and scheduled items after a date.
13191 d Show deadlines due within `org-deadline-warning-days'.
13192 D Show deadlines and scheduled items between a date range."
13193 (interactive "P")
13194 (setq type (or type org-sparse-tree-default-date-type))
13195 (setq org-ts-type type)
13196 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13197 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13198 \[c]ycle through date types: %s"
13199 (cl-case type
13200 (all "all timestamps")
13201 (scheduled "only scheduled")
13202 (deadline "only deadline")
13203 (active "only active timestamps")
13204 (inactive "only inactive timestamps")
13205 (closed "with a closed time-stamp")
13206 (otherwise "scheduled/deadline")))
13207 (let ((answer (read-char-exclusive)))
13208 (cl-case answer
13210 (org-sparse-tree
13212 (cadr
13213 (memq type '(nil all scheduled deadline active inactive closed)))))
13214 (?d (call-interactively 'org-check-deadlines))
13215 (?b (call-interactively 'org-check-before-date))
13216 (?a (call-interactively 'org-check-after-date))
13217 (?D (call-interactively 'org-check-dates-range))
13218 (?t (call-interactively 'org-show-todo-tree))
13219 (?T (org-show-todo-tree '(4)))
13220 (?m (call-interactively 'org-match-sparse-tree))
13221 ((?p ?P)
13222 (let* ((kwd (completing-read
13223 "Property: " (mapcar #'list (org-buffer-property-keys))))
13224 (value (completing-read
13225 "Value: " (mapcar #'list (org-property-values kwd)))))
13226 (unless (string-match "\\`{.*}\\'" value)
13227 (setq value (concat "\"" value "\"")))
13228 (org-match-sparse-tree arg (concat kwd "=" value))))
13229 ((?r ?R ?/) (call-interactively 'org-occur))
13230 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13232 (defvar-local org-occur-highlights nil
13233 "List of overlays used for occur matches.")
13234 (defvar-local org-occur-parameters nil
13235 "Parameters of the active org-occur calls.
13236 This is a list, each call to org-occur pushes as cons cell,
13237 containing the regular expression and the callback, onto the list.
13238 The list can contain several entries if `org-occur' has been called
13239 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13240 will only contain one set of parameters. When the highlights are
13241 removed (for example with `C-c C-c', or with the next edit (depending
13242 on `org-remove-highlights-with-change'), this variable is emptied
13243 as well.")
13245 (defun org-occur (regexp &optional keep-previous callback)
13246 "Make a compact tree which shows all matches of REGEXP.
13248 The tree will show the lines where the regexp matches, and any other context
13249 defined in `org-show-context-detail', which see.
13251 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13252 done by a previous call to `org-occur' will be kept, to allow stacking of
13253 calls to this command.
13255 Optional argument CALLBACK can be a function of no argument. In this case,
13256 it is called with point at the end of the match, match data being set
13257 accordingly. Current match is shown only if the return value is non-nil.
13258 The function must neither move point nor alter narrowing."
13259 (interactive "sRegexp: \nP")
13260 (when (equal regexp "")
13261 (user-error "Regexp cannot be empty"))
13262 (unless keep-previous
13263 (org-remove-occur-highlights nil nil t))
13264 (push (cons regexp callback) org-occur-parameters)
13265 (let ((cnt 0))
13266 (save-excursion
13267 (goto-char (point-min))
13268 (when (or (not keep-previous) ; do not want to keep
13269 (not org-occur-highlights)) ; no previous matches
13270 ;; hide everything
13271 (org-overview))
13272 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13273 (isearch-no-upper-case-p regexp t)
13274 org-occur-case-fold-search)))
13275 (while (re-search-forward regexp nil t)
13276 (when (or (not callback)
13277 (save-match-data (funcall callback)))
13278 (setq cnt (1+ cnt))
13279 (when org-highlight-sparse-tree-matches
13280 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13281 (org-show-context 'occur-tree)))))
13282 (when org-remove-highlights-with-change
13283 (add-hook 'before-change-functions 'org-remove-occur-highlights
13284 nil 'local))
13285 (unless org-sparse-tree-open-archived-trees
13286 (org-hide-archived-subtrees (point-min) (point-max)))
13287 (run-hooks 'org-occur-hook)
13288 (when (called-interactively-p 'interactive)
13289 (message "%d match(es) for regexp %s" cnt regexp))
13290 cnt))
13292 (defun org-occur-next-match (&optional n _reset)
13293 "Function for `next-error-function' to find sparse tree matches.
13294 N is the number of matches to move, when negative move backwards.
13295 This function always goes back to the starting point when no
13296 match is found."
13297 (let* ((limit (if (< n 0) (point-min) (point-max)))
13298 (search-func (if (< n 0)
13299 'previous-single-char-property-change
13300 'next-single-char-property-change))
13301 (n (abs n))
13302 (pos (point))
13304 (catch 'exit
13305 (while (setq p1 (funcall search-func (point) 'org-type))
13306 (when (equal p1 limit)
13307 (goto-char pos)
13308 (user-error "No more matches"))
13309 (when (equal (get-char-property p1 'org-type) 'org-occur)
13310 (setq n (1- n))
13311 (when (= n 0)
13312 (goto-char p1)
13313 (throw 'exit (point))))
13314 (goto-char p1))
13315 (goto-char p1)
13316 (user-error "No more matches"))))
13318 (defun org-highlight-new-match (beg end)
13319 "Highlight from BEG to END and mark the highlight is an occur headline."
13320 (let ((ov (make-overlay beg end)))
13321 (overlay-put ov 'face 'secondary-selection)
13322 (overlay-put ov 'org-type 'org-occur)
13323 (push ov org-occur-highlights)))
13325 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13326 "Remove the occur highlights from the buffer.
13327 BEG and END are ignored. If NOREMOVE is nil, remove this function
13328 from the `before-change-functions' in the current buffer."
13329 (interactive)
13330 (unless org-inhibit-highlight-removal
13331 (mapc #'delete-overlay org-occur-highlights)
13332 (setq org-occur-highlights nil)
13333 (setq org-occur-parameters nil)
13334 (unless noremove
13335 (remove-hook 'before-change-functions
13336 'org-remove-occur-highlights 'local))))
13338 ;;;; Priorities
13340 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13341 "Regular expression matching the priority indicator.")
13343 (defvar org-remove-priority-next-time nil)
13345 (defun org-priority-up ()
13346 "Increase the priority of the current item."
13347 (interactive)
13348 (org-priority 'up))
13350 (defun org-priority-down ()
13351 "Decrease the priority of the current item."
13352 (interactive)
13353 (org-priority 'down))
13355 (defun org-priority (&optional action _show)
13356 "Change the priority of an item.
13357 ACTION can be `set', `up', `down', or a character."
13358 (interactive "P")
13359 (if (equal action '(4))
13360 (org-show-priority)
13361 (unless org-enable-priority-commands
13362 (user-error "Priority commands are disabled"))
13363 (setq action (or action 'set))
13364 (let (current new news have remove)
13365 (save-excursion
13366 (org-back-to-heading t)
13367 (when (looking-at org-priority-regexp)
13368 (setq current (string-to-char (match-string 2))
13369 have t))
13370 (cond
13371 ((eq action 'remove)
13372 (setq remove t new ?\ ))
13373 ((or (eq action 'set)
13374 (integerp action))
13375 (if (not (eq action 'set))
13376 (setq new action)
13377 (message "Priority %c-%c, SPC to remove: "
13378 org-highest-priority org-lowest-priority)
13379 (save-match-data
13380 (setq new (read-char-exclusive))))
13381 (when (and (= (upcase org-highest-priority) org-highest-priority)
13382 (= (upcase org-lowest-priority) org-lowest-priority))
13383 (setq new (upcase new)))
13384 (cond ((equal new ?\ ) (setq remove t))
13385 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13386 (user-error "Priority must be between `%c' and `%c'"
13387 org-highest-priority org-lowest-priority))))
13388 ((eq action 'up)
13389 (setq new (if have
13390 (1- current) ; normal cycling
13391 ;; last priority was empty
13392 (if (eq last-command this-command)
13393 org-lowest-priority ; wrap around empty to lowest
13394 ;; default
13395 (if org-priority-start-cycle-with-default
13396 org-default-priority
13397 (1- org-default-priority))))))
13398 ((eq action 'down)
13399 (setq new (if have
13400 (1+ current) ; normal cycling
13401 ;; last priority was empty
13402 (if (eq last-command this-command)
13403 org-highest-priority ; wrap around empty to highest
13404 ;; default
13405 (if org-priority-start-cycle-with-default
13406 org-default-priority
13407 (1+ org-default-priority))))))
13408 (t (user-error "Invalid action")))
13409 (when (or (< (upcase new) org-highest-priority)
13410 (> (upcase new) org-lowest-priority))
13411 (if (and (memq action '(up down))
13412 (not have) (not (eq last-command this-command)))
13413 ;; `new' is from default priority
13414 (error
13415 "The default can not be set, see `org-default-priority' why")
13416 ;; normal cycling: `new' is beyond highest/lowest priority
13417 ;; and is wrapped around to the empty priority
13418 (setq remove t)))
13419 (setq news (format "%c" new))
13420 (if have
13421 (if remove
13422 (replace-match "" t t nil 1)
13423 (replace-match news t t nil 2))
13424 (if remove
13425 (user-error "No priority cookie found in line")
13426 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13427 (if (match-end 2)
13428 (progn
13429 (goto-char (match-end 2))
13430 (insert " [#" news "]"))
13431 (goto-char (match-beginning 3))
13432 (insert "[#" news "] "))))
13433 (org-set-tags nil 'align))
13434 (if remove
13435 (message "Priority removed")
13436 (message "Priority of current item set to %s" news)))))
13438 (defun org-show-priority ()
13439 "Show the priority of the current item.
13440 This priority is composed of the main priority given with the [#A] cookies,
13441 and by additional input from the age of a schedules or deadline entry."
13442 (interactive)
13443 (let ((pri (if (eq major-mode 'org-agenda-mode)
13444 (org-get-at-bol 'priority)
13445 (save-excursion
13446 (save-match-data
13447 (beginning-of-line)
13448 (and (looking-at org-heading-regexp)
13449 (org-get-priority (match-string 0))))))))
13450 (message "Priority is %d" (if pri pri -1000))))
13452 (defun org-get-priority (s)
13453 "Find priority cookie and return priority."
13454 (save-match-data
13455 (if (functionp org-get-priority-function)
13456 (funcall org-get-priority-function)
13457 (if (not (string-match org-priority-regexp s))
13458 (* 1000 (- org-lowest-priority org-default-priority))
13459 (* 1000 (- org-lowest-priority
13460 (string-to-char (match-string 2 s))))))))
13462 ;;;; Tags
13464 (defvar org-agenda-archives-mode)
13465 (defvar org-map-continue-from nil
13466 "Position from where mapping should continue.
13467 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13469 (defvar org-scanner-tags nil
13470 "The current tag list while the tags scanner is running.")
13472 (defvar org-trust-scanner-tags nil
13473 "Should `org-get-tags-at' use the tags for the scanner.
13474 This is for internal dynamical scoping only.
13475 When this is non-nil, the function `org-get-tags-at' will return the value
13476 of `org-scanner-tags' instead of building the list by itself. This
13477 can lead to large speed-ups when the tags scanner is used in a file with
13478 many entries, and when the list of tags is retrieved, for example to
13479 obtain a list of properties. Building the tags list for each entry in such
13480 a file becomes an N^2 operation - but with this variable set, it scales
13481 as N.")
13483 (defvar org--matcher-tags-todo-only nil)
13485 (defun org-scan-tags (action matcher todo-only &optional start-level)
13486 "Scan headline tags with inheritance and produce output ACTION.
13488 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13489 or `agenda' to produce an entry list for an agenda view. It can also be
13490 a Lisp form or a function that should be called at each matched headline, in
13491 this case the return value is a list of all return values from these calls.
13493 MATCHER is a function accepting three arguments, returning
13494 a non-nil value whenever a given set of tags qualifies a headline
13495 for inclusion. See `org-make-tags-matcher' for more information.
13496 As a special case, it can also be set to t (respectively nil) in
13497 order to match all (respectively none) headline.
13499 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13500 included in the output.
13502 START-LEVEL can be a string with asterisks, reducing the scope to
13503 headlines matching this string."
13504 (require 'org-agenda)
13505 (let* ((re (concat "^"
13506 (if start-level
13507 ;; Get the correct level to match
13508 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13509 org-outline-regexp)
13510 " *\\(\\<\\("
13511 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13512 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13513 (props (list 'face 'default
13514 'done-face 'org-agenda-done
13515 'undone-face 'default
13516 'mouse-face 'highlight
13517 'org-not-done-regexp org-not-done-regexp
13518 'org-todo-regexp org-todo-regexp
13519 'org-complex-heading-regexp org-complex-heading-regexp
13520 'help-echo
13521 (format "mouse-2 or RET jump to Org file %S"
13522 (abbreviate-file-name
13523 (or (buffer-file-name (buffer-base-buffer))
13524 (buffer-name (buffer-base-buffer)))))))
13525 (org-map-continue-from nil)
13526 lspos tags tags-list
13527 (tags-alist (list (cons 0 org-file-tags)))
13528 (llast 0) rtn rtn1 level category i txt
13529 todo marker entry priority
13530 ts-date ts-date-type ts-date-pair)
13531 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13532 (setq action (list 'lambda nil action)))
13533 (save-excursion
13534 (goto-char (point-min))
13535 (when (eq action 'sparse-tree)
13536 (org-overview)
13537 (org-remove-occur-highlights))
13538 (while (let (case-fold-search)
13539 (re-search-forward re nil t))
13540 (setq org-map-continue-from nil)
13541 (catch :skip
13542 (setq todo
13543 ;; TODO: is the 1-2 difference a bug?
13544 (when (match-end 1) (match-string-no-properties 2))
13545 tags (when (match-end 4) (match-string-no-properties 4)))
13546 (goto-char (setq lspos (match-beginning 0)))
13547 (setq level (org-reduced-level (org-outline-level))
13548 category (org-get-category))
13549 (when (eq action 'agenda)
13550 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13551 ts-date (car ts-date-pair)
13552 ts-date-type (cdr ts-date-pair)))
13553 (setq i llast llast level)
13554 ;; remove tag lists from same and sublevels
13555 (while (>= i level)
13556 (when (setq entry (assoc i tags-alist))
13557 (setq tags-alist (delete entry tags-alist)))
13558 (setq i (1- i)))
13559 ;; add the next tags
13560 (when tags
13561 (setq tags (org-split-string tags ":")
13562 tags-alist
13563 (cons (cons level tags) tags-alist)))
13564 ;; compile tags for current headline
13565 (setq tags-list
13566 (if org-use-tag-inheritance
13567 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13568 tags)
13569 org-scanner-tags tags-list)
13570 (when org-use-tag-inheritance
13571 (setcdr (car tags-alist)
13572 (mapcar (lambda (x)
13573 (setq x (copy-sequence x))
13574 (org-add-prop-inherited x))
13575 (cdar tags-alist))))
13576 (when (and tags org-use-tag-inheritance
13577 (or (not (eq t org-use-tag-inheritance))
13578 org-tags-exclude-from-inheritance))
13579 ;; Selective inheritance, remove uninherited ones.
13580 (setcdr (car tags-alist)
13581 (org-remove-uninherited-tags (cdar tags-alist))))
13582 (when (and
13584 ;; eval matcher only when the todo condition is OK
13585 (and (or (not todo-only) (member todo org-todo-keywords-1))
13586 (if (functionp matcher)
13587 (let ((case-fold-search t) (org-trust-scanner-tags t))
13588 (funcall matcher todo tags-list level))
13589 matcher))
13591 ;; Call the skipper, but return t if it does not
13592 ;; skip, so that the `and' form continues evaluating.
13593 (progn
13594 (unless (eq action 'sparse-tree) (org-agenda-skip))
13597 ;; Check if timestamps are deselecting this entry
13598 (or (not todo-only)
13599 (and (member todo org-todo-keywords-1)
13600 (or (not org-agenda-tags-todo-honor-ignore-options)
13601 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13603 ;; select this headline
13604 (cond
13605 ((eq action 'sparse-tree)
13606 (and org-highlight-sparse-tree-matches
13607 (org-get-heading) (match-end 0)
13608 (org-highlight-new-match
13609 (match-beginning 1) (match-end 1)))
13610 (org-show-context 'tags-tree))
13611 ((eq action 'agenda)
13612 (setq txt (org-agenda-format-item
13614 (concat
13615 (if (eq org-tags-match-list-sublevels 'indented)
13616 (make-string (1- level) ?.) "")
13617 (org-get-heading))
13618 (make-string level ?\s)
13619 category
13620 tags-list)
13621 priority (org-get-priority txt))
13622 (goto-char lspos)
13623 (setq marker (org-agenda-new-marker))
13624 (org-add-props txt props
13625 'org-marker marker 'org-hd-marker marker 'org-category category
13626 'todo-state todo
13627 'ts-date ts-date
13628 'priority priority
13629 'type (concat "tagsmatch" ts-date-type))
13630 (push txt rtn))
13631 ((functionp action)
13632 (setq org-map-continue-from nil)
13633 (save-excursion
13634 (setq rtn1 (funcall action))
13635 (push rtn1 rtn)))
13636 (t (user-error "Invalid action")))
13638 ;; if we are to skip sublevels, jump to end of subtree
13639 (unless org-tags-match-list-sublevels
13640 (org-end-of-subtree t)
13641 (backward-char 1))))
13642 ;; Get the correct position from where to continue
13643 (if org-map-continue-from
13644 (goto-char org-map-continue-from)
13645 (and (= (point) lspos) (end-of-line 1)))))
13646 (when (and (eq action 'sparse-tree)
13647 (not org-sparse-tree-open-archived-trees))
13648 (org-hide-archived-subtrees (point-min) (point-max)))
13649 (nreverse rtn)))
13651 (defun org-remove-uninherited-tags (tags)
13652 "Remove all tags that are not inherited from the list TAGS."
13653 (cond
13654 ((eq org-use-tag-inheritance t)
13655 (if org-tags-exclude-from-inheritance
13656 (org-delete-all org-tags-exclude-from-inheritance tags)
13657 tags))
13658 ((not org-use-tag-inheritance) nil)
13659 ((stringp org-use-tag-inheritance)
13660 (delq nil (mapcar
13661 (lambda (x)
13662 (if (and (string-match org-use-tag-inheritance x)
13663 (not (member x org-tags-exclude-from-inheritance)))
13664 x nil))
13665 tags)))
13666 ((listp org-use-tag-inheritance)
13667 (delq nil (mapcar
13668 (lambda (x)
13669 (if (member x org-use-tag-inheritance) x nil))
13670 tags)))))
13672 (defun org-match-sparse-tree (&optional todo-only match)
13673 "Create a sparse tree according to tags string MATCH.
13675 MATCH is a string with match syntax. It can contain a selection
13676 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13677 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13678 those. See the manual for details.
13680 If optional argument TODO-ONLY is non-nil, only select lines that
13681 are also TODO tasks."
13682 (interactive "P")
13683 (org-agenda-prepare-buffers (list (current-buffer)))
13684 (let ((org--matcher-tags-todo-only todo-only))
13685 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13686 org--matcher-tags-todo-only)))
13688 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13690 (defvar org-cached-props nil)
13691 (defun org-cached-entry-get (pom property)
13692 (if (or (eq t org-use-property-inheritance)
13693 (and (stringp org-use-property-inheritance)
13694 (let ((case-fold-search t))
13695 (string-match-p org-use-property-inheritance property)))
13696 (and (listp org-use-property-inheritance)
13697 (member-ignore-case property org-use-property-inheritance)))
13698 ;; Caching is not possible, check it directly.
13699 (org-entry-get pom property 'inherit)
13700 ;; Get all properties, so we can do complicated checks easily.
13701 (cdr (assoc-string property
13702 (or org-cached-props
13703 (setq org-cached-props (org-entry-properties pom)))
13704 t))))
13706 (defun org-global-tags-completion-table (&optional files)
13707 "Return the list of all tags in all agenda buffer/files.
13708 Optional FILES argument is a list of files which can be used
13709 instead of the agenda files."
13710 (save-excursion
13711 (org-uniquify
13712 (delq nil
13713 (apply #'append
13714 (mapcar
13715 (lambda (file)
13716 (set-buffer (find-file-noselect file))
13717 (mapcar (lambda (x)
13718 (and (stringp (car-safe x))
13719 (list (car-safe x))))
13720 (or org-current-tag-alist (org-get-buffer-tags))))
13721 (if (car-safe files) files
13722 (org-agenda-files))))))))
13724 (defun org-make-tags-matcher (match)
13725 "Create the TAGS/TODO matcher form for the selection string MATCH.
13727 Returns a cons of the selection string MATCH and a function
13728 implementing the matcher.
13730 The matcher is to be called at an Org entry, with point on the
13731 headline, and returns non-nil if the entry matches the selection
13732 string MATCH. It must be called with three arguments: the TODO
13733 keyword at the entry (or nil if none), the list of all tags at
13734 the entry including inherited ones and the reduced level of the
13735 headline. Additionally, the category of the entry, if any, must
13736 be specified as the text property `org-category' on the headline.
13738 This function sets the variable `org--matcher-tags-todo-only' to
13739 a non-nil value if the matcher restricts matching to TODO
13740 entries, otherwise it is not touched.
13742 See also `org-scan-tags'."
13743 (unless match
13744 ;; Get a new match request, with completion against the global
13745 ;; tags table and the local tags in current buffer.
13746 (let ((org-last-tags-completion-table
13747 (org-uniquify
13748 (delq nil (append (org-get-buffer-tags)
13749 (org-global-tags-completion-table))))))
13750 (setq match
13751 (completing-read
13752 "Match: "
13753 'org-tags-completion-function nil nil nil 'org-tags-history))))
13755 (let ((match0 match)
13756 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13757 (start 0)
13758 tagsmatch todomatch tagsmatcher todomatcher)
13760 ;; Expand group tags.
13761 (setq match (org-tags-expand match))
13763 ;; Check if there is a TODO part of this match, which would be the
13764 ;; part after a "/". To make sure that this slash is not part of
13765 ;; a property value to be matched against, we also check that
13766 ;; there is no / after that slash. First, find the last slash.
13767 (let ((s 0))
13768 (while (string-match "/+" match s)
13769 (setq start (match-beginning 0))
13770 (setq s (match-end 0))))
13771 (if (and (string-match "/+" match start)
13772 (not (string-match-p "\"" match start)))
13773 ;; Match contains also a TODO-matching request.
13774 (progn
13775 (setq tagsmatch (substring match 0 (match-beginning 0)))
13776 (setq todomatch (substring match (match-end 0)))
13777 (when (string-prefix-p "!" todomatch)
13778 (setq org--matcher-tags-todo-only t)
13779 (setq todomatch (substring todomatch 1)))
13780 (when (string-match "\\`\\s-*\\'" todomatch)
13781 (setq todomatch nil)))
13782 ;; Only matching tags.
13783 (setq tagsmatch match)
13784 (setq todomatch nil))
13786 ;; Make the tags matcher.
13787 (when (org-string-nw-p tagsmatch)
13788 (let ((orlist nil)
13789 (orterms (org-split-string tagsmatch "|"))
13790 term)
13791 (while (setq term (pop orterms))
13792 (while (and (equal (substring term -1) "\\") orterms)
13793 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13794 (while (string-match re term)
13795 (let* ((rest (substring term (match-end 0)))
13796 (minus (and (match-end 1)
13797 (equal (match-string 1 term) "-")))
13798 (tag (save-match-data
13799 (replace-regexp-in-string
13800 "\\\\-" "-" (match-string 2 term))))
13801 (regexp (eq (string-to-char tag) ?{))
13802 (levelp (match-end 4))
13803 (propp (match-end 5))
13805 (cond
13806 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13807 (levelp
13808 `(,(org-op-to-function (match-string 3 term))
13809 level
13810 ,(string-to-number (match-string 4 term))))
13811 (propp
13812 (let* ((gv (pcase (upcase (match-string 5 term))
13813 ("CATEGORY"
13814 '(get-text-property (point) 'org-category))
13815 ("TODO" 'todo)
13816 (p `(org-cached-entry-get nil ,p))))
13817 (pv (match-string 7 term))
13818 (regexp (eq (string-to-char pv) ?{))
13819 (strp (eq (string-to-char pv) ?\"))
13820 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13821 (po (org-op-to-function (match-string 6 term)
13822 (if timep 'time strp))))
13823 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13824 (when timep (setq pv (org-matcher-time pv)))
13825 (cond ((and regexp (eq po 'org<>))
13826 `(not (string-match ,pv (or ,gv ""))))
13827 (regexp `(string-match ,pv (or ,gv "")))
13828 (strp `(,po (or ,gv "") ,pv))
13830 `(,po
13831 (string-to-number (or ,gv ""))
13832 ,(string-to-number pv))))))
13833 (t `(member ,tag tags-list)))))
13834 (push (if minus `(not ,mm) mm) tagsmatcher)
13835 (setq term rest)))
13836 (push `(and ,@tagsmatcher) orlist)
13837 (setq tagsmatcher nil))
13838 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13840 ;; Make the TODO matcher.
13841 (when (org-string-nw-p todomatch)
13842 (let ((orlist nil))
13843 (dolist (term (org-split-string todomatch "|"))
13844 (while (string-match re term)
13845 (let* ((minus (and (match-end 1)
13846 (equal (match-string 1 term) "-")))
13847 (kwd (match-string 2 term))
13848 (regexp (eq (string-to-char kwd) ?{))
13849 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13850 `(equal todo ,kwd))))
13851 (push (if minus `(not ,mm) mm) todomatcher))
13852 (setq term (substring term (match-end 0))))
13853 (push (if (> (length todomatcher) 1)
13854 (cons 'and todomatcher)
13855 (car todomatcher))
13856 orlist)
13857 (setq todomatcher nil))
13858 (setq todomatcher (cons 'or orlist))))
13860 ;; Return the string and function of the matcher. If no
13861 ;; tags-specific or todo-specific matcher exists, match
13862 ;; everything.
13863 (let ((matcher (if (and tagsmatcher todomatcher)
13864 `(and ,tagsmatcher ,todomatcher)
13865 (or tagsmatcher todomatcher t))))
13866 (when org--matcher-tags-todo-only
13867 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13868 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13870 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13871 "Expand group tags in MATCH.
13873 This replaces every group tag in MATCH with a regexp tag search.
13874 For example, a group tag \"Work\" defined as { Work : Lab Conf }
13875 will be replaced like this:
13877 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13878 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13879 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13881 Replacing by a regexp preserves the structure of the match.
13882 E.g., this expansion
13884 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
13886 will match anything tagged with \"Lab\" and \"Home\", or tagged
13887 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
13889 A group tag in MATCH can contain regular expressions of its own.
13890 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
13891 will be replaced like this:
13893 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
13895 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
13896 assumed to be a single group tag, and the function will return
13897 the list of tags in this group.
13899 When DOWNCASE is non-nil, expand downcased TAGS."
13900 (if org-group-tags
13901 (let* ((case-fold-search t)
13902 (stable org-mode-syntax-table)
13903 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
13904 (taggroups (if downcased
13905 (mapcar (lambda (tg) (mapcar #'downcase tg))
13906 taggroups)
13907 taggroups))
13908 (taggroups-keys (mapcar #'car taggroups))
13909 (return-match (if downcased (downcase match) match))
13910 (count 0)
13911 (work-already-expanded tags-already-expanded)
13912 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
13913 ;; @ and _ are allowed as word-components in tags.
13914 (modify-syntax-entry ?@ "w" stable)
13915 (modify-syntax-entry ?_ "w" stable)
13916 ;; Temporarily replace regexp-expressions in the match-expression.
13917 (while (string-match "{.+?}" return-match)
13918 (cl-incf count)
13919 (push (match-string 0 return-match) regexps-in-match)
13920 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
13921 (while (and taggroups-keys
13922 (with-syntax-table stable
13923 (string-match
13924 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
13925 (regexp-opt taggroups-keys) "\\>\\)")
13926 return-match)))
13927 (let* ((dir (match-string 1 return-match))
13928 (tag (match-string 2 return-match))
13929 (tag (if downcased (downcase tag) tag)))
13930 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
13931 (member tag work-already-expanded))
13932 (setq tags-in-group (assoc tag taggroups))
13933 (push tag work-already-expanded)
13934 ;; Recursively expand each tag in the group, if the tag hasn't
13935 ;; already been expanded. Restore the match-data after all recursive calls.
13936 (save-match-data
13937 (let (tags-expanded)
13938 (dolist (x (cdr tags-in-group))
13939 (if (and (member x taggroups-keys)
13940 (not (member x work-already-expanded)))
13941 (setq tags-expanded
13942 (delete-dups
13943 (append
13944 (org-tags-expand x t downcased
13945 work-already-expanded)
13946 tags-expanded)))
13947 (setq tags-expanded
13948 (append (list x) tags-expanded)))
13949 (setq work-already-expanded
13950 (delete-dups
13951 (append tags-expanded
13952 work-already-expanded))))
13953 (setq tags-in-group
13954 (delete-dups (cons (car tags-in-group)
13955 tags-expanded)))))
13956 ;; Filter tag-regexps from tags.
13957 (setq regexp-in-group-escaped
13958 (delq nil (mapcar (lambda (x)
13959 (if (stringp x)
13960 (and (equal "{" (substring x 0 1))
13961 (equal "}" (substring x -1))
13964 tags-in-group))
13965 regexp-in-group
13966 (mapcar (lambda (x)
13967 (substring x 1 -1))
13968 regexp-in-group-escaped)
13969 tags-in-group
13970 (delq nil (mapcar (lambda (x)
13971 (if (stringp x)
13972 (and (not (equal "{" (substring x 0 1)))
13973 (not (equal "}" (substring x -1)))
13976 tags-in-group)))
13977 ;; If single-as-list, do no more in the while-loop.
13978 (if (not single-as-list)
13979 (progn
13980 (when regexp-in-group
13981 (setq regexp-in-group
13982 (concat "\\|"
13983 (mapconcat 'identity regexp-in-group
13984 "\\|"))))
13985 (setq tags-in-group
13986 (concat dir
13987 "{\\<"
13988 (regexp-opt tags-in-group)
13989 "\\>"
13990 regexp-in-group
13991 "}"))
13992 (when (stringp tags-in-group)
13993 (org-add-props tags-in-group '(grouptag t)))
13994 (setq return-match
13995 (replace-match tags-in-group t t return-match)))
13996 (setq tags-in-group
13997 (append regexp-in-group-escaped tags-in-group))))
13998 (setq taggroups-keys (delete tag taggroups-keys))))
13999 ;; Add the regular expressions back into the match-expression again.
14000 (while regexps-in-match
14001 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14002 (pop regexps-in-match)
14003 return-match t t))
14004 (cl-decf count))
14005 (if single-as-list
14006 (if tags-in-group tags-in-group (list return-match))
14007 return-match))
14008 (if single-as-list
14009 (list (if downcased (downcase match) match))
14010 match)))
14012 (defun org-op-to-function (op &optional stringp)
14013 "Turn an operator into the appropriate function."
14014 (setq op
14015 (cond
14016 ((equal op "<" ) '(< string< org-time<))
14017 ((equal op ">" ) '(> org-string> org-time>))
14018 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14019 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14020 ((member op '("=" "==")) '(= string= org-time=))
14021 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14022 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14024 (defun org<> (a b) (not (= a b)))
14025 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14026 (defun org-string>= (a b) (not (string< a b)))
14027 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14028 (defun org-string<> (a b) (not (string= a b)))
14029 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14030 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14031 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14032 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14033 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14034 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14035 (defun org-2ft (s)
14036 "Convert S to a floating point time.
14037 If S is already a number, just return it. If it is a string, parse
14038 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14039 (cond
14040 ((numberp s) s)
14041 ((stringp s)
14042 (condition-case nil
14043 (float-time (apply #'encode-time (org-parse-time-string s)))
14044 (error 0.)))
14045 (t 0.)))
14047 (defun org-time-today ()
14048 "Time in seconds today at 0:00.
14049 Returns the float number of seconds since the beginning of the
14050 epoch to the beginning of today (00:00)."
14051 (float-time (apply 'encode-time
14052 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14054 (defun org-matcher-time (s)
14055 "Interpret a time comparison value."
14056 (save-match-data
14057 (cond
14058 ((string= s "<now>") (float-time))
14059 ((string= s "<today>") (org-time-today))
14060 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14061 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14062 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14063 (+ (org-time-today)
14064 (* (string-to-number (match-string 1 s))
14065 (cdr (assoc (match-string 2 s)
14066 '(("d" . 86400.0) ("w" . 604800.0)
14067 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14068 (t (org-2ft s)))))
14070 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14071 (defvar org-tags-overlay (make-overlay 1 1))
14072 (delete-overlay org-tags-overlay)
14074 (defun org-get-local-tags-at (&optional pos)
14075 "Get a list of tags defined in the current headline."
14076 (org-get-tags-at pos 'local))
14078 (defun org-get-local-tags ()
14079 "Get a list of tags defined in the current headline."
14080 (org-get-tags-at nil 'local))
14082 (defun org-get-tags-at (&optional pos local)
14083 "Get a list of all headline tags applicable at POS.
14084 POS defaults to point. If tags are inherited, the list contains
14085 the targets in the same sequence as the headlines appear, i.e.
14086 the tags of the current headline come last.
14087 When LOCAL is non-nil, only return tags from the current headline,
14088 ignore inherited ones."
14089 (interactive)
14090 (if (and org-trust-scanner-tags
14091 (or (not pos) (equal pos (point)))
14092 (not local))
14093 org-scanner-tags
14094 (let (tags ltags lastpos parent)
14095 (save-excursion
14096 (save-restriction
14097 (widen)
14098 (goto-char (or pos (point)))
14099 (save-match-data
14100 (catch 'done
14101 (condition-case nil
14102 (progn
14103 (org-back-to-heading t)
14104 (while (not (equal lastpos (point)))
14105 (setq lastpos (point))
14106 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14107 (setq ltags (org-split-string
14108 (match-string-no-properties 1) ":"))
14109 (when parent
14110 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14111 (setq tags (append
14112 (if parent
14113 (org-remove-uninherited-tags ltags)
14114 ltags)
14115 tags)))
14116 (or org-use-tag-inheritance (throw 'done t))
14117 (when local (throw 'done t))
14118 (or (org-up-heading-safe) (error nil))
14119 (setq parent t)))
14120 (error nil)))))
14121 (if local
14122 tags
14123 (reverse (delete-dups
14124 (reverse (append
14125 (org-remove-uninherited-tags
14126 org-file-tags)
14127 tags)))))))))
14129 (defun org-add-prop-inherited (s)
14130 (add-text-properties 0 (length s) '(inherited t) s)
14133 (defun org-toggle-tag (tag &optional onoff)
14134 "Toggle the tag TAG for the current line.
14135 If ONOFF is `on' or `off', don't toggle but set to this state."
14136 (save-excursion
14137 (org-back-to-heading t)
14138 (let ((current
14139 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14140 (line-end-position) t)
14141 (let ((tags (match-string 1)))
14142 ;; Clear current tags.
14143 (replace-match "")
14144 ;; Reverse the tags list so any new tag is appended to
14145 ;; the current list of tags.
14146 (nreverse (org-split-string tags ":")))))
14147 res)
14148 (pcase onoff
14149 (`off (setq current (delete tag current)))
14150 ((or `on (guard (not (member tag current))))
14151 (setq res t)
14152 (cl-pushnew tag current :test #'equal))
14153 (_ (setq current (delete tag current))))
14154 (end-of-line)
14155 (if current
14156 (progn
14157 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14158 (org-set-tags nil t))
14159 (delete-horizontal-space))
14160 (run-hooks 'org-after-tags-change-hook)
14161 res)))
14163 (defun org--align-tags-here (to-col)
14164 "Align tags on the current headline to TO-COL.
14165 Assume point is on a headline."
14166 (let ((pos (point)))
14167 (beginning-of-line)
14168 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14169 (>= pos (match-beginning 2)))
14170 ;; No tags or point within tags: do not align.
14171 (goto-char pos)
14172 (goto-char (match-beginning 1))
14173 (let ((shift (max (- (if (>= to-col 0) to-col
14174 (- (abs to-col) (string-width (match-string 2))))
14175 (current-column))
14176 1)))
14177 (replace-match (make-string shift ?\s) nil nil nil 1)
14178 ;; Preserve initial position, if possible. In any case, stop
14179 ;; before tags.
14180 (when (< pos (point)) (goto-char pos))))))
14182 (defun org-set-tags-command (&optional arg just-align)
14183 "Call the set-tags command for the current entry."
14184 (interactive "P")
14185 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14186 (org-set-tags arg just-align)
14187 (save-excursion
14188 (unless (and (org-region-active-p)
14189 org-loop-over-headlines-in-active-region)
14190 (org-back-to-heading t))
14191 (org-set-tags arg just-align))))
14193 (defun org-set-tags-to (data)
14194 "Set the tags of the current entry to DATA, replacing the current tags.
14195 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14196 If DATA is nil or the empty string, any tags will be removed."
14197 (interactive "sTags: ")
14198 (setq data
14199 (cond
14200 ((eq data nil) "")
14201 ((equal data "") "")
14202 ((stringp data)
14203 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14204 ":"))
14205 ((listp data)
14206 (concat ":" (mapconcat 'identity data ":") ":"))))
14207 (when data
14208 (save-excursion
14209 (org-back-to-heading t)
14210 (when (let ((case-fold-search nil))
14211 (looking-at org-complex-heading-regexp))
14212 (if (match-end 5)
14213 (progn
14214 (goto-char (match-beginning 5))
14215 (insert data)
14216 (delete-region (point) (point-at-eol))
14217 (org-set-tags nil 'align))
14218 (goto-char (point-at-eol))
14219 (insert " " data)
14220 (org-set-tags nil 'align)))
14221 (beginning-of-line 1)
14222 (when (looking-at ".*?\\([ \t]+\\)$")
14223 (delete-region (match-beginning 1) (match-end 1))))))
14225 (defun org-align-all-tags ()
14226 "Align the tags in all headings."
14227 (interactive)
14228 (save-excursion
14229 (or (ignore-errors (org-back-to-heading t))
14230 (outline-next-heading))
14231 (if (org-at-heading-p)
14232 (org-set-tags t)
14233 (message "No headings"))))
14235 (defvar org-indent-indentation-per-level)
14236 (defun org-set-tags (&optional arg just-align)
14237 "Set the tags for the current headline.
14238 With prefix ARG, realign all tags in headings in the current buffer.
14239 When JUST-ALIGN is non-nil, only align tags."
14240 (interactive "P")
14241 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14242 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14243 'region-start-level
14244 'region))
14245 org-loop-over-headlines-in-active-region)
14246 (org-map-entries
14247 ;; We don't use ARG and JUST-ALIGN here because these args
14248 ;; are not useful when looping over headlines.
14249 #'org-set-tags
14250 org-loop-over-headlines-in-active-region
14252 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14253 (let ((org-setting-tags t))
14254 (if arg
14255 (save-excursion
14256 (goto-char (point-min))
14257 (while (re-search-forward org-outline-regexp-bol nil t)
14258 (org-set-tags nil t)
14259 (end-of-line))
14260 (message "All tags realigned to column %d" org-tags-column))
14261 (let* ((current (org-get-tags-string))
14262 (tags
14263 (if just-align current
14264 ;; Get a new set of tags from the user.
14265 (save-excursion
14266 (let* ((seen)
14267 (table
14268 (setq
14269 org-last-tags-completion-table
14270 ;; Uniquify tags in alists, yet preserve
14271 ;; structure (i.e., keywords).
14272 (delq nil
14273 (mapcar
14274 (lambda (pair)
14275 (let ((head (car pair)))
14276 (cond ((symbolp head) pair)
14277 ((member head seen) nil)
14278 (t (push head seen)
14279 pair))))
14280 (append
14281 (or org-current-tag-alist
14282 (org-get-buffer-tags))
14283 (and
14284 org-complete-tags-always-offer-all-agenda-tags
14285 (org-global-tags-completion-table
14286 (org-agenda-files))))))))
14287 (current-tags (org-split-string current ":"))
14288 (inherited-tags
14289 (nreverse (nthcdr (length current-tags)
14290 (nreverse (org-get-tags-at))))))
14291 (replace-regexp-in-string
14292 "\\([-+&]+\\|,\\)"
14294 (if (or (eq t org-use-fast-tag-selection)
14295 (and org-use-fast-tag-selection
14296 (delq nil (mapcar #'cdr table))))
14297 (org-fast-tag-selection
14298 current-tags inherited-tags table
14299 (and org-fast-tag-selection-include-todo
14300 org-todo-key-alist))
14301 (let ((org-add-colon-after-tag-completion
14302 (< 1 (length table))))
14303 (org-trim
14304 (completing-read
14305 "Tags: "
14306 #'org-tags-completion-function
14307 nil nil current 'org-tags-history))))))))))
14309 (when org-tags-sort-function
14310 (setq tags
14311 (mapconcat
14312 #'identity
14313 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14314 org-tags-sort-function)
14315 ":")))
14317 (if (or (string= ":" tags)
14318 (string= "::" tags))
14319 (setq tags ""))
14320 (if (not (org-string-nw-p tags)) (setq tags "")
14321 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14322 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14324 ;; Insert new tags at the correct column.
14325 (unless (equal current tags)
14326 (save-excursion
14327 (beginning-of-line)
14328 (let ((case-fold-search nil))
14329 (looking-at org-complex-heading-regexp))
14330 ;; Remove current tags, if any.
14331 (when (match-end 5) (replace-match "" nil nil nil 5))
14332 ;; Insert new tags, if any. Otherwise, remove trailing
14333 ;; white spaces.
14334 (end-of-line)
14335 (if (not (equal tags ""))
14336 ;; When text is being inserted on an invisible
14337 ;; region boundary, it can be inadvertently sucked
14338 ;; into invisibility.
14339 (org-flag-region (point) (progn (insert " " tags) (point))
14341 'outline)
14342 (skip-chars-backward " \t")
14343 (delete-region (point) (line-end-position)))))
14344 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14345 ;; is on.
14346 (unless (equal tags "")
14347 (let* ((level (save-excursion
14348 (beginning-of-line)
14349 (skip-chars-forward "\\*")))
14350 (offset (if (bound-and-true-p org-indent-mode)
14351 (* (1- org-indent-indentation-per-level)
14352 (1- level))
14354 (tags-column
14355 (+ org-tags-column
14356 (if (> org-tags-column 0) (- offset) offset))))
14357 (org--align-tags-here tags-column))))
14358 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14360 (defun org-change-tag-in-region (beg end tag off)
14361 "Add or remove TAG for each entry in the region.
14362 This works in the agenda, and also in an Org buffer."
14363 (interactive
14364 (list (region-beginning) (region-end)
14365 (let ((org-last-tags-completion-table
14366 (if (derived-mode-p 'org-mode)
14367 (org-uniquify
14368 (delq nil (append (org-get-buffer-tags)
14369 (org-global-tags-completion-table))))
14370 (org-global-tags-completion-table))))
14371 (completing-read
14372 "Tag: " 'org-tags-completion-function nil nil nil
14373 'org-tags-history))
14374 (progn
14375 (message "[s]et or [r]emove? ")
14376 (equal (read-char-exclusive) ?r))))
14377 (when (fboundp 'deactivate-mark) (deactivate-mark))
14378 (let ((agendap (equal major-mode 'org-agenda-mode))
14379 l1 l2 m buf pos newhead (cnt 0))
14380 (goto-char end)
14381 (setq l2 (1- (org-current-line)))
14382 (goto-char beg)
14383 (setq l1 (org-current-line))
14384 (cl-loop for l from l1 to l2 do
14385 (org-goto-line l)
14386 (setq m (get-text-property (point) 'org-hd-marker))
14387 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14388 (and agendap m))
14389 (setq buf (if agendap (marker-buffer m) (current-buffer))
14390 pos (if agendap m (point)))
14391 (with-current-buffer buf
14392 (save-excursion
14393 (save-restriction
14394 (goto-char pos)
14395 (setq cnt (1+ cnt))
14396 (org-toggle-tag tag (if off 'off 'on))
14397 (setq newhead (org-get-heading)))))
14398 (and agendap (org-agenda-change-all-lines newhead m))))
14399 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14401 (defun org-tags-completion-function (string _predicate &optional flag)
14402 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14403 (confirm (lambda (x) (stringp (car x)))))
14404 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14405 (setq s1 (match-string 1 string)
14406 s2 (match-string 2 string))
14407 (setq s1 "" s2 string))
14408 (cond
14409 ((eq flag nil)
14410 ;; try completion
14411 (setq rtn (try-completion s2 ctable confirm))
14412 (when (stringp rtn)
14413 (setq rtn
14414 (concat s1 s2 (substring rtn (length s2))
14415 (if (and org-add-colon-after-tag-completion
14416 (assoc rtn ctable))
14417 ":" ""))))
14418 rtn)
14419 ((eq flag t)
14420 ;; all-completions
14421 (all-completions s2 ctable confirm))
14422 ((eq flag 'lambda)
14423 ;; exact match?
14424 (assoc s2 ctable)))))
14426 (defun org-fast-tag-insert (kwd tags face &optional end)
14427 "Insert KDW, and the TAGS, the latter with face FACE.
14428 Also insert END."
14429 (insert (format "%-12s" (concat kwd ":"))
14430 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14431 (or end "")))
14433 (defun org-fast-tag-show-exit (flag)
14434 (save-excursion
14435 (org-goto-line 3)
14436 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14437 (replace-match ""))
14438 (when flag
14439 (end-of-line 1)
14440 (org-move-to-column (- (window-width) 19) t)
14441 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14443 (defun org-set-current-tags-overlay (current prefix)
14444 "Add an overlay to CURRENT tag with PREFIX."
14445 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14446 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14447 (org-overlay-display org-tags-overlay (concat prefix s))))
14449 (defvar org-last-tag-selection-key nil)
14450 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14451 "Fast tag selection with single keys.
14452 CURRENT is the current list of tags in the headline, INHERITED is the
14453 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14454 possibly with grouping information. TODO-TABLE is a similar table with
14455 TODO keywords, should these have keys assigned to them.
14456 If the keys are nil, a-z are automatically assigned.
14457 Returns the new tags string, or nil to not change the current settings."
14458 (let* ((fulltable (append table todo-table))
14459 (maxlen (apply 'max (mapcar
14460 (lambda (x)
14461 (if (stringp (car x)) (string-width (car x)) 0))
14462 fulltable)))
14463 (buf (current-buffer))
14464 (expert (eq org-fast-tag-selection-single-key 'expert))
14465 (buffer-tags nil)
14466 (fwidth (+ maxlen 3 1 3))
14467 (ncol (/ (- (window-width) 4) fwidth))
14468 (i-face 'org-done)
14469 (c-face 'org-todo)
14470 tg cnt e c char c1 c2 ntable tbl rtn
14471 ov-start ov-end ov-prefix
14472 (exit-after-next org-fast-tag-selection-single-key)
14473 (done-keywords org-done-keywords)
14474 groups ingroup intaggroup)
14475 (save-excursion
14476 (beginning-of-line 1)
14477 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14478 (setq ov-start (match-beginning 1)
14479 ov-end (match-end 1)
14480 ov-prefix "")
14481 (setq ov-start (1- (point-at-eol))
14482 ov-end (1+ ov-start))
14483 (skip-chars-forward "^\n\r")
14484 (setq ov-prefix
14485 (concat
14486 (buffer-substring (1- (point)) (point))
14487 (if (> (current-column) org-tags-column)
14489 (make-string (- org-tags-column (current-column)) ?\ ))))))
14490 (move-overlay org-tags-overlay ov-start ov-end)
14491 (save-window-excursion
14492 (if expert
14493 (set-buffer (get-buffer-create " *Org tags*"))
14494 (delete-other-windows)
14495 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14496 (org-switch-to-buffer-other-window " *Org tags*"))
14497 (erase-buffer)
14498 (setq-local org-done-keywords done-keywords)
14499 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14500 (org-fast-tag-insert "Current" current c-face "\n\n")
14501 (org-fast-tag-show-exit exit-after-next)
14502 (org-set-current-tags-overlay current ov-prefix)
14503 (setq tbl fulltable char ?a cnt 0)
14504 (while (setq e (pop tbl))
14505 (cond
14506 ((eq (car e) :startgroup)
14507 (push '() groups) (setq ingroup t)
14508 (unless (zerop cnt)
14509 (setq cnt 0)
14510 (insert "\n"))
14511 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14512 ((eq (car e) :endgroup)
14513 (setq ingroup nil cnt 0)
14514 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14515 ((eq (car e) :startgrouptag)
14516 (setq intaggroup t)
14517 (unless (zerop cnt)
14518 (setq cnt 0)
14519 (insert "\n"))
14520 (insert "[ "))
14521 ((eq (car e) :endgrouptag)
14522 (setq intaggroup nil cnt 0)
14523 (insert "]\n"))
14524 ((equal e '(:newline))
14525 (unless (zerop cnt)
14526 (setq cnt 0)
14527 (insert "\n")
14528 (setq e (car tbl))
14529 (while (equal (car tbl) '(:newline))
14530 (insert "\n")
14531 (setq tbl (cdr tbl)))))
14532 ((equal e '(:grouptags)) (insert " : "))
14534 (setq tg (copy-sequence (car e)) c2 nil)
14535 (if (cdr e)
14536 (setq c (cdr e))
14537 ;; automatically assign a character.
14538 (setq c1 (string-to-char
14539 (downcase (substring
14540 tg (if (= (string-to-char tg) ?@) 1 0)))))
14541 (if (or (rassoc c1 ntable) (rassoc c1 table))
14542 (while (or (rassoc char ntable) (rassoc char table))
14543 (setq char (1+ char)))
14544 (setq c2 c1))
14545 (setq c (or c2 char)))
14546 (when ingroup (push tg (car groups)))
14547 (setq tg (org-add-props tg nil 'face
14548 (cond
14549 ((not (assoc tg table))
14550 (org-get-todo-face tg))
14551 ((member tg current) c-face)
14552 ((member tg inherited) i-face))))
14553 (when (equal (caar tbl) :grouptags)
14554 (org-add-props tg nil 'face 'org-tag-group))
14555 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14556 (insert "[" c "] " tg (make-string
14557 (- fwidth 4 (length tg)) ?\ ))
14558 (push (cons tg c) ntable)
14559 (when (= (cl-incf cnt) ncol)
14560 (insert "\n")
14561 (when (or ingroup intaggroup) (insert " "))
14562 (setq cnt 0)))))
14563 (setq ntable (nreverse ntable))
14564 (insert "\n")
14565 (goto-char (point-min))
14566 (unless expert (org-fit-window-to-buffer))
14567 (setq rtn
14568 (catch 'exit
14569 (while t
14570 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14571 (if (not groups) "no " "")
14572 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14573 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14574 (setq org-last-tag-selection-key c)
14575 (cond
14576 ((= c ?\r) (throw 'exit t))
14577 ((= c ?!)
14578 (setq groups (not groups))
14579 (goto-char (point-min))
14580 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14581 ((= c ?\C-c)
14582 (if (not expert)
14583 (org-fast-tag-show-exit
14584 (setq exit-after-next (not exit-after-next)))
14585 (setq expert nil)
14586 (delete-other-windows)
14587 (set-window-buffer (split-window-vertically) " *Org tags*")
14588 (org-switch-to-buffer-other-window " *Org tags*")
14589 (org-fit-window-to-buffer)))
14590 ((or (= c ?\C-g)
14591 (and (= c ?q) (not (rassoc c ntable))))
14592 (delete-overlay org-tags-overlay)
14593 (setq quit-flag t))
14594 ((= c ?\ )
14595 (setq current nil)
14596 (when exit-after-next (setq exit-after-next 'now)))
14597 ((= c ?\t)
14598 (condition-case nil
14599 (setq tg (completing-read
14600 "Tag: "
14601 (or buffer-tags
14602 (with-current-buffer buf
14603 (setq buffer-tags
14604 (org-get-buffer-tags))))))
14605 (quit (setq tg "")))
14606 (when (string-match "\\S-" tg)
14607 (cl-pushnew (list tg) buffer-tags :test #'equal)
14608 (if (member tg current)
14609 (setq current (delete tg current))
14610 (push tg current)))
14611 (when exit-after-next (setq exit-after-next 'now)))
14612 ((setq e (rassoc c todo-table) tg (car e))
14613 (with-current-buffer buf
14614 (save-excursion (org-todo tg)))
14615 (when exit-after-next (setq exit-after-next 'now)))
14616 ((setq e (rassoc c ntable) tg (car e))
14617 (if (member tg current)
14618 (setq current (delete tg current))
14619 (cl-loop for g in groups do
14620 (when (member tg g)
14621 (dolist (x g) (setq current (delete x current)))))
14622 (push tg current))
14623 (when exit-after-next (setq exit-after-next 'now))))
14625 ;; Create a sorted list
14626 (setq current
14627 (sort current
14628 (lambda (a b)
14629 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14630 (when (eq exit-after-next 'now) (throw 'exit t))
14631 (goto-char (point-min))
14632 (beginning-of-line 2)
14633 (delete-region (point) (point-at-eol))
14634 (org-fast-tag-insert "Current" current c-face)
14635 (org-set-current-tags-overlay current ov-prefix)
14636 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14637 (setq tg (match-string 1))
14638 (add-text-properties
14639 (match-beginning 1) (match-end 1)
14640 (list 'face
14641 (cond
14642 ((member tg current) c-face)
14643 ((member tg inherited) i-face)
14644 (t (get-text-property (match-beginning 1) 'face))))))
14645 (goto-char (point-min)))))
14646 (delete-overlay org-tags-overlay)
14647 (if rtn
14648 (mapconcat 'identity current ":")
14649 nil))))
14651 (defun org-get-tags-string ()
14652 "Get the TAGS string in the current headline."
14653 (unless (org-at-heading-p t)
14654 (user-error "Not on a heading"))
14655 (save-excursion
14656 (beginning-of-line 1)
14657 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14658 (match-string-no-properties 1)
14659 "")))
14661 (defun org-get-tags ()
14662 "Get the list of tags specified in the current headline."
14663 (org-split-string (org-get-tags-string) ":"))
14665 (defun org-get-buffer-tags ()
14666 "Get a table of all tags used in the buffer, for completion."
14667 (org-with-wide-buffer
14668 (goto-char (point-min))
14669 (let ((tag-re (concat org-outline-regexp-bol
14670 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14671 tags)
14672 (while (re-search-forward tag-re nil t)
14673 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14674 (push tag tags)))
14675 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14677 ;;;; The mapping API
14679 (defvar org-agenda-skip-comment-trees)
14680 (defvar org-agenda-skip-function)
14681 (defun org-map-entries (func &optional match scope &rest skip)
14682 "Call FUNC at each headline selected by MATCH in SCOPE.
14684 FUNC is a function or a lisp form. The function will be called without
14685 arguments, with the cursor positioned at the beginning of the headline.
14686 The return values of all calls to the function will be collected and
14687 returned as a list.
14689 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14690 does not need to preserve point. After evaluation, the cursor will be
14691 moved to the end of the line (presumably of the headline of the
14692 processed entry) and search continues from there. Under some
14693 circumstances, this may not produce the wanted results. For example,
14694 if you have removed (e.g. archived) the current (sub)tree it could
14695 mean that the next entry will be skipped entirely. In such cases, you
14696 can specify the position from where search should continue by making
14697 FUNC set the variable `org-map-continue-from' to the desired buffer
14698 position.
14700 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14701 Only headlines that are matched by this query will be considered during
14702 the iteration. When MATCH is nil or t, all headlines will be
14703 visited by the iteration.
14705 SCOPE determines the scope of this command. It can be any of:
14707 nil The current buffer, respecting the restriction if any
14708 tree The subtree started with the entry at point
14709 region The entries within the active region, if any
14710 region-start-level
14711 The entries within the active region, but only those at
14712 the same level than the first one.
14713 file The current buffer, without restriction
14714 file-with-archives
14715 The current buffer, and any archives associated with it
14716 agenda All agenda files
14717 agenda-with-archives
14718 All agenda files with any archive files associated with them
14719 \(file1 file2 ...)
14720 If this is a list, all files in the list will be scanned
14722 The remaining args are treated as settings for the skipping facilities of
14723 the scanner. The following items can be given here:
14725 archive skip trees with the archive tag
14726 comment skip trees with the COMMENT keyword
14727 function or Emacs Lisp form:
14728 will be used as value for `org-agenda-skip-function', so
14729 whenever the function returns a position, FUNC will not be
14730 called for that entry and search will continue from the
14731 position returned
14733 If your function needs to retrieve the tags including inherited tags
14734 at the *current* entry, you can use the value of the variable
14735 `org-scanner-tags' which will be much faster than getting the value
14736 with `org-get-tags-at'. If your function gets properties with
14737 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14738 to t around the call to `org-entry-properties' to get the same speedup.
14739 Note that if your function moves around to retrieve tags and properties at
14740 a *different* entry, you cannot use these techniques."
14741 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14742 (not (org-region-active-p)))
14743 (let* ((org-agenda-archives-mode nil) ; just to make sure
14744 (org-agenda-skip-archived-trees (memq 'archive skip))
14745 (org-agenda-skip-comment-trees (memq 'comment skip))
14746 (org-agenda-skip-function
14747 (car (org-delete-all '(comment archive) skip)))
14748 (org-tags-match-list-sublevels t)
14749 (start-level (eq scope 'region-start-level))
14750 matcher res
14751 org-todo-keywords-for-agenda
14752 org-done-keywords-for-agenda
14753 org-todo-keyword-alist-for-agenda
14754 org-tag-alist-for-agenda
14755 org--matcher-tags-todo-only)
14757 (cond
14758 ((eq match t) (setq matcher t))
14759 ((eq match nil) (setq matcher t))
14760 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14762 (save-excursion
14763 (save-restriction
14764 (cond ((eq scope 'tree)
14765 (org-back-to-heading t)
14766 (org-narrow-to-subtree)
14767 (setq scope nil))
14768 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14769 (org-region-active-p))
14770 ;; If needed, set start-level to a string like "2"
14771 (when start-level
14772 (save-excursion
14773 (goto-char (region-beginning))
14774 (unless (org-at-heading-p) (outline-next-heading))
14775 (setq start-level (org-current-level))))
14776 (narrow-to-region (region-beginning)
14777 (save-excursion
14778 (goto-char (region-end))
14779 (unless (and (bolp) (org-at-heading-p))
14780 (outline-next-heading))
14781 (point)))
14782 (setq scope nil)))
14784 (if (not scope)
14785 (progn
14786 (org-agenda-prepare-buffers
14787 (and buffer-file-name (list buffer-file-name)))
14788 (setq res
14789 (org-scan-tags
14790 func matcher org--matcher-tags-todo-only start-level)))
14791 ;; Get the right scope
14792 (cond
14793 ((and scope (listp scope) (symbolp (car scope)))
14794 (setq scope (eval scope)))
14795 ((eq scope 'agenda)
14796 (setq scope (org-agenda-files t)))
14797 ((eq scope 'agenda-with-archives)
14798 (setq scope (org-agenda-files t))
14799 (setq scope (org-add-archive-files scope)))
14800 ((eq scope 'file)
14801 (setq scope (and buffer-file-name (list buffer-file-name))))
14802 ((eq scope 'file-with-archives)
14803 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14804 (org-agenda-prepare-buffers scope)
14805 (dolist (file scope)
14806 (with-current-buffer (org-find-base-buffer-visiting file)
14807 (org-with-wide-buffer
14808 (goto-char (point-min))
14809 (setq res
14810 (append
14812 (org-scan-tags
14813 func matcher org--matcher-tags-todo-only)))))))))
14814 res)))
14816 ;;; Properties API
14818 (defconst org-special-properties
14819 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14820 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14821 "The special properties valid in Org mode.
14822 These are properties that are not defined in the property drawer,
14823 but in some other way.")
14825 (defconst org-default-properties
14826 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14827 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14828 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14829 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14830 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14831 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14832 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14833 "Some properties that are used by Org mode for various purposes.
14834 Being in this list makes sure that they are offered for completion.")
14836 (defun org--valid-property-p (property)
14837 "Non nil when string PROPERTY is a valid property name."
14838 (not
14839 (or (equal property "")
14840 (string-match-p "\\s-" property))))
14842 (defun org--update-property-plist (key val props)
14843 "Associate KEY to VAL in alist PROPS.
14844 Modifications are made by side-effect. Return new alist."
14845 (let* ((appending (string= (substring key -1) "+"))
14846 (key (if appending (substring key 0 -1) key))
14847 (old (assoc-string key props t)))
14848 (if (not old) (cons (cons key val) props)
14849 (setcdr old (if appending (concat (cdr old) " " val) val))
14850 props)))
14852 (defun org-get-property-block (&optional beg force)
14853 "Return the (beg . end) range of the body of the property drawer.
14854 BEG is the beginning of the current subtree, or of the part
14855 before the first headline. If it is not given, it will be found.
14856 If the drawer does not exist, create it if FORCE is non-nil, or
14857 return nil."
14858 (org-with-wide-buffer
14859 (when beg (goto-char beg))
14860 (unless (org-before-first-heading-p)
14861 (let ((beg (cond (beg)
14862 ((or (not (featurep 'org-inlinetask))
14863 (org-inlinetask-in-task-p))
14864 (org-back-to-heading t))
14865 (t (org-with-limited-levels (org-back-to-heading t))))))
14866 (forward-line)
14867 (when (looking-at-p org-planning-line-re) (forward-line))
14868 (cond ((looking-at org-property-drawer-re)
14869 (forward-line)
14870 (cons (point) (progn (goto-char (match-end 0))
14871 (line-beginning-position))))
14872 (force
14873 (goto-char beg)
14874 (org-insert-property-drawer)
14875 (let ((pos (save-excursion (search-forward ":END:")
14876 (line-beginning-position))))
14877 (cons pos pos))))))))
14879 (defun org-at-property-p ()
14880 "Non-nil when point is inside a property drawer.
14881 See `org-property-re' for match data, if applicable."
14882 (save-excursion
14883 (beginning-of-line)
14884 (and (looking-at org-property-re)
14885 (let ((property-drawer (save-match-data (org-get-property-block))))
14886 (and property-drawer
14887 (>= (point) (car property-drawer))
14888 (< (point) (cdr property-drawer)))))))
14890 (defun org-property-action ()
14891 "Do an action on properties."
14892 (interactive)
14893 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14894 (let ((c (read-char-exclusive)))
14895 (cl-case c
14896 (?s (call-interactively #'org-set-property))
14897 (?d (call-interactively #'org-delete-property))
14898 (?D (call-interactively #'org-delete-property-globally))
14899 (?c (call-interactively #'org-compute-property-at-point))
14900 (otherwise (user-error "No such property action %c" c)))))
14902 (defun org-inc-effort ()
14903 "Increment the value of the effort property in the current entry."
14904 (interactive)
14905 (org-set-effort t))
14907 (defvar org-clock-effort) ; Defined in org-clock.el.
14908 (defvar org-clock-current-task) ; Defined in org-clock.el.
14909 (defun org-set-effort (&optional increment value)
14910 "Set the effort property of the current entry.
14911 If INCREMENT is non-nil, set the property to the next allowed
14912 value. Otherwise, if optional argument VALUE is provided, use
14913 it. Eventually, prompt for the new value if none of the previous
14914 variables is set."
14915 (interactive "P")
14916 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14917 (current (org-entry-get nil org-effort-property))
14918 (value
14919 (cond
14920 (increment
14921 (unless allowed (user-error "Allowed effort values are not set"))
14922 (or (cl-caadr (member (list current) allowed))
14923 (user-error "Unknown value %S among allowed values" current)))
14924 (value
14925 (if (stringp value) value
14926 (error "Invalid effort value: %S" value)))
14928 (let ((must-match
14929 (and allowed
14930 (not (get-text-property 0 'org-unrestricted
14931 (caar allowed))))))
14932 (completing-read "Effort: " allowed nil must-match))))))
14933 (unless (equal current value)
14934 (org-entry-put nil org-effort-property value))
14935 (org-refresh-property '((effort . identity)
14936 (effort-minutes . org-duration-to-minutes))
14937 value)
14938 (when (equal (org-get-heading t t t t)
14939 (bound-and-true-p org-clock-current-task))
14940 (setq org-clock-effort (org-get-at-bol 'effort))
14941 (org-clock-update-mode-line))
14942 (message "%s is now %s" org-effort-property value)))
14944 (defun org-entry-properties (&optional pom which)
14945 "Get all properties of the current entry.
14947 When POM is a buffer position, get all properties from the entry
14948 there instead.
14950 This includes the TODO keyword, the tags, time strings for
14951 deadline, scheduled, and clocking, and any additional properties
14952 defined in the entry.
14954 If WHICH is nil or `all', get all properties. If WHICH is
14955 `special' or `standard', only get that subclass. If WHICH is
14956 a string, only get that property.
14958 Return value is an alist. Keys are properties, as upcased
14959 strings."
14960 (org-with-point-at pom
14961 (when (and (derived-mode-p 'org-mode)
14962 (ignore-errors (org-back-to-heading t)))
14963 (catch 'exit
14964 (let* ((beg (point))
14965 (specific (and (stringp which) (upcase which)))
14966 (which (cond ((not specific) which)
14967 ((member specific org-special-properties) 'special)
14968 (t 'standard)))
14969 props)
14970 ;; Get the special properties, like TODO and TAGS.
14971 (when (memq which '(nil all special))
14972 (when (or (not specific) (string= specific "CLOCKSUM"))
14973 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
14974 (when clocksum
14975 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
14976 props)))
14977 (when specific (throw 'exit props)))
14978 (when (or (not specific) (string= specific "CLOCKSUM_T"))
14979 (let ((clocksumt (get-text-property (point)
14980 :org-clock-minutes-today)))
14981 (when clocksumt
14982 (push (cons "CLOCKSUM_T"
14983 (org-duration-from-minutes clocksumt))
14984 props)))
14985 (when specific (throw 'exit props)))
14986 (when (or (not specific) (string= specific "ITEM"))
14987 (let ((case-fold-search nil))
14988 (when (looking-at org-complex-heading-regexp)
14989 (push (cons "ITEM"
14990 (let ((title (match-string-no-properties 4)))
14991 (if (org-string-nw-p title)
14992 (org-remove-tabs title)
14993 "")))
14994 props)))
14995 (when specific (throw 'exit props)))
14996 (when (or (not specific) (string= specific "TODO"))
14997 (let ((case-fold-search nil))
14998 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14999 (push (cons "TODO" (match-string-no-properties 2)) props)))
15000 (when specific (throw 'exit props)))
15001 (when (or (not specific) (string= specific "PRIORITY"))
15002 (push (cons "PRIORITY"
15003 (if (looking-at org-priority-regexp)
15004 (match-string-no-properties 2)
15005 (char-to-string org-default-priority)))
15006 props)
15007 (when specific (throw 'exit props)))
15008 (when (or (not specific) (string= specific "FILE"))
15009 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15010 props)
15011 (when specific (throw 'exit props)))
15012 (when (or (not specific) (string= specific "TAGS"))
15013 (let ((value (org-string-nw-p (org-get-tags-string))))
15014 (when value (push (cons "TAGS" value) props)))
15015 (when specific (throw 'exit props)))
15016 (when (or (not specific) (string= specific "ALLTAGS"))
15017 (let ((value (org-get-tags-at)))
15018 (when value
15019 (push (cons "ALLTAGS"
15020 (format ":%s:" (mapconcat #'identity value ":")))
15021 props)))
15022 (when specific (throw 'exit props)))
15023 (when (or (not specific) (string= specific "BLOCKED"))
15024 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15025 (when specific (throw 'exit props)))
15026 (when (or (not specific)
15027 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15028 (forward-line)
15029 (when (looking-at-p org-planning-line-re)
15030 (end-of-line)
15031 (let ((bol (line-beginning-position))
15032 ;; Backward compatibility: time keywords used to
15033 ;; be configurable (before 8.3). Make sure we
15034 ;; get the correct keyword.
15035 (key-assoc `(("CLOSED" . ,org-closed-string)
15036 ("DEADLINE" . ,org-deadline-string)
15037 ("SCHEDULED" . ,org-scheduled-string))))
15038 (dolist (pair (if specific (list (assoc specific key-assoc))
15039 key-assoc))
15040 (save-excursion
15041 (when (search-backward (cdr pair) bol t)
15042 (goto-char (match-end 0))
15043 (skip-chars-forward " \t")
15044 (and (looking-at org-ts-regexp-both)
15045 (push (cons (car pair)
15046 (match-string-no-properties 0))
15047 props)))))))
15048 (when specific (throw 'exit props)))
15049 (when (or (not specific)
15050 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15051 (let ((find-ts
15052 (lambda (end ts)
15053 ;; Fix next time-stamp before END. TS is the
15054 ;; list of time-stamps found so far.
15055 (let ((ts ts)
15056 (regexp (cond
15057 ((string= specific "TIMESTAMP")
15058 org-ts-regexp)
15059 ((string= specific "TIMESTAMP_IA")
15060 org-ts-regexp-inactive)
15061 ((assoc "TIMESTAMP_IA" ts)
15062 org-ts-regexp)
15063 ((assoc "TIMESTAMP" ts)
15064 org-ts-regexp-inactive)
15065 (t org-ts-regexp-both))))
15066 (catch 'next
15067 (while (re-search-forward regexp end t)
15068 (backward-char)
15069 (let ((object (org-element-context)))
15070 ;; Accept to match timestamps in node
15071 ;; properties, too.
15072 (when (memq (org-element-type object)
15073 '(node-property timestamp))
15074 (let ((type
15075 (org-element-property :type object)))
15076 (cond
15077 ((and (memq type '(active active-range))
15078 (not (equal specific "TIMESTAMP_IA")))
15079 (unless (assoc "TIMESTAMP" ts)
15080 (push (cons "TIMESTAMP"
15081 (org-element-property
15082 :raw-value object))
15084 (when specific (throw 'exit ts))))
15085 ((and (memq type '(inactive inactive-range))
15086 (not (string= specific "TIMESTAMP")))
15087 (unless (assoc "TIMESTAMP_IA" ts)
15088 (push (cons "TIMESTAMP_IA"
15089 (org-element-property
15090 :raw-value object))
15092 (when specific (throw 'exit ts))))))
15093 ;; Both timestamp types are found,
15094 ;; move to next part.
15095 (when (= (length ts) 2) (throw 'next ts)))))
15096 ts)))))
15097 (goto-char beg)
15098 ;; First look for timestamps within headline.
15099 (let ((ts (funcall find-ts (line-end-position) nil)))
15100 (if (= (length ts) 2) (setq props (nconc ts props))
15101 ;; Then find timestamps in the section, skipping
15102 ;; planning line.
15103 (let ((end (save-excursion (outline-next-heading))))
15104 (forward-line)
15105 (when (looking-at-p org-planning-line-re) (forward-line))
15106 (setq props (nconc (funcall find-ts end ts) props))))))))
15107 ;; Get the standard properties, like :PROP:.
15108 (when (memq which '(nil all standard))
15109 ;; If we are looking after a specific property, delegate
15110 ;; to `org-entry-get', which is faster. However, make an
15111 ;; exception for "CATEGORY", since it can be also set
15112 ;; through keywords (i.e. #+CATEGORY).
15113 (if (and specific (not (equal specific "CATEGORY")))
15114 (let ((value (org-entry-get beg specific nil t)))
15115 (throw 'exit (and value (list (cons specific value)))))
15116 (let ((range (org-get-property-block beg)))
15117 (when range
15118 (let ((end (cdr range)) seen-base)
15119 (goto-char (car range))
15120 ;; Unlike to `org--update-property-plist', we
15121 ;; handle the case where base values is found
15122 ;; after its extension. We also forbid standard
15123 ;; properties to be named as special properties.
15124 (while (re-search-forward org-property-re end t)
15125 (let* ((key (upcase (match-string-no-properties 2)))
15126 (extendp (string-match-p "\\+\\'" key))
15127 (key-base (if extendp (substring key 0 -1) key))
15128 (value (match-string-no-properties 3)))
15129 (cond
15130 ((member-ignore-case key-base org-special-properties))
15131 (extendp
15132 (setq props
15133 (org--update-property-plist key value props)))
15134 ((member key seen-base))
15135 (t (push key seen-base)
15136 (let ((p (assoc-string key props t)))
15137 (if p (setcdr p (concat value " " (cdr p)))
15138 (push (cons key value) props))))))))))))
15139 (unless (assoc "CATEGORY" props)
15140 (push (cons "CATEGORY" (org-get-category beg)) props)
15141 (when (string= specific "CATEGORY") (throw 'exit props)))
15142 ;; Return value.
15143 props)))))
15145 (defun org--property-local-values (property literal-nil)
15146 "Return value for PROPERTY in current entry.
15147 Value is a list whose car is the base value for PROPERTY and cdr
15148 a list of accumulated values. Return nil if neither is found in
15149 the entry. Also return nil when PROPERTY is set to \"nil\",
15150 unless LITERAL-NIL is non-nil."
15151 (let ((range (org-get-property-block)))
15152 (when range
15153 (goto-char (car range))
15154 (let* ((case-fold-search t)
15155 (end (cdr range))
15156 (value
15157 ;; Base value.
15158 (save-excursion
15159 (let ((v (and (re-search-forward
15160 (org-re-property property nil t) end t)
15161 (match-string-no-properties 3))))
15162 (list (if literal-nil v (org-not-nil v)))))))
15163 ;; Find additional values.
15164 (let* ((property+ (org-re-property (concat property "+") nil t)))
15165 (while (re-search-forward property+ end t)
15166 (push (match-string-no-properties 3) value)))
15167 ;; Return final values.
15168 (and (not (equal value '(nil))) (nreverse value))))))
15170 (defun org--property-global-value (property literal-nil)
15171 "Return value for PROPERTY in current buffer.
15172 Return value is a string. Return nil if property is not set
15173 globally. Also return nil when PROPERTY is set to \"nil\",
15174 unless LITERAL-NIL is non-nil."
15175 (let ((global
15176 (cdr (or (assoc-string property org-file-properties t)
15177 (assoc-string property org-global-properties t)
15178 (assoc-string property org-global-properties-fixed t)))))
15179 (if literal-nil global (org-not-nil global))))
15181 (defun org-entry-get (pom property &optional inherit literal-nil)
15182 "Get value of PROPERTY for entry or content at point-or-marker POM.
15184 If INHERIT is non-nil and the entry does not have the property,
15185 then also check higher levels of the hierarchy. If INHERIT is
15186 the symbol `selective', use inheritance only if the setting in
15187 `org-use-property-inheritance' selects PROPERTY for inheritance.
15189 If the property is present but empty, the return value is the
15190 empty string. If the property is not present at all, nil is
15191 returned. In any other case, return the value as a string.
15192 Search is case-insensitive.
15194 If LITERAL-NIL is set, return the string value \"nil\" as
15195 a string, do not interpret it as the list atom nil. This is used
15196 for inheritance when a \"nil\" value can supersede a non-nil
15197 value higher up the hierarchy."
15198 (org-with-point-at pom
15199 (cond
15200 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15201 ;; We need a special property. Use `org-entry-properties' to
15202 ;; retrieve it, but specify the wanted property.
15203 (cdr (assoc-string property (org-entry-properties nil property))))
15204 ((and inherit
15205 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15206 (org-entry-get-with-inheritance property literal-nil))
15208 (let* ((local (org--property-local-values property literal-nil))
15209 (value (and local (mapconcat #'identity (delq nil local) " "))))
15210 (if literal-nil value (org-not-nil value)))))))
15212 (defun org-property-or-variable-value (var &optional inherit)
15213 "Check if there is a property fixing the value of VAR.
15214 If yes, return this value. If not, return the current value of the variable."
15215 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15216 (if (and prop (stringp prop) (string-match "\\S-" prop))
15217 (read prop)
15218 (symbol-value var))))
15220 (defun org-entry-delete (pom property)
15221 "Delete PROPERTY from entry at point-or-marker POM.
15222 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15223 non-nil when a property was removed."
15224 (org-with-point-at pom
15225 (pcase (org-get-property-block)
15226 (`(,begin . ,origin)
15227 (let* ((end (copy-marker origin))
15228 (re (org-re-property
15229 (concat (regexp-quote property) "\\+?") t t)))
15230 (goto-char begin)
15231 (while (re-search-forward re end t)
15232 (delete-region (match-beginning 0) (line-beginning-position 2)))
15233 ;; If drawer is empty, remove it altogether.
15234 (when (= begin end)
15235 (delete-region (line-beginning-position 0)
15236 (line-beginning-position 2)))
15237 ;; Return non-nil if some property was removed.
15238 (prog1 (/= end origin) (set-marker end nil))))
15239 (_ nil))))
15241 ;; Multi-values properties are properties that contain multiple values
15242 ;; These values are assumed to be single words, separated by whitespace.
15243 (defun org-entry-add-to-multivalued-property (pom property value)
15244 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15245 (let* ((old (org-entry-get pom property))
15246 (values (and old (split-string old))))
15247 (setq value (org-entry-protect-space value))
15248 (unless (member value values)
15249 (setq values (append values (list value)))
15250 (org-entry-put pom property (mapconcat #'identity values " ")))))
15252 (defun org-entry-remove-from-multivalued-property (pom property value)
15253 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15254 (let* ((old (org-entry-get pom property))
15255 (values (and old (split-string old))))
15256 (setq value (org-entry-protect-space value))
15257 (when (member value values)
15258 (setq values (delete value values))
15259 (org-entry-put pom property (mapconcat #'identity values " ")))))
15261 (defun org-entry-member-in-multivalued-property (pom property value)
15262 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15263 (let* ((old (org-entry-get pom property))
15264 (values (and old (split-string old))))
15265 (setq value (org-entry-protect-space value))
15266 (member value values)))
15268 (defun org-entry-get-multivalued-property (pom property)
15269 "Return a list of values in a multivalued property."
15270 (let* ((value (org-entry-get pom property))
15271 (values (and value (split-string value))))
15272 (mapcar #'org-entry-restore-space values)))
15274 (defun org-entry-put-multivalued-property (pom property &rest values)
15275 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15276 VALUES should be a list of strings. Spaces will be protected."
15277 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15278 (let* ((value (org-entry-get pom property))
15279 (values (and value (split-string value))))
15280 (mapcar #'org-entry-restore-space values)))
15282 (defun org-entry-protect-space (s)
15283 "Protect spaces and newline in string S."
15284 (while (string-match " " s)
15285 (setq s (replace-match "%20" t t s)))
15286 (while (string-match "\n" s)
15287 (setq s (replace-match "%0A" t t s)))
15290 (defun org-entry-restore-space (s)
15291 "Restore spaces and newline in string S."
15292 (while (string-match "%20" s)
15293 (setq s (replace-match " " t t s)))
15294 (while (string-match "%0A" s)
15295 (setq s (replace-match "\n" t t s)))
15298 (defvar org-entry-property-inherited-from (make-marker)
15299 "Marker pointing to the entry from where a property was inherited.
15300 Each call to `org-entry-get-with-inheritance' will set this marker to the
15301 location of the entry where the inheritance search matched. If there was
15302 no match, the marker will point nowhere.
15303 Note that also `org-entry-get' calls this function, if the INHERIT flag
15304 is set.")
15306 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15307 "Get PROPERTY of entry or content at point, search higher levels if needed.
15308 The search will stop at the first ancestor which has the property defined.
15309 If the value found is \"nil\", return nil to show that the property
15310 should be considered as undefined (this is the meaning of nil here).
15311 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15312 (move-marker org-entry-property-inherited-from nil)
15313 (org-with-wide-buffer
15314 (let (value)
15315 (catch 'exit
15316 (while t
15317 (let ((v (org--property-local-values property literal-nil)))
15318 (when v
15319 (setq value
15320 (concat (mapconcat #'identity (delq nil v) " ")
15321 (and value " ")
15322 value)))
15323 (cond
15324 ((car v)
15325 (org-back-to-heading t)
15326 (move-marker org-entry-property-inherited-from (point))
15327 (throw 'exit nil))
15328 ((org-up-heading-safe))
15330 (let ((global (org--property-global-value property literal-nil)))
15331 (cond ((not global))
15332 (value (setq value (concat global " " value)))
15333 (t (setq value global))))
15334 (throw 'exit nil))))))
15335 (if literal-nil value (org-not-nil value)))))
15337 (defvar org-property-changed-functions nil
15338 "Hook called when the value of a property has changed.
15339 Each hook function should accept two arguments, the name of the property
15340 and the new value.")
15342 (defun org-entry-put (pom property value)
15343 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15345 If the value is nil, it is converted to the empty string. If it
15346 is not a string, an error is raised. Also raise an error on
15347 invalid property names.
15349 PROPERTY can be any regular property (see
15350 `org-special-properties'). It can also be \"TODO\",
15351 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15353 For the last two properties, VALUE may have any of the special
15354 values \"earlier\" and \"later\". The function then increases or
15355 decreases scheduled or deadline date by one day."
15356 (cond ((null value) (setq value ""))
15357 ((not (stringp value)) (error "Properties values should be strings"))
15358 ((not (org--valid-property-p property))
15359 (user-error "Invalid property name: \"%s\"" property)))
15360 (org-with-point-at pom
15361 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15362 (org-back-to-heading t)
15363 (org-with-limited-levels (org-back-to-heading t)))
15364 (let ((beg (point)))
15365 (cond
15366 ((equal property "TODO")
15367 (cond ((not (org-string-nw-p value)) (setq value 'none))
15368 ((not (member value org-todo-keywords-1))
15369 (user-error "\"%s\" is not a valid TODO state" value)))
15370 (org-todo value)
15371 (org-set-tags nil 'align))
15372 ((equal property "PRIORITY")
15373 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15374 (org-set-tags nil 'align))
15375 ((equal property "SCHEDULED")
15376 (forward-line)
15377 (if (and (looking-at-p org-planning-line-re)
15378 (re-search-forward
15379 org-scheduled-time-regexp (line-end-position) t))
15380 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15381 ((string= value "later") (org-timestamp-change 1 'day))
15382 ((string= value "") (org-schedule '(4)))
15383 (t (org-schedule nil value)))
15384 (if (member value '("earlier" "later" ""))
15385 (call-interactively #'org-schedule)
15386 (org-schedule nil value))))
15387 ((equal property "DEADLINE")
15388 (forward-line)
15389 (if (and (looking-at-p org-planning-line-re)
15390 (re-search-forward
15391 org-deadline-time-regexp (line-end-position) t))
15392 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15393 ((string= value "later") (org-timestamp-change 1 'day))
15394 ((string= value "") (org-deadline '(4)))
15395 (t (org-deadline nil value)))
15396 (if (member value '("earlier" "later" ""))
15397 (call-interactively #'org-deadline)
15398 (org-deadline nil value))))
15399 ((member property org-special-properties)
15400 (error "The %s property cannot be set with `org-entry-put'" property))
15402 (let* ((range (org-get-property-block beg 'force))
15403 (end (cdr range))
15404 (case-fold-search t))
15405 (goto-char (car range))
15406 (if (re-search-forward (org-re-property property nil t) end t)
15407 (progn (delete-region (match-beginning 0) (match-end 0))
15408 (goto-char (match-beginning 0)))
15409 (goto-char end)
15410 (insert "\n")
15411 (backward-char))
15412 (insert ":" property ":")
15413 (when value (insert " " value))
15414 (org-indent-line)))))
15415 (run-hook-with-args 'org-property-changed-functions property value)))
15417 (defun org-buffer-property-keys (&optional specials defaults columns)
15418 "Get all property keys in the current buffer.
15420 When SPECIALS is non-nil, also list the special properties that
15421 reflect things like tags and TODO state.
15423 When DEFAULTS is non-nil, also include properties that has
15424 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15425 DESCRIPTION, LOCATION, and LOGGING and others.
15427 When COLUMNS in non-nil, also include property names given in
15428 COLUMN formats in the current buffer."
15429 (let ((case-fold-search t)
15430 (props (append
15431 (and specials org-special-properties)
15432 (and defaults (cons org-effort-property org-default-properties))
15433 nil)))
15434 (org-with-wide-buffer
15435 (goto-char (point-min))
15436 (while (re-search-forward org-property-start-re nil t)
15437 (catch :skip
15438 (let ((range (org-get-property-block)))
15439 (unless range (throw :skip nil))
15440 (goto-char (car range))
15441 (let ((begin (car range))
15442 (end (cdr range)))
15443 ;; Make sure that found property block is not located
15444 ;; before current point, as it would generate an infloop.
15445 ;; It can happen, for example, in the following
15446 ;; situation:
15448 ;; * Headline
15449 ;; :PROPERTIES:
15450 ;; ...
15451 ;; :END:
15452 ;; *************** Inlinetask
15453 ;; #+BEGIN_EXAMPLE
15454 ;; :PROPERTIES:
15455 ;; #+END_EXAMPLE
15457 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15458 (while (< (point) end)
15459 (let ((p (progn (looking-at org-property-re)
15460 (match-string-no-properties 2))))
15461 ;; Only add true property name, not extension symbol.
15462 (push (if (not (string-match-p "\\+\\'" p)) p
15463 (substring p 0 -1))
15464 props))
15465 (forward-line))))
15466 (outline-next-heading)))
15467 (when columns
15468 (goto-char (point-min))
15469 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15470 (let ((element (org-element-at-point)))
15471 (when (memq (org-element-type element) '(keyword node-property))
15472 (let ((value (org-element-property :value element))
15473 (start 0))
15474 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15475 \\(?:{[^}]+}\\)?"
15476 value start)
15477 (setq start (match-end 0))
15478 (let ((p (match-string-no-properties 1 value)))
15479 (unless (member-ignore-case p org-special-properties)
15480 (push p props))))))))))
15481 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15483 (defun org-property-values (key)
15484 "List all non-nil values of property KEY in current buffer."
15485 (org-with-wide-buffer
15486 (goto-char (point-min))
15487 (let ((case-fold-search t)
15488 (re (org-re-property key))
15489 values)
15490 (while (re-search-forward re nil t)
15491 (push (org-entry-get (point) key) values))
15492 (delete-dups values))))
15494 (defun org-insert-property-drawer ()
15495 "Insert a property drawer into the current entry."
15496 (org-with-wide-buffer
15497 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15498 (org-back-to-heading t)
15499 (org-with-limited-levels (org-back-to-heading t)))
15500 (forward-line)
15501 (when (looking-at-p org-planning-line-re) (forward-line))
15502 (unless (looking-at-p org-property-drawer-re)
15503 ;; Make sure we start editing a line from current entry, not from
15504 ;; next one. It prevents extending text properties or overlays
15505 ;; belonging to the latter.
15506 (when (bolp) (backward-char))
15507 (let ((begin (1+ (point)))
15508 (inhibit-read-only t))
15509 (insert "\n:PROPERTIES:\n:END:")
15510 (when (eobp) (insert "\n"))
15511 (org-indent-region begin (point))))))
15513 (defun org-insert-drawer (&optional arg drawer)
15514 "Insert a drawer at point.
15516 When optional argument ARG is non-nil, insert a property drawer.
15518 Optional argument DRAWER, when non-nil, is a string representing
15519 drawer's name. Otherwise, the user is prompted for a name.
15521 If a region is active, insert the drawer around that region
15522 instead.
15524 Point is left between drawer's boundaries."
15525 (interactive "P")
15526 (let* ((drawer (if arg "PROPERTIES"
15527 (or drawer (read-from-minibuffer "Drawer: ")))))
15528 (cond
15529 ;; With C-u, fall back on `org-insert-property-drawer'
15530 (arg (org-insert-property-drawer))
15531 ;; Check validity of suggested drawer's name.
15532 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15533 (user-error "Invalid drawer name"))
15534 ;; With an active region, insert a drawer at point.
15535 ((not (org-region-active-p))
15536 (progn
15537 (unless (bolp) (insert "\n"))
15538 (insert (format ":%s:\n\n:END:\n" drawer))
15539 (forward-line -2)))
15540 ;; Otherwise, insert the drawer at point
15542 (let ((rbeg (region-beginning))
15543 (rend (copy-marker (region-end))))
15544 (unwind-protect
15545 (progn
15546 (goto-char rbeg)
15547 (beginning-of-line)
15548 (when (save-excursion
15549 (re-search-forward org-outline-regexp-bol rend t))
15550 (user-error "Drawers cannot contain headlines"))
15551 ;; Position point at the beginning of the first
15552 ;; non-blank line in region. Insert drawer's opening
15553 ;; there, then indent it.
15554 (org-skip-whitespace)
15555 (beginning-of-line)
15556 (insert ":" drawer ":\n")
15557 (forward-line -1)
15558 (indent-for-tab-command)
15559 ;; Move point to the beginning of the first blank line
15560 ;; after the last non-blank line in region. Insert
15561 ;; drawer's closing, then indent it.
15562 (goto-char rend)
15563 (skip-chars-backward " \r\t\n")
15564 (insert "\n:END:")
15565 (deactivate-mark t)
15566 (indent-for-tab-command)
15567 (unless (eolp) (insert "\n")))
15568 ;; Clear marker, whatever the outcome of insertion is.
15569 (set-marker rend nil)))))))
15571 (defvar org-property-set-functions-alist nil
15572 "Property set function alist.
15573 Each entry should have the following format:
15575 (PROPERTY . READ-FUNCTION)
15577 The read function will be called with the same argument as
15578 `org-completing-read'.")
15580 (defun org-set-property-function (property)
15581 "Get the function that should be used to set PROPERTY.
15582 This is computed according to `org-property-set-functions-alist'."
15583 (or (cdr (assoc property org-property-set-functions-alist))
15584 'org-completing-read))
15586 (defun org-read-property-value (property)
15587 "Read PROPERTY value from user."
15588 (let* ((completion-ignore-case t)
15589 (allowed (org-property-get-allowed-values nil property 'table))
15590 (cur (org-entry-get nil property))
15591 (prompt (concat property " value"
15592 (if (and cur (string-match "\\S-" cur))
15593 (concat " [" cur "]") "") ": "))
15594 (set-function (org-set-property-function property))
15595 (val (if allowed
15596 (funcall set-function prompt allowed nil
15597 (not (get-text-property 0 'org-unrestricted
15598 (caar allowed))))
15599 (funcall set-function prompt
15600 (mapcar 'list (org-property-values property))
15601 nil nil "" nil cur))))
15602 (org-trim val)))
15604 (defvar org-last-set-property nil)
15605 (defvar org-last-set-property-value nil)
15606 (defun org-read-property-name ()
15607 "Read a property name."
15608 (let ((completion-ignore-case t)
15609 (default-prop (or (and (org-at-property-p)
15610 (match-string-no-properties 2))
15611 org-last-set-property)))
15612 (org-completing-read
15613 (concat "Property"
15614 (if default-prop (concat " [" default-prop "]") "")
15615 ": ")
15616 (mapcar #'list (org-buffer-property-keys nil t t))
15617 nil nil nil nil default-prop)))
15619 (defun org-set-property-and-value (use-last)
15620 "Allow to set [PROPERTY]: [value] direction from prompt.
15621 When use-default, don't even ask, just use the last
15622 \"[PROPERTY]: [value]\" string from the history."
15623 (interactive "P")
15624 (let* ((completion-ignore-case t)
15625 (pv (or (and use-last org-last-set-property-value)
15626 (org-completing-read
15627 "Enter a \"[Property]: [value]\" pair: "
15628 nil nil nil nil nil
15629 org-last-set-property-value)))
15630 prop val)
15631 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15632 (setq prop (match-string 1 pv)
15633 val (match-string 2 pv))
15634 (org-set-property prop val))))
15636 (defun org-set-property (property value)
15637 "In the current entry, set PROPERTY to VALUE.
15639 When called interactively, this will prompt for a property name, offering
15640 completion on existing and default properties. And then it will prompt
15641 for a value, offering completion either on allowed values (via an inherited
15642 xxx_ALL property) or on existing values in other instances of this property
15643 in the current file.
15645 Throw an error when trying to set a property with an invalid name."
15646 (interactive (list nil nil))
15647 (let ((property (or property (org-read-property-name))))
15648 ;; `org-entry-put' also makes the following check, but this one
15649 ;; avoids polluting `org-last-set-property' and
15650 ;; `org-last-set-property-value' needlessly.
15651 (unless (org--valid-property-p property)
15652 (user-error "Invalid property name: \"%s\"" property))
15653 (let ((value (or value (org-read-property-value property)))
15654 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15655 (setq org-last-set-property property)
15656 (setq org-last-set-property-value (concat property ": " value))
15657 ;; Possibly postprocess the inserted value:
15658 (when fn (setq value (funcall fn value)))
15659 (unless (equal (org-entry-get nil property) value)
15660 (org-entry-put nil property value)))))
15662 (defun org-find-property (property &optional value)
15663 "Find first entry in buffer that sets PROPERTY.
15665 When optional argument VALUE is non-nil, only consider an entry
15666 if it contains PROPERTY set to this value. If PROPERTY should be
15667 explicitly set to nil, use string \"nil\" for VALUE.
15669 Return position where the entry begins, or nil if there is no
15670 such entry. If narrowing is in effect, only search the visible
15671 part of the buffer."
15672 (save-excursion
15673 (goto-char (point-min))
15674 (let ((case-fold-search t)
15675 (re (org-re-property property nil (not value) value)))
15676 (catch 'exit
15677 (while (re-search-forward re nil t)
15678 (when (if value (org-at-property-p)
15679 (org-entry-get (point) property nil t))
15680 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15682 (defun org-delete-property (property)
15683 "In the current entry, delete PROPERTY."
15684 (interactive
15685 (let* ((completion-ignore-case t)
15686 (cat (org-entry-get (point) "CATEGORY"))
15687 (props0 (org-entry-properties nil 'standard))
15688 (props (if cat props0
15689 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15690 (prop (if (< 1 (length props))
15691 (completing-read "Property: " props nil t)
15692 (caar props))))
15693 (list prop)))
15694 (if (not property)
15695 (message "No property to delete in this entry")
15696 (org-entry-delete nil property)
15697 (message "Property \"%s\" deleted" property)))
15699 (defun org-delete-property-globally (property)
15700 "Remove PROPERTY globally, from all entries.
15701 This function ignores narrowing, if any."
15702 (interactive
15703 (let* ((completion-ignore-case t)
15704 (prop (completing-read
15705 "Globally remove property: "
15706 (mapcar #'list (org-buffer-property-keys)))))
15707 (list prop)))
15708 (org-with-wide-buffer
15709 (goto-char (point-min))
15710 (let ((count 0)
15711 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15712 (while (re-search-forward re nil t)
15713 (when (org-entry-delete (point) property) (cl-incf count)))
15714 (message "Property \"%s\" removed from %d entries" property count))))
15716 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15718 (defun org-compute-property-at-point ()
15719 "Compute the property at point.
15720 This looks for an enclosing column format, extracts the operator and
15721 then applies it to the property in the column format's scope."
15722 (interactive)
15723 (unless (org-at-property-p)
15724 (user-error "Not at a property"))
15725 (let ((prop (match-string-no-properties 2)))
15726 (org-columns-get-format-and-top-level)
15727 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15728 (user-error "No operator defined for property %s" prop))
15729 (org-columns-compute prop)))
15731 (defvar org-property-allowed-value-functions nil
15732 "Hook for functions supplying allowed values for a specific property.
15733 The functions must take a single argument, the name of the property, and
15734 return a flat list of allowed values. If \":ETC\" is one of
15735 the values, this means that these values are intended as defaults for
15736 completion, but that other values should be allowed too.
15737 The functions must return nil if they are not responsible for this
15738 property.")
15740 (defun org-property-get-allowed-values (pom property &optional table)
15741 "Get allowed values for the property PROPERTY.
15742 When TABLE is non-nil, return an alist that can directly be used for
15743 completion."
15744 (let (vals)
15745 (cond
15746 ((equal property "TODO")
15747 (setq vals (org-with-point-at pom
15748 (append org-todo-keywords-1 '("")))))
15749 ((equal property "PRIORITY")
15750 (let ((n org-lowest-priority))
15751 (while (>= n org-highest-priority)
15752 (push (char-to-string n) vals)
15753 (setq n (1- n)))))
15754 ((equal property "CATEGORY"))
15755 ((member property org-special-properties))
15756 ((setq vals (run-hook-with-args-until-success
15757 'org-property-allowed-value-functions property)))
15759 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15760 (when (and vals (string-match "\\S-" vals))
15761 (setq vals (car (read-from-string (concat "(" vals ")"))))
15762 (setq vals (mapcar (lambda (x)
15763 (cond ((stringp x) x)
15764 ((numberp x) (number-to-string x))
15765 ((symbolp x) (symbol-name x))
15766 (t "???")))
15767 vals)))))
15768 (when (member ":ETC" vals)
15769 (setq vals (remove ":ETC" vals))
15770 (org-add-props (car vals) '(org-unrestricted t)))
15771 (if table (mapcar 'list vals) vals)))
15773 (defun org-property-previous-allowed-value (&optional _previous)
15774 "Switch to the next allowed value for this property."
15775 (interactive)
15776 (org-property-next-allowed-value t))
15778 (defun org-property-next-allowed-value (&optional previous)
15779 "Switch to the next allowed value for this property."
15780 (interactive)
15781 (unless (org-at-property-p)
15782 (user-error "Not at a property"))
15783 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15784 (key (match-string 2))
15785 (value (match-string 3))
15786 (allowed (or (org-property-get-allowed-values (point) key)
15787 (and (member value '("[ ]" "[-]" "[X]"))
15788 '("[ ]" "[X]"))))
15789 (heading (save-match-data (nth 4 (org-heading-components))))
15790 nval)
15791 (unless allowed
15792 (user-error "Allowed values for this property have not been defined"))
15793 (when previous (setq allowed (reverse allowed)))
15794 (when (member value allowed)
15795 (setq nval (car (cdr (member value allowed)))))
15796 (setq nval (or nval (car allowed)))
15797 (when (equal nval value)
15798 (user-error "Only one allowed value for this property"))
15799 (org-at-property-p)
15800 (replace-match (concat " :" key ": " nval) t t)
15801 (org-indent-line)
15802 (beginning-of-line 1)
15803 (skip-chars-forward " \t")
15804 (when (equal prop org-effort-property)
15805 (org-refresh-property
15806 '((effort . identity)
15807 (effort-minutes . org-duration-to-minutes))
15808 nval)
15809 (when (string= org-clock-current-task heading)
15810 (setq org-clock-effort nval)
15811 (org-clock-update-mode-line)))
15812 (run-hook-with-args 'org-property-changed-functions key nval)))
15814 (defun org-find-olp (path &optional this-buffer)
15815 "Return a marker pointing to the entry at outline path OLP.
15816 If anything goes wrong, throw an error.
15817 You can wrap this call to catch the error like this:
15819 (condition-case msg
15820 (org-mobile-locate-entry (match-string 4))
15821 (error (nth 1 msg)))
15823 The return value will then be either a string with the error message,
15824 or a marker if everything is OK.
15826 If THIS-BUFFER is set, the outline path does not contain a file,
15827 only headings."
15828 (let* ((file (if this-buffer buffer-file-name (pop path)))
15829 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15830 (level 1)
15831 (lmin 1)
15832 (lmax 1)
15833 end found flevel)
15834 (unless buffer (error "File not found :%s" file))
15835 (with-current-buffer buffer
15836 (unless (derived-mode-p 'org-mode)
15837 (error "Buffer %s needs to be in Org mode" buffer))
15838 (org-with-wide-buffer
15839 (goto-char (point-min))
15840 (dolist (heading path)
15841 (let ((re (format org-complex-heading-regexp-format
15842 (regexp-quote heading)))
15843 (cnt 0))
15844 (while (re-search-forward re end t)
15845 (setq level (- (match-end 1) (match-beginning 1)))
15846 (when (and (>= level lmin) (<= level lmax))
15847 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15848 (when (= cnt 0)
15849 (error "Heading not found on level %d: %s" lmax heading))
15850 (when (> cnt 1)
15851 (error "Heading not unique on level %d: %s" lmax heading))
15852 (goto-char found)
15853 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15854 (setq end (save-excursion (org-end-of-subtree t t)))))
15855 (when (org-at-heading-p)
15856 (point-marker))))))
15858 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15859 "Find node HEADING in BUFFER.
15860 Return a marker to the heading if it was found, or nil if not.
15861 If POS-ONLY is set, return just the position instead of a marker.
15863 The heading text must match exact, but it may have a TODO keyword,
15864 a priority cookie and tags in the standard locations."
15865 (with-current-buffer (or buffer (current-buffer))
15866 (org-with-wide-buffer
15867 (goto-char (point-min))
15868 (let (case-fold-search)
15869 (when (re-search-forward
15870 (format org-complex-heading-regexp-format
15871 (regexp-quote heading)) nil t)
15872 (if pos-only
15873 (match-beginning 0)
15874 (move-marker (make-marker) (match-beginning 0))))))))
15876 (defun org-find-exact-heading-in-directory (heading &optional dir)
15877 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15878 When the target headline is found, return a marker to this location."
15879 (let ((files (directory-files (or dir default-directory)
15880 t "\\`[^.#].*\\.org\\'"))
15881 visiting m buffer)
15882 (catch 'found
15883 (dolist (file files)
15884 (message "trying %s" file)
15885 (setq visiting (org-find-base-buffer-visiting file))
15886 (setq buffer (or visiting (find-file-noselect file)))
15887 (setq m (org-find-exact-headline-in-buffer
15888 heading buffer))
15889 (when (and (not m) (not visiting)) (kill-buffer buffer))
15890 (and m (throw 'found m))))))
15892 (defun org-find-entry-with-id (ident)
15893 "Locate the entry that contains the ID property with exact value IDENT.
15894 IDENT can be a string, a symbol or a number, this function will search for
15895 the string representation of it.
15896 Return the position where this entry starts, or nil if there is no such entry."
15897 (interactive "sID: ")
15898 (let ((id (cond
15899 ((stringp ident) ident)
15900 ((symbolp ident) (symbol-name ident))
15901 ((numberp ident) (number-to-string ident))
15902 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15903 (org-with-wide-buffer (org-find-property "ID" id))))
15905 ;;;; Timestamps
15907 (defvar org-last-changed-timestamp nil)
15908 (defvar org-last-inserted-timestamp nil
15909 "The last time stamp inserted with `org-insert-time-stamp'.")
15911 (defun org-time-stamp (arg &optional inactive)
15912 "Prompt for a date/time and insert a time stamp.
15914 If the user specifies a time like HH:MM or if this command is
15915 called with at least one prefix argument, the time stamp contains
15916 the date and the time. Otherwise, only the date is included.
15918 All parts of a date not specified by the user are filled in from
15919 the timestamp at point, if any, or the current date/time
15920 otherwise.
15922 If there is already a timestamp at the cursor, it is replaced.
15924 With two universal prefix arguments, insert an active timestamp
15925 with the current time without prompting the user.
15927 When called from lisp, the timestamp is inactive if INACTIVE is
15928 non-nil."
15929 (interactive "P")
15930 (let* ((ts (cond
15931 ((org-at-date-range-p t)
15932 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15933 ((org-at-timestamp-p 'lax) (match-string 0))))
15934 ;; Default time is either the timestamp at point or today.
15935 ;; When entering a range, only the range start is considered.
15936 (default-time (if (not ts) (current-time)
15937 (apply #'encode-time (org-parse-time-string ts))))
15938 (default-input (and ts (org-get-compact-tod ts)))
15939 (repeater (and ts
15940 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15941 (match-string 0 ts)))
15942 org-time-was-given
15943 org-end-time-was-given
15944 (time
15945 (and (if (equal arg '(16)) (current-time)
15946 ;; Preserve `this-command' and `last-command'.
15947 (let ((this-command this-command)
15948 (last-command last-command))
15949 (org-read-date
15950 arg 'totime nil nil default-time default-input
15951 inactive))))))
15952 (cond
15953 ((and ts
15954 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15955 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15956 (insert "--")
15957 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15959 ;; Make sure we're on a timestamp. When in the middle of a date
15960 ;; range, move arbitrarily to range end.
15961 (unless (org-at-timestamp-p 'lax)
15962 (skip-chars-forward "-")
15963 (org-at-timestamp-p 'lax))
15964 (replace-match "")
15965 (setq org-last-changed-timestamp
15966 (org-insert-time-stamp
15967 time (or org-time-was-given arg)
15968 inactive nil nil (list org-end-time-was-given)))
15969 (when repeater
15970 (backward-char)
15971 (insert " " repeater)
15972 (setq org-last-changed-timestamp
15973 (concat (substring org-last-inserted-timestamp 0 -1)
15974 " " repeater ">")))
15975 (message "Timestamp updated"))
15976 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
15977 (t (org-insert-time-stamp
15978 time (or org-time-was-given arg) inactive nil nil
15979 (list org-end-time-was-given))))))
15981 ;; FIXME: can we use this for something else, like computing time differences?
15982 (defun org-get-compact-tod (s)
15983 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15984 (let* ((t1 (match-string 1 s))
15985 (h1 (string-to-number (match-string 2 s)))
15986 (m1 (string-to-number (match-string 3 s)))
15987 (t2 (and (match-end 4) (match-string 5 s)))
15988 (h2 (and t2 (string-to-number (match-string 6 s))))
15989 (m2 (and t2 (string-to-number (match-string 7 s))))
15990 dh dm)
15991 (if (not t2)
15993 (setq dh (- h2 h1) dm (- m2 m1))
15994 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15995 (concat t1 "+" (number-to-string dh)
15996 (and (/= 0 dm) (format ":%02d" dm)))))))
15998 (defun org-time-stamp-inactive (&optional arg)
15999 "Insert an inactive time stamp.
16000 An inactive time stamp is enclosed in square brackets instead of angle
16001 brackets. It is inactive in the sense that it does not trigger agenda entries,
16002 does not link to the calendar and cannot be changed with the S-cursor keys.
16003 So these are more for recording a certain time/date."
16004 (interactive "P")
16005 (org-time-stamp arg 'inactive))
16007 (defvar org-date-ovl (make-overlay 1 1))
16008 (overlay-put org-date-ovl 'face 'org-date-selected)
16009 (delete-overlay org-date-ovl)
16011 (defvar org-ans1) ; dynamically scoped parameter
16012 (defvar org-ans2) ; dynamically scoped parameter
16014 (defvar org-plain-time-of-day-regexp) ; defined below
16016 (defvar org-overriding-default-time nil) ; dynamically scoped
16017 (defvar org-read-date-overlay nil)
16018 (defvar org-dcst nil) ; dynamically scoped
16019 (defvar org-read-date-history nil)
16020 (defvar org-read-date-final-answer nil)
16021 (defvar org-read-date-analyze-futurep nil)
16022 (defvar org-read-date-analyze-forced-year nil)
16023 (defvar org-read-date-inactive)
16025 (defvar org-read-date-minibuffer-local-map
16026 (let* ((map (make-sparse-keymap)))
16027 (set-keymap-parent map minibuffer-local-map)
16028 (org-defkey map (kbd ".")
16029 (lambda () (interactive)
16030 ;; Are we at the beginning of the prompt?
16031 (if (looking-back "^[^:]+: "
16032 (let ((inhibit-field-text-motion t))
16033 (line-beginning-position)))
16034 (org-eval-in-calendar '(calendar-goto-today))
16035 (insert "."))))
16036 (org-defkey map (kbd "C-.")
16037 (lambda () (interactive)
16038 (org-eval-in-calendar '(calendar-goto-today))))
16039 (org-defkey map (kbd "M-S-<left>")
16040 (lambda () (interactive)
16041 (org-eval-in-calendar '(calendar-backward-month 1))))
16042 (org-defkey map (kbd "ESC S-<left>")
16043 (lambda () (interactive)
16044 (org-eval-in-calendar '(calendar-backward-month 1))))
16045 (org-defkey map (kbd "M-S-<right>")
16046 (lambda () (interactive)
16047 (org-eval-in-calendar '(calendar-forward-month 1))))
16048 (org-defkey map (kbd "ESC S-<right>")
16049 (lambda () (interactive)
16050 (org-eval-in-calendar '(calendar-forward-month 1))))
16051 (org-defkey map (kbd "M-S-<up>")
16052 (lambda () (interactive)
16053 (org-eval-in-calendar '(calendar-backward-year 1))))
16054 (org-defkey map (kbd "ESC S-<up>")
16055 (lambda () (interactive)
16056 (org-eval-in-calendar '(calendar-backward-year 1))))
16057 (org-defkey map (kbd "M-S-<down>")
16058 (lambda () (interactive)
16059 (org-eval-in-calendar '(calendar-forward-year 1))))
16060 (org-defkey map (kbd "ESC S-<down>")
16061 (lambda () (interactive)
16062 (org-eval-in-calendar '(calendar-forward-year 1))))
16063 (org-defkey map (kbd "S-<up>")
16064 (lambda () (interactive)
16065 (org-eval-in-calendar '(calendar-backward-week 1))))
16066 (org-defkey map (kbd "S-<down>")
16067 (lambda () (interactive)
16068 (org-eval-in-calendar '(calendar-forward-week 1))))
16069 (org-defkey map (kbd "S-<left>")
16070 (lambda () (interactive)
16071 (org-eval-in-calendar '(calendar-backward-day 1))))
16072 (org-defkey map (kbd "S-<right>")
16073 (lambda () (interactive)
16074 (org-eval-in-calendar '(calendar-forward-day 1))))
16075 (org-defkey map (kbd "!")
16076 (lambda () (interactive)
16077 (org-eval-in-calendar '(diary-view-entries))
16078 (message "")))
16079 (org-defkey map (kbd ">")
16080 (lambda () (interactive)
16081 (org-eval-in-calendar '(calendar-scroll-left 1))))
16082 (org-defkey map (kbd "<")
16083 (lambda () (interactive)
16084 (org-eval-in-calendar '(calendar-scroll-right 1))))
16085 (org-defkey map (kbd "C-v")
16086 (lambda () (interactive)
16087 (org-eval-in-calendar
16088 '(calendar-scroll-left-three-months 1))))
16089 (org-defkey map (kbd "M-v")
16090 (lambda () (interactive)
16091 (org-eval-in-calendar
16092 '(calendar-scroll-right-three-months 1))))
16093 map)
16094 "Keymap for minibuffer commands when using `org-read-date'.")
16096 (defvar org-def)
16097 (defvar org-defdecode)
16098 (defvar org-with-time)
16100 (defvar calendar-setup) ; Dynamically scoped.
16101 (defun org-read-date (&optional with-time to-time from-string prompt
16102 default-time default-input inactive)
16103 "Read a date, possibly a time, and make things smooth for the user.
16104 The prompt will suggest to enter an ISO date, but you can also enter anything
16105 which will at least partially be understood by `parse-time-string'.
16106 Unrecognized parts of the date will default to the current day, month, year,
16107 hour and minute. If this command is called to replace a timestamp at point,
16108 or to enter the second timestamp of a range, the default time is taken
16109 from the existing stamp. Furthermore, the command prefers the future,
16110 so if you are giving a date where the year is not given, and the day-month
16111 combination is already past in the current year, it will assume you
16112 mean next year. For details, see the manual. A few examples:
16114 3-2-5 --> 2003-02-05
16115 feb 15 --> currentyear-02-15
16116 2/15 --> currentyear-02-15
16117 sep 12 9 --> 2009-09-12
16118 12:45 --> today 12:45
16119 22 sept 0:34 --> currentyear-09-22 0:34
16120 12 --> currentyear-currentmonth-12
16121 Fri --> nearest Friday after today
16122 -Tue --> last Tuesday
16123 etc.
16125 Furthermore you can specify a relative date by giving, as the *first* thing
16126 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16127 change in days weeks, months, years.
16128 With a single plus or minus, the date is relative to today. With a double
16129 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16130 +4d --> four days from today
16131 +4 --> same as above
16132 +2w --> two weeks from today
16133 ++5 --> five days from default date
16135 The function understands only English month and weekday abbreviations.
16137 While prompting, a calendar is popped up - you can also select the
16138 date with the mouse (button 1). The calendar shows a period of three
16139 months. To scroll it to other months, use the keys `>' and `<'.
16140 If you don't like the calendar, turn it off with
16141 (setq org-read-date-popup-calendar nil)
16143 With optional argument TO-TIME, the date will immediately be converted
16144 to an internal time.
16145 With an optional argument WITH-TIME, the prompt will suggest to
16146 also insert a time. Note that when WITH-TIME is not set, you can
16147 still enter a time, and this function will inform the calling routine
16148 about this change. The calling routine may then choose to change the
16149 format used to insert the time stamp into the buffer to include the time.
16150 With optional argument FROM-STRING, read from this string instead from
16151 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16152 the time/date that is used for everything that is not specified by the
16153 user."
16154 (require 'parse-time)
16155 (let* ((org-with-time with-time)
16156 (org-time-stamp-rounding-minutes
16157 (if (equal org-with-time '(16))
16158 '(0 0)
16159 org-time-stamp-rounding-minutes))
16160 (org-dcst org-display-custom-times)
16161 (ct (org-current-time))
16162 (org-def (or org-overriding-default-time default-time ct))
16163 (org-defdecode (decode-time org-def))
16164 (cur-frame (selected-frame))
16165 (mouse-autoselect-window nil) ; Don't let the mouse jump
16166 (calendar-setup
16167 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16168 (calendar-move-hook nil)
16169 (calendar-view-diary-initially-flag nil)
16170 (calendar-view-holidays-initially-flag nil)
16171 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16172 ;; Rationalize `org-def' and `org-defdecode', if required.
16173 (when (< (nth 2 org-defdecode) org-extend-today-until)
16174 (setf (nth 2 org-defdecode) -1)
16175 (setf (nth 1 org-defdecode) 59)
16176 (setq org-def (apply #'encode-time org-defdecode))
16177 (setq org-defdecode (decode-time org-def)))
16178 (let* ((timestr (format-time-string
16179 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16180 org-def))
16181 (prompt (concat (if prompt (concat prompt " ") "")
16182 (format "Date+time [%s]: " timestr))))
16183 (cond
16184 (from-string (setq ans from-string))
16185 (org-read-date-popup-calendar
16186 (save-excursion
16187 (save-window-excursion
16188 (calendar)
16189 (when (eq calendar-setup 'calendar-only)
16190 (setq cal-frame
16191 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16192 (select-frame cal-frame))
16193 (org-eval-in-calendar '(setq cursor-type nil) t)
16194 (unwind-protect
16195 (progn
16196 (calendar-forward-day (- (time-to-days org-def)
16197 (calendar-absolute-from-gregorian
16198 (calendar-current-date))))
16199 (org-eval-in-calendar nil t)
16200 (let* ((old-map (current-local-map))
16201 (map (copy-keymap calendar-mode-map))
16202 (minibuffer-local-map
16203 (copy-keymap org-read-date-minibuffer-local-map)))
16204 (org-defkey map (kbd "RET") 'org-calendar-select)
16205 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16206 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16207 (unwind-protect
16208 (progn
16209 (use-local-map map)
16210 (setq org-read-date-inactive inactive)
16211 (add-hook 'post-command-hook 'org-read-date-display)
16212 (setq org-ans0
16213 (read-string prompt
16214 default-input
16215 'org-read-date-history
16216 nil))
16217 ;; org-ans0: from prompt
16218 ;; org-ans1: from mouse click
16219 ;; org-ans2: from calendar motion
16220 (setq ans
16221 (concat org-ans0 " " (or org-ans1 org-ans2))))
16222 (remove-hook 'post-command-hook 'org-read-date-display)
16223 (use-local-map old-map)
16224 (when org-read-date-overlay
16225 (delete-overlay org-read-date-overlay)
16226 (setq org-read-date-overlay nil)))))
16227 (bury-buffer "*Calendar*")
16228 (when cal-frame
16229 (delete-frame cal-frame)
16230 (select-frame-set-input-focus cur-frame))))))
16232 (t ; Naked prompt only
16233 (unwind-protect
16234 (setq ans (read-string prompt default-input
16235 'org-read-date-history timestr))
16236 (when org-read-date-overlay
16237 (delete-overlay org-read-date-overlay)
16238 (setq org-read-date-overlay nil))))))
16240 (setq final (org-read-date-analyze ans org-def org-defdecode))
16242 (when org-read-date-analyze-forced-year
16243 (message "Year was forced into %s"
16244 (if org-read-date-force-compatible-dates
16245 "compatible range (1970-2037)"
16246 "range representable on this machine"))
16247 (ding))
16249 ;; One round trip to get rid of 34th of August and stuff like that....
16250 (setq final (decode-time (apply 'encode-time final)))
16252 (setq org-read-date-final-answer ans)
16254 (if to-time
16255 (apply 'encode-time final)
16256 (if (and (boundp 'org-time-was-given) org-time-was-given)
16257 (format "%04d-%02d-%02d %02d:%02d"
16258 (nth 5 final) (nth 4 final) (nth 3 final)
16259 (nth 2 final) (nth 1 final))
16260 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16262 (defun org-read-date-display ()
16263 "Display the current date prompt interpretation in the minibuffer."
16264 (when org-read-date-display-live
16265 (when org-read-date-overlay
16266 (delete-overlay org-read-date-overlay))
16267 (when (minibufferp (current-buffer))
16268 (save-excursion
16269 (end-of-line 1)
16270 (while (not (equal (buffer-substring
16271 (max (point-min) (- (point) 4)) (point))
16272 " "))
16273 (insert " ")))
16274 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16275 " " (or org-ans1 org-ans2)))
16276 (org-end-time-was-given nil)
16277 (f (org-read-date-analyze ans org-def org-defdecode))
16278 (fmts (if org-dcst
16279 org-time-stamp-custom-formats
16280 org-time-stamp-formats))
16281 (fmt (if (or org-with-time
16282 (and (boundp 'org-time-was-given) org-time-was-given))
16283 (cdr fmts)
16284 (car fmts)))
16285 (txt (format-time-string fmt (apply 'encode-time f)))
16286 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16287 (txt (concat "=> " txt)))
16288 (when (and org-end-time-was-given
16289 (string-match org-plain-time-of-day-regexp txt))
16290 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16291 org-end-time-was-given
16292 (substring txt (match-end 0)))))
16293 (when org-read-date-analyze-futurep
16294 (setq txt (concat txt " (=>F)")))
16295 (setq org-read-date-overlay
16296 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16297 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16299 (defun org-read-date-analyze (ans def defdecode)
16300 "Analyze the combined answer of the date prompt."
16301 ;; FIXME: cleanup and comment
16302 ;; Pass `current-time' result to `decode-time' (instead of calling
16303 ;; without arguments) so that only `current-time' has to be
16304 ;; overridden in tests.
16305 (let ((org-def def)
16306 (org-defdecode defdecode)
16307 (nowdecode (decode-time (current-time)))
16308 delta deltan deltaw deltadef year month day
16309 hour minute second wday pm h2 m2 tl wday1
16310 iso-year iso-weekday iso-week iso-date futurep kill-year)
16311 (setq org-read-date-analyze-futurep nil
16312 org-read-date-analyze-forced-year nil)
16313 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16314 (setq ans "+0"))
16316 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16317 (setq ans (replace-match "" t t ans)
16318 deltan (car delta)
16319 deltaw (nth 1 delta)
16320 deltadef (nth 2 delta)))
16322 ;; Check if there is an iso week date in there. If yes, store the
16323 ;; info and postpone interpreting it until the rest of the parsing
16324 ;; is done.
16325 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16326 (setq iso-year (when (match-end 1)
16327 (org-small-year-to-year
16328 (string-to-number (match-string 1 ans))))
16329 iso-weekday (when (match-end 3)
16330 (string-to-number (match-string 3 ans)))
16331 iso-week (string-to-number (match-string 2 ans)))
16332 (setq ans (replace-match "" t t ans)))
16334 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16335 (when (string-match
16336 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16337 (setq year (if (match-end 2)
16338 (string-to-number (match-string 2 ans))
16339 (progn (setq kill-year t)
16340 (string-to-number (format-time-string "%Y"))))
16341 month (string-to-number (match-string 3 ans))
16342 day (string-to-number (match-string 4 ans)))
16343 (setq year (org-small-year-to-year year))
16344 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16345 t nil ans)))
16347 ;; Help matching dotted european dates
16348 (when (string-match
16349 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16350 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16351 (setq kill-year t)
16352 (string-to-number (format-time-string "%Y")))
16353 day (string-to-number (match-string 1 ans))
16354 month (string-to-number (match-string 2 ans))
16355 ans (replace-match (format "%04d-%02d-%02d" year month day)
16356 t nil ans)))
16358 ;; Help matching american dates, like 5/30 or 5/30/7
16359 (when (string-match
16360 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16361 (setq year (if (match-end 4)
16362 (string-to-number (match-string 4 ans))
16363 (progn (setq kill-year t)
16364 (string-to-number (format-time-string "%Y"))))
16365 month (string-to-number (match-string 1 ans))
16366 day (string-to-number (match-string 2 ans)))
16367 (setq year (org-small-year-to-year year))
16368 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16369 t nil ans)))
16370 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16371 ;; If there is a time with am/pm, and *no* time without it, we convert
16372 ;; so that matching will be successful.
16373 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16374 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16375 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16376 (setq hour (string-to-number (match-string 1 ans))
16377 minute (if (match-end 3)
16378 (string-to-number (match-string 3 ans))
16380 pm (equal ?p
16381 (string-to-char (downcase (match-string 4 ans)))))
16382 (if (and (= hour 12) (not pm))
16383 (setq hour 0)
16384 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16385 (setq ans (replace-match (format "%02d:%02d" hour minute)
16386 t t ans))))
16388 ;; Check if a time range is given as a duration
16389 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16390 (setq hour (string-to-number (match-string 1 ans))
16391 h2 (+ hour (string-to-number (match-string 3 ans)))
16392 minute (string-to-number (match-string 2 ans))
16393 m2 (+ minute (if (match-end 5) (string-to-number
16394 (match-string 5 ans))0)))
16395 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16396 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16397 t t ans)))
16399 ;; Check if there is a time range
16400 (when (boundp 'org-end-time-was-given)
16401 (setq org-time-was-given nil)
16402 (when (and (string-match org-plain-time-of-day-regexp ans)
16403 (match-end 8))
16404 (setq org-end-time-was-given (match-string 8 ans))
16405 (setq ans (concat (substring ans 0 (match-beginning 7))
16406 (substring ans (match-end 7))))))
16408 (setq tl (parse-time-string ans)
16409 day (or (nth 3 tl) (nth 3 org-defdecode))
16410 month
16411 (cond ((nth 4 tl))
16412 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16413 ;; Day was specified. Make sure DAY+MONTH
16414 ;; combination happens in the future.
16415 ((nth 3 tl)
16416 (setq futurep t)
16417 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16418 (nth 4 nowdecode)))
16419 (t (nth 4 org-defdecode)))
16420 year
16421 (cond ((and (not kill-year) (nth 5 tl)))
16422 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16423 ;; Month was guessed in the future and is at least
16424 ;; equal to NOWDECODE's. Fix year accordingly.
16425 (futurep
16426 (if (or (> month (nth 4 nowdecode))
16427 (>= day (nth 3 nowdecode)))
16428 (nth 5 nowdecode)
16429 (1+ (nth 5 nowdecode))))
16430 ;; Month was specified. Make sure MONTH+YEAR
16431 ;; combination happens in the future.
16432 ((nth 4 tl)
16433 (setq futurep t)
16434 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16435 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16436 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16437 (t (nth 5 nowdecode))))
16438 (t (nth 5 org-defdecode)))
16439 hour (or (nth 2 tl) (nth 2 org-defdecode))
16440 minute (or (nth 1 tl) (nth 1 org-defdecode))
16441 second (or (nth 0 tl) 0)
16442 wday (nth 6 tl))
16444 (when (and (eq org-read-date-prefer-future 'time)
16445 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16446 (equal day (nth 3 nowdecode))
16447 (equal month (nth 4 nowdecode))
16448 (equal year (nth 5 nowdecode))
16449 (nth 2 tl)
16450 (or (< (nth 2 tl) (nth 2 nowdecode))
16451 (and (= (nth 2 tl) (nth 2 nowdecode))
16452 (nth 1 tl)
16453 (< (nth 1 tl) (nth 1 nowdecode)))))
16454 (setq day (1+ day)
16455 futurep t))
16457 ;; Special date definitions below
16458 (cond
16459 (iso-week
16460 ;; There was an iso week
16461 (require 'cal-iso)
16462 (setq futurep nil)
16463 (setq year (or iso-year year)
16464 day (or iso-weekday wday 1)
16465 wday nil ; to make sure that the trigger below does not match
16466 iso-date (calendar-gregorian-from-absolute
16467 (calendar-iso-to-absolute
16468 (list iso-week day year))))
16469 ; FIXME: Should we also push ISO weeks into the future?
16470 ; (when (and org-read-date-prefer-future
16471 ; (not iso-year)
16472 ; (< (calendar-absolute-from-gregorian iso-date)
16473 ; (time-to-days (current-time))))
16474 ; (setq year (1+ year)
16475 ; iso-date (calendar-gregorian-from-absolute
16476 ; (calendar-iso-to-absolute
16477 ; (list iso-week day year)))))
16478 (setq month (car iso-date)
16479 year (nth 2 iso-date)
16480 day (nth 1 iso-date)))
16481 (deltan
16482 (setq futurep nil)
16483 (unless deltadef
16484 ;; Pass `current-time' result to `decode-time' (instead of
16485 ;; calling without arguments) so that only `current-time' has
16486 ;; to be overridden in tests.
16487 (let ((now (decode-time (current-time))))
16488 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16489 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16490 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16491 ((equal deltaw "m") (setq month (+ month deltan)))
16492 ((equal deltaw "y") (setq year (+ year deltan)))))
16493 ((and wday (not (nth 3 tl)))
16494 ;; Weekday was given, but no day, so pick that day in the week
16495 ;; on or after the derived date.
16496 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16497 (unless (equal wday wday1)
16498 (setq day (+ day (% (- wday wday1 -7) 7))))))
16499 (when (and (boundp 'org-time-was-given)
16500 (nth 2 tl))
16501 (setq org-time-was-given t))
16502 (when (< year 100) (setq year (+ 2000 year)))
16503 ;; Check of the date is representable
16504 (if org-read-date-force-compatible-dates
16505 (progn
16506 (when (< year 1970)
16507 (setq year 1970 org-read-date-analyze-forced-year t))
16508 (when (> year 2037)
16509 (setq year 2037 org-read-date-analyze-forced-year t)))
16510 (condition-case nil
16511 (ignore (encode-time second minute hour day month year))
16512 (error
16513 (setq year (nth 5 org-defdecode))
16514 (setq org-read-date-analyze-forced-year t))))
16515 (setq org-read-date-analyze-futurep futurep)
16516 (list second minute hour day month year)))
16518 (defvar parse-time-weekdays)
16519 (defun org-read-date-get-relative (s today default)
16520 "Check string S for special relative date string.
16521 TODAY and DEFAULT are internal times, for today and for a default.
16522 Return shift list (N what def-flag)
16523 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16524 N is the number of WHATs to shift.
16525 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16526 the DEFAULT date rather than TODAY."
16527 (require 'parse-time)
16528 (when (and
16529 (string-match
16530 (concat
16531 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16532 "\\([0-9]+\\)?"
16533 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16534 "\\([ \t]\\|$\\)") s)
16535 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16536 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16537 (string-to-char (substring (match-string 1 s) -1))
16538 ?+))
16539 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16540 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16541 (what (if (match-end 3) (match-string 3 s) "d"))
16542 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16543 (date (if rel default today))
16544 (wday (nth 6 (decode-time date)))
16545 delta)
16546 (if wday1
16547 (progn
16548 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16549 (when (= delta 0) (setq delta 7))
16550 (when (= dir ?-)
16551 (setq delta (- delta 7))
16552 (when (= delta 0) (setq delta -7)))
16553 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16554 (list delta "d" rel))
16555 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16557 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16558 "Turn a user-specified date into the internal representation.
16559 The internal representation needed by the calendar is (month day year).
16560 This is a wrapper to handle the brain-dead convention in calendar that
16561 user function argument order change dependent on argument order."
16562 (pcase calendar-date-style
16563 (`american (list arg1 arg2 arg3))
16564 (`european (list arg2 arg1 arg3))
16565 (`iso (list arg2 arg3 arg1))))
16567 (defun org-eval-in-calendar (form &optional keepdate)
16568 "Eval FORM in the calendar window and return to current window.
16569 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16570 (let ((sf (selected-frame))
16571 (sw (selected-window)))
16572 (select-window (get-buffer-window "*Calendar*" t))
16573 (eval form)
16574 (when (and (not keepdate) (calendar-cursor-to-date))
16575 (let* ((date (calendar-cursor-to-date))
16576 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16577 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16578 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16579 (select-window sw)
16580 (select-frame-set-input-focus sf)))
16582 (defun org-calendar-select ()
16583 "Return to `org-read-date' with the date currently selected.
16584 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16585 (interactive)
16586 (when (calendar-cursor-to-date)
16587 (let* ((date (calendar-cursor-to-date))
16588 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16589 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16590 (when (active-minibuffer-window) (exit-minibuffer))))
16592 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16593 "Insert a date stamp for the date given by the internal TIME.
16594 See `format-time-string' for the format of TIME.
16595 WITH-HM means use the stamp format that includes the time of the day.
16596 INACTIVE means use square brackets instead of angular ones, so that the
16597 stamp will not contribute to the agenda.
16598 PRE and POST are optional strings to be inserted before and after the
16599 stamp.
16600 The command returns the inserted time stamp."
16601 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16602 stamp)
16603 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16604 (insert-before-markers (or pre ""))
16605 (when (listp extra)
16606 (setq extra (car extra))
16607 (if (and (stringp extra)
16608 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16609 (setq extra (format "-%02d:%02d"
16610 (string-to-number (match-string 1 extra))
16611 (string-to-number (match-string 2 extra))))
16612 (setq extra nil)))
16613 (when extra
16614 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16615 (insert-before-markers (setq stamp (format-time-string fmt time)))
16616 (insert-before-markers (or post ""))
16617 (setq org-last-inserted-timestamp stamp)))
16619 (defun org-toggle-time-stamp-overlays ()
16620 "Toggle the use of custom time stamp formats."
16621 (interactive)
16622 (setq org-display-custom-times (not org-display-custom-times))
16623 (unless org-display-custom-times
16624 (let ((p (point-min)) (bmp (buffer-modified-p)))
16625 (while (setq p (next-single-property-change p 'display))
16626 (when (and (get-text-property p 'display)
16627 (eq (get-text-property p 'face) 'org-date))
16628 (remove-text-properties
16629 p (setq p (next-single-property-change p 'display))
16630 '(display t))))
16631 (set-buffer-modified-p bmp)))
16632 (org-restart-font-lock)
16633 (setq org-table-may-need-update t)
16634 (if org-display-custom-times
16635 (message "Time stamps are overlaid with custom format")
16636 (message "Time stamp overlays removed")))
16638 (defun org-display-custom-time (beg end)
16639 "Overlay modified time stamp format over timestamp between BEG and END."
16640 (let* ((ts (buffer-substring beg end))
16641 t1 with-hm tf time str (off 0))
16642 (save-match-data
16643 (setq t1 (org-parse-time-string ts t))
16644 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16645 (setq off (- (match-end 0) (match-beginning 0)))))
16646 (setq end (- end off))
16647 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16648 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16649 time (org-fix-decoded-time t1)
16650 str (org-add-props
16651 (format-time-string
16652 (substring tf 1 -1) (apply 'encode-time time))
16653 nil 'mouse-face 'highlight))
16654 (put-text-property beg end 'display str)))
16656 (defun org-fix-decoded-time (time)
16657 "Set 0 instead of nil for the first 6 elements of time.
16658 Don't touch the rest."
16659 (let ((n 0))
16660 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16662 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16663 "Difference between TIMESTAMP-STRING and now in days.
16664 If SECONDS is non-nil, return the difference in seconds."
16665 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16666 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16667 (funcall fdiff (current-time)))))
16669 (defun org-deadline-close-p (timestamp-string &optional ndays)
16670 "Is the time in TIMESTAMP-STRING close to the current date?"
16671 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16672 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16673 (not (org-entry-is-done-p))))
16675 (defun org-get-wdays (ts &optional delay zero-delay)
16676 "Get the deadline lead time appropriate for timestring TS.
16677 When DELAY is non-nil, get the delay time for scheduled items
16678 instead of the deadline lead time. When ZERO-DELAY is non-nil
16679 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16680 don't try to find the delay cookie in the scheduled timestamp."
16681 (let ((tv (if delay org-scheduled-delay-days
16682 org-deadline-warning-days)))
16683 (cond
16684 ((or (and delay (< tv 0))
16685 (and delay zero-delay (<= tv 0))
16686 (and (not delay) (<= tv 0)))
16687 ;; Enforce this value no matter what
16688 (- tv))
16689 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16690 ;; lead time is specified.
16691 (floor (* (string-to-number (match-string 1 ts))
16692 (cdr (assoc (match-string 2 ts)
16693 '(("d" . 1) ("w" . 7)
16694 ("m" . 30.4) ("y" . 365.25)
16695 ("h" . 0.041667)))))))
16696 ;; go for the default.
16697 (t tv))))
16699 (defun org-calendar-select-mouse (ev)
16700 "Return to `org-read-date' with the date currently selected.
16701 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16702 (interactive "e")
16703 (mouse-set-point ev)
16704 (when (calendar-cursor-to-date)
16705 (let* ((date (calendar-cursor-to-date))
16706 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16707 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16708 (when (active-minibuffer-window) (exit-minibuffer))))
16710 (defun org-check-deadlines (ndays)
16711 "Check if there are any deadlines due or past due.
16712 A deadline is considered due if it happens within `org-deadline-warning-days'
16713 days from today's date. If the deadline appears in an entry marked DONE,
16714 it is not shown. A numeric prefix argument NDAYS can be used to test that
16715 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16716 are shown."
16717 (interactive "P")
16718 (let* ((org-warn-days
16719 (cond
16720 ((equal ndays '(4)) 100000)
16721 (ndays (prefix-numeric-value ndays))
16722 (t (abs org-deadline-warning-days))))
16723 (case-fold-search nil)
16724 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16725 (callback
16726 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16727 (message "%d deadlines past-due or due within %d days"
16728 (org-occur regexp nil callback)
16729 org-warn-days)))
16731 (defsubst org-re-timestamp (type)
16732 "Return a regexp for timestamp TYPE.
16733 Allowed values for TYPE are:
16735 all: all timestamps
16736 active: only active timestamps (<...>)
16737 inactive: only inactive timestamps ([...])
16738 scheduled: only scheduled timestamps
16739 deadline: only deadline timestamps
16740 closed: only closed time-stamps
16742 When TYPE is nil, fall back on returning a regexp that matches
16743 both scheduled and deadline timestamps."
16744 (cl-case type
16745 (all org-ts-regexp-both)
16746 (active org-ts-regexp)
16747 (inactive org-ts-regexp-inactive)
16748 (scheduled org-scheduled-time-regexp)
16749 (deadline org-deadline-time-regexp)
16750 (closed org-closed-time-regexp)
16751 (otherwise
16752 (concat "\\<"
16753 (regexp-opt (list org-deadline-string org-scheduled-string))
16754 " *<\\([^>]+\\)>"))))
16756 (defun org-check-before-date (d)
16757 "Check if there are deadlines or scheduled entries before date D."
16758 (interactive (list (org-read-date)))
16759 (let* ((case-fold-search nil)
16760 (regexp (org-re-timestamp org-ts-type))
16761 (ts-type org-ts-type)
16762 (callback
16763 (lambda ()
16764 (let ((match (match-string 1)))
16765 (and (if (memq ts-type '(active inactive all))
16766 (eq (org-element-type (save-excursion
16767 (backward-char)
16768 (org-element-context)))
16769 'timestamp)
16770 (org-at-planning-p))
16771 (time-less-p
16772 (org-time-string-to-time match)
16773 (org-time-string-to-time d)))))))
16774 (message "%d entries before %s"
16775 (org-occur regexp nil callback)
16776 d)))
16778 (defun org-check-after-date (d)
16779 "Check if there are deadlines or scheduled entries after date D."
16780 (interactive (list (org-read-date)))
16781 (let* ((case-fold-search nil)
16782 (regexp (org-re-timestamp org-ts-type))
16783 (ts-type org-ts-type)
16784 (callback
16785 (lambda ()
16786 (let ((match (match-string 1)))
16787 (and (if (memq ts-type '(active inactive all))
16788 (eq (org-element-type (save-excursion
16789 (backward-char)
16790 (org-element-context)))
16791 'timestamp)
16792 (org-at-planning-p))
16793 (not (time-less-p
16794 (org-time-string-to-time match)
16795 (org-time-string-to-time d))))))))
16796 (message "%d entries after %s"
16797 (org-occur regexp nil callback)
16798 d)))
16800 (defun org-check-dates-range (start-date end-date)
16801 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16802 (interactive (list (org-read-date nil nil nil "Range starts")
16803 (org-read-date nil nil nil "Range end")))
16804 (let ((case-fold-search nil)
16805 (regexp (org-re-timestamp org-ts-type))
16806 (callback
16807 (let ((type org-ts-type))
16808 (lambda ()
16809 (let ((match (match-string 1)))
16810 (and
16811 (if (memq type '(active inactive all))
16812 (eq (org-element-type (save-excursion
16813 (backward-char)
16814 (org-element-context)))
16815 'timestamp)
16816 (org-at-planning-p))
16817 (not (time-less-p
16818 (org-time-string-to-time match)
16819 (org-time-string-to-time start-date)))
16820 (time-less-p
16821 (org-time-string-to-time match)
16822 (org-time-string-to-time end-date))))))))
16823 (message "%d entries between %s and %s"
16824 (org-occur regexp nil callback) start-date end-date)))
16826 (defun org-evaluate-time-range (&optional to-buffer)
16827 "Evaluate a time range by computing the difference between start and end.
16828 Normally the result is just printed in the echo area, but with prefix arg
16829 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16830 If the time range is actually in a table, the result is inserted into the
16831 next column.
16832 For time difference computation, a year is assumed to be exactly 365
16833 days in order to avoid rounding problems."
16834 (interactive "P")
16836 (org-clock-update-time-maybe)
16837 (save-excursion
16838 (unless (org-at-date-range-p t)
16839 (goto-char (point-at-bol))
16840 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16841 (unless (org-at-date-range-p t)
16842 (user-error "Not at a time-stamp range, and none found in current line")))
16843 (let* ((ts1 (match-string 1))
16844 (ts2 (match-string 2))
16845 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16846 (match-end (match-end 0))
16847 (time1 (org-time-string-to-time ts1))
16848 (time2 (org-time-string-to-time ts2))
16849 (t1 (float-time time1))
16850 (t2 (float-time time2))
16851 (diff (abs (- t2 t1)))
16852 (negative (< (- t2 t1) 0))
16853 ;; (ys (floor (* 365 24 60 60)))
16854 (ds (* 24 60 60))
16855 (hs (* 60 60))
16856 (fy "%dy %dd %02d:%02d")
16857 (fy1 "%dy %dd")
16858 (fd "%dd %02d:%02d")
16859 (fd1 "%dd")
16860 (fh "%02d:%02d")
16861 y d h m align)
16862 (if havetime
16863 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16865 d (floor (/ diff ds)) diff (mod diff ds)
16866 h (floor (/ diff hs)) diff (mod diff hs)
16867 m (floor (/ diff 60)))
16868 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16870 d (floor (+ (/ diff ds) 0.5))
16871 h 0 m 0))
16872 (if (not to-buffer)
16873 (message "%s" (org-make-tdiff-string y d h m))
16874 (if (org-at-table-p)
16875 (progn
16876 (goto-char match-end)
16877 (setq align t)
16878 (and (looking-at " *|") (goto-char (match-end 0))))
16879 (goto-char match-end))
16880 (when (looking-at
16881 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16882 (replace-match ""))
16883 (when negative (insert " -"))
16884 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16885 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16886 (insert " " (format fh h m))))
16887 (when align (org-table-align))
16888 (message "Time difference inserted")))))
16890 (defun org-make-tdiff-string (y d h m)
16891 (let ((fmt "")
16892 (l nil))
16893 (when (> y 0)
16894 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16895 (push y l))
16896 (when (> d 0)
16897 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16898 (push d l))
16899 (when (> h 0)
16900 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16901 (push h l))
16902 (when (> m 0)
16903 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16904 (push m l))
16905 (apply 'format fmt (nreverse l))))
16907 (defun org-time-string-to-time (s)
16908 "Convert timestamp string S into internal time."
16909 (apply #'encode-time (org-parse-time-string s)))
16911 (defun org-time-string-to-seconds (s)
16912 "Convert a timestamp string S into a number of seconds."
16913 (float-time (org-time-string-to-time s)))
16915 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16917 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16918 "Convert time stamp S to an absolute day number.
16920 If DAYNR in non-nil, and there is a specifier for a cyclic time
16921 stamp, get the closest date to DAYNR. If PREFER is
16922 `past' (respectively `future') return a date past (respectively
16923 after) or equal to DAYNR.
16925 POS is the location of time stamp S, as a buffer position in
16926 BUFFER.
16928 Diary sexp timestamps are matched against DAYNR, when non-nil.
16929 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16930 signaled."
16931 (cond
16932 ((string-match "\\`%%\\((.*)\\)" s)
16933 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16934 ;; only able to match individual dates. If it fails, raise an
16935 ;; error.
16936 (if (and daynr
16937 (org-diary-sexp-entry
16938 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16939 daynr
16940 (signal 'org-diary-sexp-no-match (list s))))
16941 (daynr (org-closest-date s daynr prefer))
16942 (t (time-to-days
16943 (condition-case errdata
16944 (apply #'encode-time (org-parse-time-string s))
16945 (error (error "Bad timestamp `%s'%s\nError was: %s"
16947 (if (not (and buffer pos)) ""
16948 (format-message " at %d in buffer `%s'" pos buffer))
16949 (cdr errdata))))))))
16951 (defun org-days-to-iso-week (days)
16952 "Return the iso week number."
16953 (require 'cal-iso)
16954 (car (calendar-iso-from-absolute days)))
16956 (defun org-small-year-to-year (year)
16957 "Convert 2-digit years into 4-digit years.
16958 YEAR is expanded into one of the 30 next years, if possible, or
16959 into a past one. Any year larger than 99 is returned unchanged."
16960 (if (>= year 100) year
16961 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16962 (century (/ current 100))
16963 (offset (- year (% current 100))))
16964 (cond ((> offset 30) (+ (* (1- century) 100) year))
16965 ((> offset -70) (+ (* century 100) year))
16966 (t (+ (* (1+ century) 100) year))))))
16968 (defun org-time-from-absolute (d)
16969 "Return the time corresponding to date D.
16970 D may be an absolute day number, or a calendar-type list (month day year)."
16971 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16972 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16974 (defvar org-agenda-current-date)
16975 (defun org-calendar-holiday ()
16976 "List of holidays, for Diary display in Org mode."
16977 (require 'holidays)
16978 (let ((hl (calendar-check-holidays org-agenda-current-date)))
16979 (and hl (mapconcat #'identity hl "; "))))
16981 (defun org-diary-sexp-entry (sexp entry d)
16982 "Process a SEXP diary ENTRY for date D."
16983 (require 'diary-lib)
16984 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
16985 ;; dynamically.
16986 (let* ((sexp `(let ((entry ,entry)
16987 (date ',d))
16988 ,(car (read-from-string sexp))))
16989 (result (if calendar-debug-sexp (eval sexp)
16990 (condition-case nil
16991 (eval sexp)
16992 (error
16993 (beep)
16994 (message "Bad sexp at line %d in %s: %s"
16995 (org-current-line)
16996 (buffer-file-name) sexp)
16997 (sleep-for 2))))))
16998 (cond ((stringp result) (split-string result "; "))
16999 ((and (consp result)
17000 (not (consp (cdr result)))
17001 (stringp (cdr result))) (cdr result))
17002 ((and (consp result)
17003 (stringp (car result))) result)
17004 (result entry))))
17006 (defun org-diary-to-ical-string (frombuf)
17007 "Get iCalendar entries from diary entries in buffer FROMBUF.
17008 This uses the icalendar.el library."
17009 (let* ((tmpdir temporary-file-directory)
17010 (tmpfile (make-temp-name
17011 (expand-file-name "orgics" tmpdir)))
17012 buf rtn b e)
17013 (with-current-buffer frombuf
17014 (icalendar-export-region (point-min) (point-max) tmpfile)
17015 (setq buf (find-buffer-visiting tmpfile))
17016 (set-buffer buf)
17017 (goto-char (point-min))
17018 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17019 (setq b (match-beginning 0)))
17020 (goto-char (point-max))
17021 (when (re-search-backward "^END:VEVENT" nil t)
17022 (setq e (match-end 0)))
17023 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17024 (kill-buffer buf)
17025 (delete-file tmpfile)
17026 rtn))
17028 (defun org-closest-date (start current prefer)
17029 "Return closest date to CURRENT starting from START.
17031 CURRENT and START are both time stamps.
17033 When PREFER is `past', return a date that is either CURRENT or
17034 past. When PREFER is `future', return a date that is either
17035 CURRENT or future.
17037 Only time stamps with a repeater are modified. Any other time
17038 stamp stay unchanged. In any case, return value is an absolute
17039 day number."
17040 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17041 ;; No repeater. Do not shift time stamp.
17042 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17043 (let ((value (string-to-number (match-string 1 start)))
17044 (type (match-string 2 start)))
17045 (if (= 0 value)
17046 ;; Repeater with a 0-value is considered as void.
17047 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17048 (let* ((base (org-date-to-gregorian start))
17049 (target (org-date-to-gregorian current))
17050 (sday (calendar-absolute-from-gregorian base))
17051 (cday (calendar-absolute-from-gregorian target))
17052 n1 n2)
17053 ;; If START is already past CURRENT, just return START.
17054 (if (<= cday sday) sday
17055 ;; Compute closest date before (N1) and closest date past
17056 ;; (N2) CURRENT.
17057 (pcase type
17058 ("h"
17059 (let ((missing-hours
17060 (mod (+ (- (* 24 (- cday sday))
17061 (nth 2 (org-parse-time-string start)))
17062 org-extend-today-until)
17063 value)))
17064 (setf n1 (if (= missing-hours 0) cday
17065 (- cday (1+ (/ missing-hours 24)))))
17066 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17067 ((or "d" "w")
17068 (let ((value (if (equal type "w") (* 7 value) value)))
17069 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17070 (setf n2 (+ n1 value))))
17071 ("m"
17072 (let* ((add-months
17073 (lambda (d n)
17074 ;; Add N months to gregorian date D, i.e.,
17075 ;; a list (MONTH DAY YEAR). Return a valid
17076 ;; gregorian date.
17077 (let ((m (+ (nth 0 d) n)))
17078 (list (mod m 12)
17079 (nth 1 d)
17080 (+ (/ m 12) (nth 2 d))))))
17081 (months ; Complete months to TARGET.
17082 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17083 (- (nth 0 target) (nth 0 base))
17084 ;; If START's day is greater than
17085 ;; TARGET's, remove incomplete month.
17086 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17087 value)
17088 value))
17089 (before (funcall add-months base months)))
17090 (setf n1 (calendar-absolute-from-gregorian before))
17091 (setf n2
17092 (calendar-absolute-from-gregorian
17093 (funcall add-months before value)))))
17095 (let* ((d (nth 1 base))
17096 (m (nth 0 base))
17097 (y (nth 2 base))
17098 (years ; Complete years to TARGET.
17099 (* (/ (- (nth 2 target)
17101 ;; If START's month and day are
17102 ;; greater than TARGET's, remove
17103 ;; incomplete year.
17104 (if (or (> (nth 0 target) m)
17105 (and (= (nth 0 target) m)
17106 (> (nth 1 target) d)))
17109 value)
17110 value))
17111 (before (list m d (+ y years))))
17112 (setf n1 (calendar-absolute-from-gregorian before))
17113 (setf n2 (calendar-absolute-from-gregorian
17114 (list m d (+ (nth 2 before) value)))))))
17115 ;; Handle PREFER parameter, if any.
17116 (cond
17117 ((eq prefer 'past) (if (= cday n2) n2 n1))
17118 ((eq prefer 'future) (if (= cday n1) n1 n2))
17119 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17121 (defun org-date-to-gregorian (d)
17122 "Turn any specification of date D into a Gregorian date for the calendar."
17123 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17124 ((and (listp d) (= (length d) 3)) d)
17125 ((stringp d)
17126 (let ((d (org-parse-time-string d)))
17127 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17128 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17130 (defun org-parse-time-string (s &optional nodefault)
17131 "Parse the standard Org time string.
17133 This should be a lot faster than the normal `parse-time-string'.
17135 If time is not given, defaults to 0:00. However, with optional
17136 NODEFAULT, hour and minute fields will be nil if not given."
17137 (cond ((string-match org-ts-regexp0 s)
17138 (list 0
17139 (when (or (match-beginning 8) (not nodefault))
17140 (string-to-number (or (match-string 8 s) "0")))
17141 (when (or (match-beginning 7) (not nodefault))
17142 (string-to-number (or (match-string 7 s) "0")))
17143 (string-to-number (match-string 4 s))
17144 (string-to-number (match-string 3 s))
17145 (string-to-number (match-string 2 s))
17146 nil nil nil))
17147 ((string-match "^<[^>]+>$" s)
17148 ;; FIXME: `decode-time' needs to be called with ZONE as its
17149 ;; second argument. However, this requires at least Emacs
17150 ;; 25.1. We can do it when we switch to this version as our
17151 ;; minimal requirement.
17152 (decode-time (seconds-to-time (org-matcher-time s))))
17153 (t (error "Not a standard Org time string: %s" s))))
17155 (defun org-timestamp-up (&optional arg)
17156 "Increase the date item at the cursor by one.
17157 If the cursor is on the year, change the year. If it is on the month,
17158 the day or the time, change that.
17159 With prefix ARG, change by that many units."
17160 (interactive "p")
17161 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17163 (defun org-timestamp-down (&optional arg)
17164 "Decrease the date item at the cursor by one.
17165 If the cursor is on the year, change the year. If it is on the month,
17166 the day or the time, change that.
17167 With prefix ARG, change by that many units."
17168 (interactive "p")
17169 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17171 (defun org-timestamp-up-day (&optional arg)
17172 "Increase the date in the time stamp by one day.
17173 With prefix ARG, change that many days."
17174 (interactive "p")
17175 (if (and (not (org-at-timestamp-p 'lax))
17176 (org-at-heading-p))
17177 (org-todo 'up)
17178 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17180 (defun org-timestamp-down-day (&optional arg)
17181 "Decrease the date in the time stamp by one day.
17182 With prefix ARG, change that many days."
17183 (interactive "p")
17184 (if (and (not (org-at-timestamp-p 'lax))
17185 (org-at-heading-p))
17186 (org-todo 'down)
17187 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17189 (defun org-at-timestamp-p (&optional extended)
17190 "Non-nil if point is inside a timestamp.
17192 By default, the function only consider syntactically valid active
17193 timestamps. However, the caller may have a broader definition
17194 for timestamps. As a consequence, optional argument EXTENDED can
17195 be set to the following values
17197 `inactive'
17199 Include also syntactically valid inactive timestamps.
17201 `agenda'
17203 Include timestamps allowed in Agenda, i.e., those in
17204 properties drawers, planning lines and clock lines.
17206 `lax'
17208 Ignore context. The function matches any part of the
17209 document looking like a timestamp. This includes comments,
17210 example blocks...
17212 For backward-compatibility with Org 9.0, every other non-nil
17213 value is equivalent to `inactive'.
17215 When at a timestamp, return the position of the point as a symbol
17216 among `bracket', `after', `year', `month', `hour', `minute',
17217 `day' or a number of character from the last know part of the
17218 time stamp.
17220 When matching, the match groups are the following:
17221 group 1: year
17222 group 2: month
17223 group 3: day number
17224 group 4: day name
17225 group 5: hours, if any
17226 group 6: minutes, if any"
17227 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17228 (pos (point))
17229 (match?
17230 (let ((boundaries (org-in-regexp regexp)))
17231 (save-match-data
17232 (cond ((null boundaries) nil)
17233 ((eq extended 'lax) t)
17235 (or (and (eq extended 'agenda)
17236 (or (org-at-planning-p)
17237 (org-at-property-p)
17238 (and (bound-and-true-p
17239 org-agenda-include-inactive-timestamps)
17240 (org-at-clock-log-p))))
17241 (eq 'timestamp
17242 (save-excursion
17243 (when (= pos (cdr boundaries)) (forward-char -1))
17244 (org-element-type (org-element-context)))))))))))
17245 (cond
17246 ((not match?) nil)
17247 ((= pos (match-beginning 0)) 'bracket)
17248 ;; Distinguish location right before the closing bracket from
17249 ;; right after it.
17250 ((= pos (1- (match-end 0))) 'bracket)
17251 ((= pos (match-end 0)) 'after)
17252 ((org-pos-in-match-range pos 2) 'year)
17253 ((org-pos-in-match-range pos 3) 'month)
17254 ((org-pos-in-match-range pos 7) 'hour)
17255 ((org-pos-in-match-range pos 8) 'minute)
17256 ((or (org-pos-in-match-range pos 4)
17257 (org-pos-in-match-range pos 5)) 'day)
17258 ((and (> pos (or (match-end 8) (match-end 5)))
17259 (< pos (match-end 0)))
17260 (- pos (or (match-end 8) (match-end 5))))
17261 (t 'day))))
17263 (defun org-toggle-timestamp-type ()
17264 "Toggle the type (<active> or [inactive]) of a time stamp."
17265 (interactive)
17266 (when (org-at-timestamp-p 'lax)
17267 (let ((beg (match-beginning 0)) (end (match-end 0))
17268 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17269 (save-excursion
17270 (goto-char beg)
17271 (while (re-search-forward "[][<>]" end t)
17272 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17273 t t)))
17274 (message "Timestamp is now %sactive"
17275 (if (equal (char-after beg) ?<) "" "in")))))
17277 (defun org-at-clock-log-p ()
17278 "Non-nil if point is on a clock log line."
17279 (and (org-match-line org-clock-line-re)
17280 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17282 (defvar org-clock-history) ; defined in org-clock.el
17283 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17284 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17285 "Change the date in the time stamp at point.
17286 The date will be changed by N times WHAT. WHAT can be `day', `month',
17287 `year', `minute', `second'. If WHAT is not given, the cursor position
17288 in the timestamp determines what will be changed.
17289 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17290 (let ((origin (point))
17291 (timestamp? (org-at-timestamp-p 'lax))
17292 origin-cat
17293 with-hm inactive
17294 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17295 extra rem
17296 ts time time0 fixnext clrgx)
17297 (unless timestamp? (user-error "Not at a timestamp"))
17298 (if (and (not what) (eq timestamp? 'bracket))
17299 (org-toggle-timestamp-type)
17300 ;; Point isn't on brackets. Remember the part of the time-stamp
17301 ;; the point was in. Indeed, size of time-stamps may change,
17302 ;; but point must be kept in the same category nonetheless.
17303 (setq origin-cat timestamp?)
17304 (when (and (not what) (not (eq timestamp? 'day))
17305 org-display-custom-times
17306 (get-text-property (point) 'display)
17307 (not (get-text-property (1- (point)) 'display)))
17308 (setq timestamp? 'day))
17309 (setq timestamp? (or what timestamp?)
17310 inactive (= (char-after (match-beginning 0)) ?\[)
17311 ts (match-string 0))
17312 (replace-match "")
17313 (when (string-match
17314 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17316 (setq extra (match-string 1 ts))
17317 (when suppress-tmp-delay
17318 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17319 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17320 (setq with-hm t))
17321 (setq time0 (org-parse-time-string ts))
17322 (when (and updown
17323 (eq timestamp? 'minute)
17324 (not current-prefix-arg))
17325 ;; This looks like s-up and s-down. Change by one rounding step.
17326 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17327 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17328 (setcar (cdr time0) (+ (nth 1 time0)
17329 (if (> n 0) (- rem) (- dm rem))))))
17330 (setq time
17331 (apply #'encode-time
17332 (or (car time0) 0)
17333 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17334 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17335 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17336 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17337 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17338 (nthcdr 6 time0)))
17339 (when (and (memq timestamp? '(hour minute))
17340 extra
17341 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17342 (setq extra (org-modify-ts-extra
17343 extra
17344 (if (eq timestamp? 'hour) 2 5)
17345 n dm)))
17346 (when (integerp timestamp?)
17347 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17348 (when (eq what 'calendar)
17349 (let ((cal-date (org-get-date-from-calendar)))
17350 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17351 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17352 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17353 (setcar time0 (or (car time0) 0))
17354 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17355 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17356 (setq time (apply 'encode-time time0))))
17357 ;; Insert the new time-stamp, and ensure point stays in the same
17358 ;; category as before (i.e. not after the last position in that
17359 ;; category).
17360 (let ((pos (point)))
17361 ;; Stay before inserted string. `save-excursion' is of no use.
17362 (setq org-last-changed-timestamp
17363 (org-insert-time-stamp time with-hm inactive nil nil extra))
17364 (goto-char pos))
17365 (save-match-data
17366 (looking-at org-ts-regexp3)
17367 (goto-char
17368 (pcase origin-cat
17369 ;; `day' category ends before `hour' if any, or at the end
17370 ;; of the day name.
17371 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17372 (`hour (min (match-end 7) origin))
17373 (`minute (min (1- (match-end 8)) origin))
17374 ((pred integerp) (min (1- (match-end 0)) origin))
17375 ;; Point was right after the time-stamp. However, the
17376 ;; time-stamp length might have changed, so refer to
17377 ;; (match-end 0) instead.
17378 (`after (match-end 0))
17379 ;; `year' and `month' have both fixed size: point couldn't
17380 ;; have moved into another part.
17381 (_ origin))))
17382 ;; Update clock if on a CLOCK line.
17383 (org-clock-update-time-maybe)
17384 ;; Maybe adjust the closest clock in `org-clock-history'
17385 (when org-clock-adjust-closest
17386 (if (not (and (org-at-clock-log-p)
17387 (< 1 (length (delq nil (mapcar 'marker-position
17388 org-clock-history))))))
17389 (message "No clock to adjust")
17390 (cond ((save-excursion ; fix previous clock?
17391 (re-search-backward org-ts-regexp0 nil t)
17392 (looking-back (concat org-clock-string " \\[")
17393 (line-beginning-position)))
17394 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17395 ((save-excursion ; fix next clock?
17396 (re-search-backward org-ts-regexp0 nil t)
17397 (looking-at (concat org-ts-regexp0 "\\] =>")))
17398 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17399 (save-window-excursion
17400 ;; Find closest clock to point, adjust the previous/next one in history
17401 (let* ((p (save-excursion (org-back-to-heading t)))
17402 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17403 (clfixnth
17404 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17405 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17406 (if (not clfixpos)
17407 (message "No clock to adjust")
17408 (save-excursion
17409 (org-goto-marker-or-bmk clfixpos)
17410 (org-show-subtree)
17411 (when (re-search-forward clrgx nil t)
17412 (goto-char (match-beginning 1))
17413 (let (org-clock-adjust-closest)
17414 (org-timestamp-change n timestamp? updown))
17415 (message "Clock adjusted in %s for heading: %s"
17416 (file-name-nondirectory (buffer-file-name))
17417 (org-get-heading t t)))))))))
17418 ;; Try to recenter the calendar window, if any.
17419 (when (and org-calendar-follow-timestamp-change
17420 (get-buffer-window "*Calendar*" t)
17421 (memq timestamp? '(day month year)))
17422 (org-recenter-calendar (time-to-days time))))))
17424 (defun org-modify-ts-extra (s pos n dm)
17425 "Change the different parts of the lead-time and repeat fields in timestamp."
17426 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17427 ng h m new rem)
17428 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17429 (cond
17430 ((or (org-pos-in-match-range pos 2)
17431 (org-pos-in-match-range pos 3))
17432 (setq m (string-to-number (match-string 3 s))
17433 h (string-to-number (match-string 2 s)))
17434 (if (org-pos-in-match-range pos 2)
17435 (setq h (+ h n))
17436 (setq n (* dm (with-no-warnings (signum n))))
17437 (unless (= 0 (setq rem (% m dm)))
17438 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17439 (setq m (+ m n)))
17440 (when (< m 0) (setq m (+ m 60) h (1- h)))
17441 (when (> m 59) (setq m (- m 60) h (1+ h)))
17442 (setq h (mod h 24))
17443 (setq ng 1 new (format "-%02d:%02d" h m)))
17444 ((org-pos-in-match-range pos 6)
17445 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17446 ((org-pos-in-match-range pos 5)
17447 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17449 ((org-pos-in-match-range pos 9)
17450 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17451 ((org-pos-in-match-range pos 8)
17452 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17454 (when ng
17455 (setq s (concat
17456 (substring s 0 (match-beginning ng))
17458 (substring s (match-end ng))))))
17461 (defun org-recenter-calendar (d)
17462 "If the calendar is visible, recenter it to date D."
17463 (let ((cwin (get-buffer-window "*Calendar*" t)))
17464 (when cwin
17465 (let ((calendar-move-hook nil))
17466 (with-selected-window cwin
17467 (calendar-goto-date
17468 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17470 (defun org-goto-calendar (&optional arg)
17471 "Go to the Emacs calendar at the current date.
17472 If there is a time stamp in the current line, go to that date.
17473 A prefix ARG can be used to force the current date."
17474 (interactive "P")
17475 (let ((calendar-move-hook nil)
17476 (calendar-view-holidays-initially-flag nil)
17477 (calendar-view-diary-initially-flag nil)
17478 diff)
17479 (when (or (org-at-timestamp-p 'lax)
17480 (org-match-line (concat ".*" org-ts-regexp)))
17481 (let ((d1 (time-to-days (current-time)))
17482 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17483 (setq diff (- d2 d1))))
17484 (calendar)
17485 (calendar-goto-today)
17486 (when (and diff (not arg)) (calendar-forward-day diff))))
17488 (defun org-get-date-from-calendar ()
17489 "Return a list (month day year) of date at point in calendar."
17490 (with-current-buffer "*Calendar*"
17491 (save-match-data
17492 (calendar-cursor-to-date))))
17494 (defun org-date-from-calendar ()
17495 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17496 If there is already a time stamp at the cursor position, update it."
17497 (interactive)
17498 (if (org-at-timestamp-p 'lax)
17499 (org-timestamp-change 0 'calendar)
17500 (let ((cal-date (org-get-date-from-calendar)))
17501 (org-insert-time-stamp
17502 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17504 (defcustom org-effort-durations
17505 `(("min" . 1)
17506 ("h" . 60)
17507 ("d" . ,(* 60 8))
17508 ("w" . ,(* 60 8 5))
17509 ("m" . ,(* 60 8 5 4))
17510 ("y" . ,(* 60 8 5 40)))
17511 "Conversion factor to minutes for an effort modifier.
17513 Each entry has the form (MODIFIER . MINUTES).
17515 In an effort string, a number followed by MODIFIER is multiplied
17516 by the specified number of MINUTES to obtain an effort in
17517 minutes.
17519 For example, if the value of this variable is ((\"hours\" . 60)), then an
17520 effort string \"2hours\" is equivalent to 120 minutes."
17521 :group 'org-agenda
17522 :version "26.1"
17523 :package-version '(Org . "8.3")
17524 :type '(alist :key-type (string :tag "Modifier")
17525 :value-type (number :tag "Minutes")))
17527 (defcustom org-image-actual-width t
17528 "Should we use the actual width of images when inlining them?
17530 When set to t, always use the image width.
17532 When set to a number, use imagemagick (when available) to set
17533 the image's width to this value.
17535 When set to a number in a list, try to get the width from any
17536 #+ATTR.* keyword if it matches a width specification like
17538 #+ATTR_HTML: :width 300px
17540 and fall back on that number if none is found.
17542 When set to nil, try to get the width from an #+ATTR.* keyword
17543 and fall back on the original width if none is found.
17545 This requires Emacs >= 24.1, build with imagemagick support."
17546 :group 'org-appearance
17547 :version "24.4"
17548 :package-version '(Org . "8.0")
17549 :type '(choice
17550 (const :tag "Use the image width" t)
17551 (integer :tag "Use a number of pixels")
17552 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17553 (const :tag "Use #+ATTR* or don't resize" nil)))
17555 (defcustom org-agenda-inhibit-startup nil
17556 "Inhibit startup when preparing agenda buffers.
17557 When this variable is t, the initialization of the Org agenda
17558 buffers is inhibited: e.g. the visibility state is not set, the
17559 tables are not re-aligned, etc."
17560 :type 'boolean
17561 :version "24.3"
17562 :group 'org-agenda)
17564 (defcustom org-agenda-ignore-properties nil
17565 "Avoid updating text properties when building the agenda.
17566 Properties are used to prepare buffers for effort estimates,
17567 appointments, statistics and subtree-local categories.
17568 If you don't use these in the agenda, you can add them to this
17569 list and agenda building will be a bit faster.
17570 The value is a list, with zero or more of the symbols `effort', `appt',
17571 `stats' or `category'."
17572 :type '(set :greedy t
17573 (const effort)
17574 (const appt)
17575 (const stats)
17576 (const category))
17577 :version "26.1"
17578 :package-version '(Org . "8.3")
17579 :group 'org-agenda)
17581 ;;;; Files
17583 (defun org-save-all-org-buffers ()
17584 "Save all Org buffers without user confirmation."
17585 (interactive)
17586 (message "Saving all Org buffers...")
17587 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17588 (when (featurep 'org-id) (org-id-locations-save))
17589 (message "Saving all Org buffers... done"))
17591 (defun org-revert-all-org-buffers ()
17592 "Revert all Org buffers.
17593 Prompt for confirmation when there are unsaved changes.
17594 Be sure you know what you are doing before letting this function
17595 overwrite your changes.
17597 This function is useful in a setup where one tracks Org files
17598 with a version control system, to revert on one machine after pulling
17599 changes from another. I believe the procedure must be like this:
17601 1. M-x org-save-all-org-buffers
17602 2. Pull changes from the other machine, resolve conflicts
17603 3. M-x org-revert-all-org-buffers"
17604 (interactive)
17605 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17606 (user-error "Abort"))
17607 (save-excursion
17608 (save-window-excursion
17609 (dolist (b (buffer-list))
17610 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17611 (with-current-buffer b buffer-file-name))
17612 (pop-to-buffer-same-window b)
17613 (revert-buffer t 'no-confirm)))
17614 (when (and (featurep 'org-id) org-id-track-globally)
17615 (org-id-locations-load)))))
17617 ;;;; Agenda files
17619 ;;;###autoload
17620 (defun org-switchb (&optional arg)
17621 "Switch between Org buffers.
17623 With `\\[universal-argument]' prefix, restrict available buffers to files.
17625 With `\\[universal-argument] \\[universal-argument]' \
17626 prefix, restrict available buffers to agenda files."
17627 (interactive "P")
17628 (let ((blist (org-buffer-list
17629 (cond ((equal arg '(4)) 'files)
17630 ((equal arg '(16)) 'agenda)))))
17631 (pop-to-buffer-same-window
17632 (completing-read "Org buffer: "
17633 (mapcar #'list (mapcar #'buffer-name blist))
17634 nil t))))
17636 (defun org-buffer-list (&optional predicate exclude-tmp)
17637 "Return a list of Org buffers.
17638 PREDICATE can be `export', `files' or `agenda'.
17640 export restrict the list to Export buffers.
17641 files restrict the list to buffers visiting Org files.
17642 agenda restrict the list to buffers visiting agenda files.
17644 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17645 (let* ((bfn nil)
17646 (agenda-files (and (eq predicate 'agenda)
17647 (mapcar 'file-truename (org-agenda-files t))))
17648 (filter
17649 (cond
17650 ((eq predicate 'files)
17651 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17652 ((eq predicate 'export)
17653 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17654 ((eq predicate 'agenda)
17655 (lambda (b)
17656 (with-current-buffer b
17657 (and (derived-mode-p 'org-mode)
17658 (setq bfn (buffer-file-name b))
17659 (member (file-truename bfn) agenda-files)))))
17660 (t (lambda (b) (with-current-buffer b
17661 (or (derived-mode-p 'org-mode)
17662 (string-match "\\*Org .*Export"
17663 (buffer-name b)))))))))
17664 (delq nil
17665 (mapcar
17666 (lambda(b)
17667 (if (and (funcall filter b)
17668 (or (not exclude-tmp)
17669 (not (string-match "tmp" (buffer-name b)))))
17671 nil))
17672 (buffer-list)))))
17674 (defun org-agenda-files (&optional unrestricted archives)
17675 "Get the list of agenda files.
17676 Optional UNRESTRICTED means return the full list even if a restriction
17677 is currently in place.
17678 When ARCHIVES is t, include all archive files that are really being
17679 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17680 `org-agenda-archives-mode' is t."
17681 (let ((files
17682 (cond
17683 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17684 ((stringp org-agenda-files) (org-read-agenda-file-list))
17685 ((listp org-agenda-files) org-agenda-files)
17686 (t (error "Invalid value of `org-agenda-files'")))))
17687 (setq files (apply 'append
17688 (mapcar (lambda (f)
17689 (if (file-directory-p f)
17690 (directory-files
17691 f t org-agenda-file-regexp)
17692 (list f)))
17693 files)))
17694 (when org-agenda-skip-unavailable-files
17695 (setq files (delq nil
17696 (mapcar (function
17697 (lambda (file)
17698 (and (file-readable-p file) file)))
17699 files))))
17700 (when (or (eq archives t)
17701 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17702 (setq files (org-add-archive-files files)))
17703 files))
17705 (defun org-agenda-file-p (&optional file)
17706 "Return non-nil, if FILE is an agenda file.
17707 If FILE is omitted, use the file associated with the current
17708 buffer."
17709 (let ((fname (or file (buffer-file-name))))
17710 (and fname
17711 (member (file-truename fname)
17712 (mapcar #'file-truename (org-agenda-files t))))))
17714 (defun org-edit-agenda-file-list ()
17715 "Edit the list of agenda files.
17716 Depending on setup, this either uses customize to edit the variable
17717 `org-agenda-files', or it visits the file that is holding the list. In the
17718 latter case, the buffer is set up in a way that saving it automatically kills
17719 the buffer and restores the previous window configuration."
17720 (interactive)
17721 (if (stringp org-agenda-files)
17722 (let ((cw (current-window-configuration)))
17723 (find-file org-agenda-files)
17724 (setq-local org-window-configuration cw)
17725 (add-hook 'after-save-hook
17726 (lambda ()
17727 (set-window-configuration
17728 (prog1 org-window-configuration
17729 (kill-buffer (current-buffer))))
17730 (org-install-agenda-files-menu)
17731 (message "New agenda file list installed"))
17732 nil 'local)
17733 (message "%s" (substitute-command-keys
17734 "Edit list and finish with \\[save-buffer]")))
17735 (customize-variable 'org-agenda-files)))
17737 (defun org-store-new-agenda-file-list (list)
17738 "Set new value for the agenda file list and save it correctly."
17739 (if (stringp org-agenda-files)
17740 (let ((fe (org-read-agenda-file-list t)) b u)
17741 (while (setq b (find-buffer-visiting org-agenda-files))
17742 (kill-buffer b))
17743 (with-temp-file org-agenda-files
17744 (insert
17745 (mapconcat
17746 (lambda (f) ;; Keep un-expanded entries.
17747 (if (setq u (assoc f fe))
17748 (cdr u)
17750 list "\n")
17751 "\n")))
17752 (let ((org-mode-hook nil) (org-inhibit-startup t)
17753 (org-insert-mode-line-in-empty-file nil))
17754 (setq org-agenda-files list)
17755 (customize-save-variable 'org-agenda-files org-agenda-files))))
17757 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17758 "Read the list of agenda files from a file.
17759 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17760 filenames, used by `org-store-new-agenda-file-list' to write back
17761 un-expanded file names."
17762 (when (file-directory-p org-agenda-files)
17763 (error "`org-agenda-files' cannot be a single directory"))
17764 (when (stringp org-agenda-files)
17765 (with-temp-buffer
17766 (insert-file-contents org-agenda-files)
17767 (mapcar
17768 (lambda (f)
17769 (let ((e (expand-file-name (substitute-in-file-name f)
17770 org-directory)))
17771 (if pair-with-expansion
17772 (cons e f)
17773 e)))
17774 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17776 ;;;###autoload
17777 (defun org-cycle-agenda-files ()
17778 "Cycle through the files in `org-agenda-files'.
17779 If the current buffer visits an agenda file, find the next one in the list.
17780 If the current buffer does not, find the first agenda file."
17781 (interactive)
17782 (let* ((fs (or (org-agenda-files t)
17783 (user-error "No agenda files")))
17784 (files (copy-sequence fs))
17785 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17786 file)
17787 (when tcf
17788 (while (and (setq file (pop files))
17789 (not (equal (file-truename file) tcf)))))
17790 (find-file (car (or files fs)))
17791 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17793 (defun org-agenda-file-to-front (&optional to-end)
17794 "Move/add the current file to the top of the agenda file list.
17795 If the file is not present in the list, it is added to the front. If it is
17796 present, it is moved there. With optional argument TO-END, add/move to the
17797 end of the list."
17798 (interactive "P")
17799 (let ((org-agenda-skip-unavailable-files nil)
17800 (file-alist (mapcar (lambda (x)
17801 (cons (file-truename x) x))
17802 (org-agenda-files t)))
17803 (ctf (file-truename
17804 (or buffer-file-name
17805 (user-error "Please save the current buffer to a file"))))
17806 x had)
17807 (setq x (assoc ctf file-alist) had x)
17809 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17810 (if to-end
17811 (setq file-alist (append (delq x file-alist) (list x)))
17812 (setq file-alist (cons x (delq x file-alist))))
17813 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17814 (org-install-agenda-files-menu)
17815 (message "File %s to %s of agenda file list"
17816 (if had "moved" "added") (if to-end "end" "front"))))
17818 (defun org-remove-file (&optional file)
17819 "Remove current file from the list of files in variable `org-agenda-files'.
17820 These are the files which are being checked for agenda entries.
17821 Optional argument FILE means use this file instead of the current."
17822 (interactive)
17823 (let* ((org-agenda-skip-unavailable-files nil)
17824 (file (or file buffer-file-name
17825 (user-error "Current buffer does not visit a file")))
17826 (true-file (file-truename file))
17827 (afile (abbreviate-file-name file))
17828 (files (delq nil (mapcar
17829 (lambda (x)
17830 (unless (equal true-file
17831 (file-truename x))
17833 (org-agenda-files t)))))
17834 (if (not (= (length files) (length (org-agenda-files t))))
17835 (progn
17836 (org-store-new-agenda-file-list files)
17837 (org-install-agenda-files-menu)
17838 (message "Removed from Org Agenda list: %s" afile))
17839 (message "File was not in list: %s (not removed)" afile))))
17841 (defun org-file-menu-entry (file)
17842 (vector file (list 'find-file file) t))
17844 (defun org-check-agenda-file (file)
17845 "Make sure FILE exists. If not, ask user what to do."
17846 (unless (file-exists-p file)
17847 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17848 (abbreviate-file-name file))
17849 (let ((r (downcase (read-char-exclusive))))
17850 (cond
17851 ((equal r ?r)
17852 (org-remove-file file)
17853 (throw 'nextfile t))
17854 (t (user-error "Abort"))))))
17856 (defun org-get-agenda-file-buffer (file)
17857 "Get an agenda buffer visiting FILE.
17858 If the buffer needs to be created, add it to the list of buffers
17859 which might be released later."
17860 (let ((buf (org-find-base-buffer-visiting file)))
17861 (if buf
17862 buf ; just return it
17863 ;; Make a new buffer and remember it
17864 (setq buf (find-file-noselect file))
17865 (when buf (push buf org-agenda-new-buffers))
17866 buf)))
17868 (defun org-release-buffers (blist)
17869 "Release all buffers in list, asking the user for confirmation when needed.
17870 When a buffer is unmodified, it is just killed. When modified, it is saved
17871 \(if the user agrees) and then killed."
17872 (let (file)
17873 (dolist (buf blist)
17874 (setq file (buffer-file-name buf))
17875 (when (and (buffer-modified-p buf)
17876 file
17877 (y-or-n-p (format "Save file %s? " file)))
17878 (with-current-buffer buf (save-buffer)))
17879 (kill-buffer buf))))
17881 (defun org-agenda-prepare-buffers (files)
17882 "Create buffers for all agenda files, protect archived trees and comments."
17883 (interactive)
17884 (let ((pa '(:org-archived t))
17885 (pc '(:org-comment t))
17886 (pall '(:org-archived t :org-comment t))
17887 (inhibit-read-only t)
17888 (org-inhibit-startup org-agenda-inhibit-startup)
17889 (rea (concat ":" org-archive-tag ":"))
17890 re pos)
17891 (setq org-tag-alist-for-agenda nil
17892 org-tag-groups-alist-for-agenda nil)
17893 (save-excursion
17894 (save-restriction
17895 (dolist (file files)
17896 (catch 'nextfile
17897 (if (bufferp file)
17898 (set-buffer file)
17899 (org-check-agenda-file file)
17900 (set-buffer (org-get-agenda-file-buffer file)))
17901 (widen)
17902 (org-set-regexps-and-options 'tags-only)
17903 (setq pos (point))
17904 (or (memq 'category org-agenda-ignore-properties)
17905 (org-refresh-category-properties))
17906 (or (memq 'stats org-agenda-ignore-properties)
17907 (org-refresh-stats-properties))
17908 (or (memq 'effort org-agenda-ignore-properties)
17909 (org-refresh-effort-properties))
17910 (or (memq 'appt org-agenda-ignore-properties)
17911 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17912 (setq org-todo-keywords-for-agenda
17913 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17914 (setq org-done-keywords-for-agenda
17915 (append org-done-keywords-for-agenda org-done-keywords))
17916 (setq org-todo-keyword-alist-for-agenda
17917 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17918 (setq org-tag-alist-for-agenda
17919 (org-uniquify
17920 (append org-tag-alist-for-agenda
17921 org-current-tag-alist)))
17922 ;; Merge current file's tag groups into global
17923 ;; `org-tag-groups-alist-for-agenda'.
17924 (when org-group-tags
17925 (dolist (alist org-tag-groups-alist)
17926 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17927 (if old
17928 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17929 (push alist org-tag-groups-alist-for-agenda)))))
17930 (org-with-silent-modifications
17931 (save-excursion
17932 (remove-text-properties (point-min) (point-max) pall)
17933 (when org-agenda-skip-archived-trees
17934 (goto-char (point-min))
17935 (while (re-search-forward rea nil t)
17936 (when (org-at-heading-p t)
17937 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17938 (goto-char (point-min))
17939 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17940 (while (re-search-forward re nil t)
17941 (when (save-match-data (org-in-commented-heading-p t))
17942 (add-text-properties
17943 (match-beginning 0) (org-end-of-subtree t) pc)))))
17944 (goto-char pos)))))
17945 (setq org-todo-keywords-for-agenda
17946 (org-uniquify org-todo-keywords-for-agenda))
17947 (setq org-todo-keyword-alist-for-agenda
17948 (org-uniquify org-todo-keyword-alist-for-agenda))))
17951 ;;;; CDLaTeX minor mode
17953 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17954 "Keymap for the minor `org-cdlatex-mode'.")
17956 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17957 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17958 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17959 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17960 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
17962 (defvar org-cdlatex-texmathp-advice-is-done nil
17963 "Flag remembering if we have applied the advice to texmathp already.")
17965 (define-minor-mode org-cdlatex-mode
17966 "Toggle the minor `org-cdlatex-mode'.
17967 This mode supports entering LaTeX environment and math in LaTeX fragments
17968 in Org mode.
17969 \\{org-cdlatex-mode-map}"
17970 nil " OCDL" nil
17971 (when org-cdlatex-mode
17972 (require 'cdlatex)
17973 (run-hooks 'cdlatex-mode-hook)
17974 (cdlatex-compute-tables))
17975 (unless org-cdlatex-texmathp-advice-is-done
17976 (setq org-cdlatex-texmathp-advice-is-done t)
17977 (defadvice texmathp (around org-math-always-on activate)
17978 "Always return t in Org buffers.
17979 This is because we want to insert math symbols without dollars even outside
17980 the LaTeX math segments. If Org mode thinks that point is actually inside
17981 an embedded LaTeX fragment, let `texmathp' do its job.
17982 `\\[org-cdlatex-mode-map]'"
17983 (interactive)
17984 (let (p)
17985 (cond
17986 ((not (derived-mode-p 'org-mode)) ad-do-it)
17987 ((eq this-command 'cdlatex-math-symbol)
17988 (setq ad-return-value t
17989 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17991 (let ((p (org-inside-LaTeX-fragment-p)))
17992 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17993 (setq ad-return-value t
17994 texmathp-why '("Org mode embedded math" . 0))
17995 (when p ad-do-it)))))))))
17997 (defun turn-on-org-cdlatex ()
17998 "Unconditionally turn on `org-cdlatex-mode'."
17999 (org-cdlatex-mode 1))
18001 (defun org-try-cdlatex-tab ()
18002 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18003 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18004 - inside a LaTeX fragment, or
18005 - after the first word in a line, where an abbreviation expansion could
18006 insert a LaTeX environment."
18007 (when org-cdlatex-mode
18008 (cond
18009 ;; Before any word on the line: No expansion possible.
18010 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18011 ;; Just after first word on the line: Expand it. Make sure it
18012 ;; cannot happen on headlines, though.
18013 ((save-excursion
18014 (skip-chars-backward "a-zA-Z0-9*")
18015 (skip-chars-backward " \t")
18016 (and (bolp) (not (org-at-heading-p))))
18017 (cdlatex-tab) t)
18018 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18020 (defun org-cdlatex-underscore-caret (&optional _arg)
18021 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18022 Revert to the normal definition outside of these fragments."
18023 (interactive "P")
18024 (if (org-inside-LaTeX-fragment-p)
18025 (call-interactively 'cdlatex-sub-superscript)
18026 (let (org-cdlatex-mode)
18027 (call-interactively (key-binding (vector last-input-event))))))
18029 (defun org-cdlatex-math-modify (&optional _arg)
18030 "Execute `cdlatex-math-modify' in LaTeX fragments.
18031 Revert to the normal definition outside of these fragments."
18032 (interactive "P")
18033 (if (org-inside-LaTeX-fragment-p)
18034 (call-interactively 'cdlatex-math-modify)
18035 (let (org-cdlatex-mode)
18036 (call-interactively (key-binding (vector last-input-event))))))
18038 (defun org-cdlatex-environment-indent (&optional environment item)
18039 "Execute `cdlatex-environment' and indent the inserted environment.
18041 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18043 The inserted environment is indented to current indentation
18044 unless point is at the beginning of the line, in which the
18045 environment remains unintended."
18046 (interactive)
18047 ;; cdlatex-environment always return nil. Therefore, capture output
18048 ;; first and determine if an environment was selected.
18049 (let* ((beg (point-marker))
18050 (end (copy-marker (point) t))
18051 (inserted (progn
18052 (ignore-errors (cdlatex-environment environment item))
18053 (< beg end)))
18054 ;; Figure out how many lines to move forward after the
18055 ;; environment has been inserted.
18056 (lines (when inserted
18057 (save-excursion
18058 (- (cl-loop while (< beg (point))
18059 with x = 0
18060 do (forward-line -1)
18061 (cl-incf x)
18062 finally return x)
18063 (if (progn (goto-char beg)
18064 (and (progn (skip-chars-forward " \t") (eolp))
18065 (progn (skip-chars-backward " \t") (bolp))))
18066 1 0)))))
18067 (env (org-trim (delete-and-extract-region beg end))))
18068 (when inserted
18069 ;; Get indentation of next line unless at column 0.
18070 (let ((ind (if (bolp) 0
18071 (save-excursion
18072 (org-return-indent)
18073 (prog1 (org-get-indentation)
18074 (when (progn (skip-chars-forward " \t") (eolp))
18075 (delete-region beg (point)))))))
18076 (bol (progn (skip-chars-backward " \t") (bolp))))
18077 ;; Insert a newline before environment unless at column zero
18078 ;; to "escape" the current line. Insert a newline if
18079 ;; something is one the same line as \end{ENVIRONMENT}.
18080 (insert
18081 (concat (unless bol "\n") env
18082 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18083 (unless (zerop ind)
18084 (save-excursion
18085 (goto-char beg)
18086 (while (< (point) end)
18087 (unless (eolp) (indent-line-to ind))
18088 (forward-line))))
18089 (goto-char beg)
18090 (forward-line lines)
18091 (indent-line-to ind)))
18092 (set-marker beg nil)
18093 (set-marker end nil)))
18096 ;;;; LaTeX fragments
18098 (defun org-inside-LaTeX-fragment-p ()
18099 "Test if point is inside a LaTeX fragment.
18100 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18101 sequence appearing also before point.
18102 Even though the matchers for math are configurable, this function assumes
18103 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18104 delimiters are skipped when they have been removed by customization.
18105 The return value is nil, or a cons cell with the delimiter and the
18106 position of this delimiter.
18108 This function does a reasonably good job, but can locally be fooled by
18109 for example currency specifications. For example it will assume being in
18110 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18111 fragments that are properly closed, but during editing, we have to live
18112 with the uncertainty caused by missing closing delimiters. This function
18113 looks only before point, not after."
18114 (catch 'exit
18115 (let ((pos (point))
18116 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18117 (lim (save-excursion (org-backward-paragraph) (point)))
18118 dd-on str (start 0) m re)
18119 (goto-char pos)
18120 (when dodollar
18121 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18122 re (nth 1 (assoc "$" org-latex-regexps)))
18123 (while (string-match re str start)
18124 (cond
18125 ((= (match-end 0) (length str))
18126 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18127 ((= (match-end 0) (- (length str) 5))
18128 (throw 'exit nil))
18129 (t (setq start (match-end 0))))))
18130 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18131 (goto-char pos)
18132 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18133 (and (match-beginning 2) (throw 'exit nil))
18134 ;; count $$
18135 (while (re-search-backward "\\$\\$" lim t)
18136 (setq dd-on (not dd-on)))
18137 (goto-char pos)
18138 (when dd-on (cons "$$" m))))))
18140 (defun org-inside-latex-macro-p ()
18141 "Is point inside a LaTeX macro or its arguments?"
18142 (save-match-data
18143 (org-in-regexp
18144 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18146 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18147 "Build an overlay between BEG and END using IMAGE file.
18148 Argument IMAGETYPE is the extension of the displayed image,
18149 as a string. It defaults to \"png\"."
18150 (let ((ov (make-overlay beg end))
18151 (imagetype (or (intern imagetype) 'png)))
18152 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18153 (overlay-put ov 'evaporate t)
18154 (overlay-put ov
18155 'modification-hooks
18156 (list (lambda (o _flag _beg _end &optional _l)
18157 (delete-overlay o))))
18158 (overlay-put ov
18159 'display
18160 (list 'image :type imagetype :file image :ascent 'center))))
18162 (defun org--list-latex-overlays (&optional beg end)
18163 "List all Org LaTeX overlays in current buffer.
18164 Limit to overlays between BEG and END when those are provided."
18165 (cl-remove-if-not
18166 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18167 (overlays-in (or beg (point-min)) (or end (point-max)))))
18169 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18170 "Remove all overlays with LaTeX fragment images in current buffer.
18171 When optional arguments BEG and END are non-nil, remove all
18172 overlays between them instead. Return a non-nil value when some
18173 overlays were removed, nil otherwise."
18174 (let ((overlays (org--list-latex-overlays beg end)))
18175 (mapc #'delete-overlay overlays)
18176 overlays))
18178 (defun org-toggle-latex-fragment (&optional arg)
18179 "Preview the LaTeX fragment at point, or all locally or globally.
18181 If the cursor is on a LaTeX fragment, create the image and overlay
18182 it over the source code, if there is none. Remove it otherwise.
18183 If there is no fragment at point, display all fragments in the
18184 current section.
18186 With prefix ARG, preview or clear image for all fragments in the
18187 current subtree or in the whole buffer when used before the first
18188 headline. With a prefix ARG `\\[universal-argument] \
18189 \\[universal-argument]' preview or clear images
18190 for all fragments in the buffer."
18191 (interactive "P")
18192 (when (display-graphic-p)
18193 (catch 'exit
18194 (save-excursion
18195 (let (beg end msg)
18196 (cond
18197 ((or (equal arg '(16))
18198 (and (equal arg '(4))
18199 (org-with-limited-levels (org-before-first-heading-p))))
18200 (if (org-remove-latex-fragment-image-overlays)
18201 (progn (message "LaTeX fragments images removed from buffer")
18202 (throw 'exit nil))
18203 (setq msg "Creating images for buffer...")))
18204 ((equal arg '(4))
18205 (org-with-limited-levels (org-back-to-heading t))
18206 (setq beg (point))
18207 (setq end (progn (org-end-of-subtree t) (point)))
18208 (if (org-remove-latex-fragment-image-overlays beg end)
18209 (progn
18210 (message "LaTeX fragment images removed from subtree")
18211 (throw 'exit nil))
18212 (setq msg "Creating images for subtree...")))
18213 ((let ((datum (org-element-context)))
18214 (when (memq (org-element-type datum)
18215 '(latex-environment latex-fragment))
18216 (setq beg (org-element-property :begin datum))
18217 (setq end (org-element-property :end datum))
18218 (if (org-remove-latex-fragment-image-overlays beg end)
18219 (progn (message "LaTeX fragment image removed")
18220 (throw 'exit nil))
18221 (setq msg "Creating image...")))))
18223 (org-with-limited-levels
18224 (setq beg (if (org-at-heading-p) (line-beginning-position)
18225 (outline-previous-heading)
18226 (point)))
18227 (setq end (progn (outline-next-heading) (point)))
18228 (if (org-remove-latex-fragment-image-overlays beg end)
18229 (progn
18230 (message "LaTeX fragment images removed from section")
18231 (throw 'exit nil))
18232 (setq msg "Creating images for section...")))))
18233 (let ((file (buffer-file-name (buffer-base-buffer))))
18234 (org-format-latex
18235 (concat org-preview-latex-image-directory "org-ltximg")
18236 beg end
18237 ;; Emacs cannot overlay images from remote hosts. Create
18238 ;; it in `temporary-file-directory' instead.
18239 (if (or (not file) (file-remote-p file))
18240 temporary-file-directory
18241 default-directory)
18242 'overlays msg 'forbuffer org-preview-latex-default-process))
18243 (message (concat msg "done")))))))
18245 (defun org-format-latex
18246 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18247 "Replace LaTeX fragments with links to an image.
18249 The function takes care of creating the replacement image.
18251 Only consider fragments between BEG and END when those are
18252 provided.
18254 When optional argument OVERLAYS is non-nil, display the image on
18255 top of the fragment instead of replacing it.
18257 PROCESSING-TYPE is the conversion method to use, as a symbol.
18259 Some of the options can be changed using the variable
18260 `org-format-latex-options', which see."
18261 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18262 (unless (eq processing-type 'verbatim)
18263 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18264 (cnt 0)
18265 checkdir-flag)
18266 (goto-char (or beg (point-min)))
18267 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18268 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18269 (overlay-recenter (or end (point-max))))
18270 (while (re-search-forward math-regexp end t)
18271 (unless (and overlays
18272 (eq (get-char-property (point) 'org-overlay-type)
18273 'org-latex-overlay))
18274 (let* ((context (org-element-context))
18275 (type (org-element-type context)))
18276 (when (memq type '(latex-environment latex-fragment))
18277 (let ((block-type (eq type 'latex-environment))
18278 (value (org-element-property :value context))
18279 (beg (org-element-property :begin context))
18280 (end (save-excursion
18281 (goto-char (org-element-property :end context))
18282 (skip-chars-backward " \r\t\n")
18283 (point))))
18284 (cond
18285 ((eq processing-type 'mathjax)
18286 ;; Prepare for MathJax processing.
18287 (if (not (string-match "\\`\\$\\$?" value))
18288 (goto-char end)
18289 (delete-region beg end)
18290 (if (string= (match-string 0 value) "$$")
18291 (insert "\\[" (substring value 2 -2) "\\]")
18292 (insert "\\(" (substring value 1 -1) "\\)"))))
18293 ((assq processing-type org-preview-latex-process-alist)
18294 ;; Process to an image.
18295 (cl-incf cnt)
18296 (goto-char beg)
18297 (let* ((processing-info
18298 (cdr (assq processing-type org-preview-latex-process-alist)))
18299 (face (face-at-point))
18300 ;; Get the colors from the face at point.
18302 (let ((color (plist-get org-format-latex-options
18303 :foreground)))
18304 (if (and forbuffer (eq color 'auto))
18305 (face-attribute face :foreground nil 'default)
18306 color)))
18308 (let ((color (plist-get org-format-latex-options
18309 :background)))
18310 (if (and forbuffer (eq color 'auto))
18311 (face-attribute face :background nil 'default)
18312 color)))
18313 (hash (sha1 (prin1-to-string
18314 (list org-format-latex-header
18315 org-latex-default-packages-alist
18316 org-latex-packages-alist
18317 org-format-latex-options
18318 forbuffer value fg bg))))
18319 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18320 (absprefix (expand-file-name prefix dir))
18321 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18322 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18323 (sep (and block-type "\n\n"))
18324 (link (concat sep "[[file:" linkfile "]]" sep))
18325 (options
18326 (org-combine-plists
18327 org-format-latex-options
18328 `(:foreground ,fg :background ,bg))))
18329 (when msg (message msg cnt))
18330 (unless checkdir-flag ; Ensure the directory exists.
18331 (setq checkdir-flag t)
18332 (let ((todir (file-name-directory absprefix)))
18333 (unless (file-directory-p todir)
18334 (make-directory todir t))))
18335 (unless (file-exists-p movefile)
18336 (org-create-formula-image
18337 value movefile options forbuffer processing-type))
18338 (if overlays
18339 (progn
18340 (dolist (o (overlays-in beg end))
18341 (when (eq (overlay-get o 'org-overlay-type)
18342 'org-latex-overlay)
18343 (delete-overlay o)))
18344 (org--format-latex-make-overlay beg end movefile imagetype)
18345 (goto-char end))
18346 (delete-region beg end)
18347 (insert
18348 (org-add-props link
18349 (list 'org-latex-src
18350 (replace-regexp-in-string "\"" "" value)
18351 'org-latex-src-embed-type
18352 (if block-type 'paragraph 'character)))))))
18353 ((eq processing-type 'mathml)
18354 ;; Process to MathML.
18355 (unless (org-format-latex-mathml-available-p)
18356 (user-error "LaTeX to MathML converter not configured"))
18357 (cl-incf cnt)
18358 (when msg (message msg cnt))
18359 (goto-char beg)
18360 (delete-region beg end)
18361 (insert (org-format-latex-as-mathml
18362 value block-type prefix dir)))
18364 (error "Unknown conversion process %s for LaTeX fragments"
18365 processing-type)))))))))))
18367 (defun org-create-math-formula (latex-frag &optional mathml-file)
18368 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18369 Use `org-latex-to-mathml-convert-command'. If the conversion is
18370 sucessful, return the portion between \"<math...> </math>\"
18371 elements otherwise return nil. When MATHML-FILE is specified,
18372 write the results in to that file. When invoked as an
18373 interactive command, prompt for LATEX-FRAG, with initial value
18374 set to the current active region and echo the results for user
18375 inspection."
18376 (interactive (list (let ((frag (when (org-region-active-p)
18377 (buffer-substring-no-properties
18378 (region-beginning) (region-end)))))
18379 (read-string "LaTeX Fragment: " frag nil frag))))
18380 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18381 (let* ((tmp-in-file
18382 (let ((file (file-relative-name
18383 (make-temp-name (expand-file-name "ltxmathml-in")))))
18384 (write-region latex-frag nil file)
18385 file))
18386 (tmp-out-file (file-relative-name
18387 (make-temp-name (expand-file-name "ltxmathml-out"))))
18388 (cmd (format-spec
18389 org-latex-to-mathml-convert-command
18390 `((?j . ,(and org-latex-to-mathml-jar-file
18391 (shell-quote-argument
18392 (expand-file-name
18393 org-latex-to-mathml-jar-file))))
18394 (?I . ,(shell-quote-argument tmp-in-file))
18395 (?i . ,latex-frag)
18396 (?o . ,(shell-quote-argument tmp-out-file)))))
18397 mathml shell-command-output)
18398 (when (called-interactively-p 'any)
18399 (unless (org-format-latex-mathml-available-p)
18400 (user-error "LaTeX to MathML converter not configured")))
18401 (message "Running %s" cmd)
18402 (setq shell-command-output (shell-command-to-string cmd))
18403 (setq mathml
18404 (when (file-readable-p tmp-out-file)
18405 (with-current-buffer (find-file-noselect tmp-out-file t)
18406 (goto-char (point-min))
18407 (when (re-search-forward
18408 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18409 (regexp-quote
18410 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18411 nil t)
18412 (prog1 (match-string 0) (kill-buffer))))))
18413 (cond
18414 (mathml
18415 (setq mathml
18416 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18417 (when mathml-file
18418 (write-region mathml nil mathml-file))
18419 (when (called-interactively-p 'any)
18420 (message mathml)))
18421 ((message "LaTeX to MathML conversion failed")
18422 (message shell-command-output)))
18423 (delete-file tmp-in-file)
18424 (when (file-exists-p tmp-out-file)
18425 (delete-file tmp-out-file))
18426 mathml))
18428 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18429 prefix &optional dir)
18430 "Use `org-create-math-formula' but check local cache first."
18431 (let* ((absprefix (expand-file-name prefix dir))
18432 (print-length nil) (print-level nil)
18433 (formula-id (concat
18434 "formula-"
18435 (sha1
18436 (prin1-to-string
18437 (list latex-frag
18438 org-latex-to-mathml-convert-command)))))
18439 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18440 (formula-cache-dir (file-name-directory formula-cache)))
18442 (unless (file-directory-p formula-cache-dir)
18443 (make-directory formula-cache-dir t))
18445 (unless (file-exists-p formula-cache)
18446 (org-create-math-formula latex-frag formula-cache))
18448 (if (file-exists-p formula-cache)
18449 ;; Successful conversion. Return the link to MathML file.
18450 (org-add-props
18451 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18452 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18453 'org-latex-src-embed-type (if latex-frag-type
18454 'paragraph 'character)))
18455 ;; Failed conversion. Return the LaTeX fragment verbatim
18456 latex-frag)))
18458 (defun org--get-display-dpi ()
18459 "Get the DPI of the display.
18460 The function assumes that the display has the same pixel width in
18461 the horizontal and vertical directions."
18462 (if (display-graphic-p)
18463 (round (/ (display-pixel-height)
18464 (/ (display-mm-height) 25.4)))
18465 (error "Attempt to calculate the dpi of a non-graphic display")))
18467 (defun org-create-formula-image
18468 (string tofile options buffer &optional processing-type)
18469 "Create an image from LaTeX source using external processes.
18471 The LaTeX STRING is saved to a temporary LaTeX file, then
18472 converted to an image file by process PROCESSING-TYPE defined in
18473 `org-preview-latex-process-alist'. A nil value defaults to
18474 `org-preview-latex-default-process'.
18476 The generated image file is eventually moved to TOFILE.
18478 The OPTIONS argument controls the size, foreground color and
18479 background color of the generated image.
18481 When BUFFER non-nil, this function is used for LaTeX previewing.
18482 Otherwise, it is used to deal with LaTeX snippets showed in
18483 a HTML file."
18484 (let* ((processing-type (or processing-type
18485 org-preview-latex-default-process))
18486 (processing-info
18487 (cdr (assq processing-type org-preview-latex-process-alist)))
18488 (programs (plist-get processing-info :programs))
18489 (error-message (or (plist-get processing-info :message) ""))
18490 (use-xcolor (plist-get processing-info :use-xcolor))
18491 (image-input-type (plist-get processing-info :image-input-type))
18492 (image-output-type (plist-get processing-info :image-output-type))
18493 (post-clean (or (plist-get processing-info :post-clean)
18494 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18495 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18496 (latex-header
18497 (or (plist-get processing-info :latex-header)
18498 (org-latex-make-preamble
18499 (org-export-get-environment (org-export-get-backend 'latex))
18500 org-format-latex-header
18501 'snippet)))
18502 (latex-compiler (plist-get processing-info :latex-compiler))
18503 (image-converter (plist-get processing-info :image-converter))
18504 (tmpdir temporary-file-directory)
18505 (texfilebase (make-temp-name
18506 (expand-file-name "orgtex" tmpdir)))
18507 (texfile (concat texfilebase ".tex"))
18508 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18509 '(1.0 . 1.0)))
18510 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18511 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18512 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18513 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18514 "Black"))
18515 (bg (or (plist-get options (if buffer :background :html-background))
18516 "Transparent"))
18517 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18518 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18519 (dolist (program programs)
18520 (org-check-external-command program error-message))
18521 (if use-xcolor
18522 (progn (if (eq fg 'default)
18523 (setq fg (org-latex-color :foreground))
18524 (setq fg (org-latex-color-format fg)))
18525 (if (eq bg 'default)
18526 (setq bg (org-latex-color :background))
18527 (setq bg (org-latex-color-format
18528 (if (string= bg "Transparent") "white" bg))))
18529 (with-temp-file texfile
18530 (insert latex-header)
18531 (insert "\n\\begin{document}\n"
18532 "\\definecolor{fg}{rgb}{" fg "}\n"
18533 "\\definecolor{bg}{rgb}{" bg "}\n"
18534 "\n\\pagecolor{bg}\n"
18535 "\n{\\color{fg}\n"
18536 string
18537 "\n}\n"
18538 "\n\\end{document}\n")))
18539 (if (eq fg 'default)
18540 (setq fg (org-dvipng-color :foreground))
18541 (unless (string= fg "Transparent")
18542 (setq fg (org-dvipng-color-format fg))))
18543 (if (eq bg 'default)
18544 (setq bg (org-dvipng-color :background))
18545 (unless (string= bg "Transparent")
18546 (setq bg (org-dvipng-color-format bg))))
18547 (with-temp-file texfile
18548 (insert latex-header)
18549 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18551 (let* ((err-msg (format "Please adjust `%s' part of \
18552 `org-preview-latex-process-alist'."
18553 processing-type))
18554 (image-input-file
18555 (org-compile-file
18556 texfile latex-compiler image-input-type err-msg log-buf))
18557 (image-output-file
18558 (org-compile-file
18559 image-input-file image-converter image-output-type err-msg log-buf
18560 `((?F . ,(shell-quote-argument fg))
18561 (?B . ,(shell-quote-argument bg))
18562 (?D . ,(shell-quote-argument (format "%s" dpi)))
18563 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18564 (copy-file image-output-file tofile 'replace)
18565 (dolist (e post-clean)
18566 (when (file-exists-p (concat texfilebase e))
18567 (delete-file (concat texfilebase e))))
18568 image-output-file)))
18570 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18571 "Fill a LaTeX header template TPL.
18572 In the template, the following place holders will be recognized:
18574 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18575 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18576 [PACKAGES] \\usepackage statements for PKG
18577 [NO-PACKAGES] do not include PKG
18578 [EXTRA] the string EXTRA
18579 [NO-EXTRA] do not include EXTRA
18581 For backward compatibility, if both the positive and the negative place
18582 holder is missing, the positive one (without the \"NO-\") will be
18583 assumed to be present at the end of the template.
18584 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18585 EXTRA is a string.
18586 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18587 (let (rpl (end ""))
18588 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18589 (setq rpl (if (or (match-end 1) (not def-pkg))
18590 "" (org-latex-packages-to-string def-pkg snippets-p t))
18591 tpl (replace-match rpl t t tpl))
18592 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18594 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18595 (setq rpl (if (or (match-end 1) (not pkg))
18596 "" (org-latex-packages-to-string pkg snippets-p t))
18597 tpl (replace-match rpl t t tpl))
18598 (when pkg (setq end
18599 (concat end "\n"
18600 (org-latex-packages-to-string pkg snippets-p)))))
18602 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18603 (setq rpl (if (or (match-end 1) (not extra))
18604 "" (concat extra "\n"))
18605 tpl (replace-match rpl t t tpl))
18606 (when (and extra (string-match "\\S-" extra))
18607 (setq end (concat end "\n" extra))))
18609 (if (string-match "\\S-" end)
18610 (concat tpl "\n" end)
18611 tpl)))
18613 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18614 "Turn an alist of packages into a string with the \\usepackage macros."
18615 (setq pkg (mapconcat (lambda(p)
18616 (cond
18617 ((stringp p) p)
18618 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18619 (format "%% Package %s omitted" (cadr p)))
18620 ((equal "" (car p))
18621 (format "\\usepackage{%s}" (cadr p)))
18623 (format "\\usepackage[%s]{%s}"
18624 (car p) (cadr p)))))
18626 "\n"))
18627 (if newline (concat pkg "\n") pkg))
18629 (defun org-dvipng-color (attr)
18630 "Return a RGB color specification for dvipng."
18631 (org-dvipng-color-format (face-attribute 'default attr nil)))
18633 (defun org-dvipng-color-format (color-name)
18634 "Convert COLOR-NAME to a RGB color value for dvipng."
18635 (apply #'format "rgb %s %s %s"
18636 (mapcar 'org-normalize-color
18637 (color-values color-name))))
18639 (defun org-latex-color (attr)
18640 "Return a RGB color for the LaTeX color package."
18641 (org-latex-color-format (face-attribute 'default attr nil)))
18643 (defun org-latex-color-format (color-name)
18644 "Convert COLOR-NAME to a RGB color value."
18645 (apply #'format "%s,%s,%s"
18646 (mapcar 'org-normalize-color
18647 (color-values color-name))))
18649 (defun org-normalize-color (value)
18650 "Return string to be used as color value for an RGB component."
18651 (format "%g" (/ value 65535.0)))
18655 ;; Image display
18657 (defvar-local org-inline-image-overlays nil)
18659 (defun org-toggle-inline-images (&optional include-linked)
18660 "Toggle the display of inline images.
18661 INCLUDE-LINKED is passed to `org-display-inline-images'."
18662 (interactive "P")
18663 (if org-inline-image-overlays
18664 (progn
18665 (org-remove-inline-images)
18666 (when (called-interactively-p 'interactive)
18667 (message "Inline image display turned off")))
18668 (org-display-inline-images include-linked)
18669 (when (called-interactively-p 'interactive)
18670 (message (if org-inline-image-overlays
18671 (format "%d images displayed inline"
18672 (length org-inline-image-overlays))
18673 "No images to display inline")))))
18675 (defun org-redisplay-inline-images ()
18676 "Refresh the display of inline images."
18677 (interactive)
18678 (if (not org-inline-image-overlays)
18679 (org-toggle-inline-images)
18680 (org-toggle-inline-images)
18681 (org-toggle-inline-images)))
18683 (defun org-display-inline-images (&optional include-linked refresh beg end)
18684 "Display inline images.
18686 An inline image is a link which follows either of these
18687 conventions:
18689 1. Its path is a file with an extension matching return value
18690 from `image-file-name-regexp' and it has no contents.
18692 2. Its description consists in a single link of the previous
18693 type.
18695 When optional argument INCLUDE-LINKED is non-nil, also links with
18696 a text description part will be inlined. This can be nice for
18697 a quick look at those images, but it does not reflect what
18698 exported files will look like.
18700 When optional argument REFRESH is non-nil, refresh existing
18701 images between BEG and END. This will create new image displays
18702 only if necessary. BEG and END default to the buffer
18703 boundaries."
18704 (interactive "P")
18705 (when (display-graphic-p)
18706 (unless refresh
18707 (org-remove-inline-images)
18708 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18709 (org-with-wide-buffer
18710 (goto-char (or beg (point-min)))
18711 (let* ((case-fold-search t)
18712 (file-extension-re (image-file-name-regexp))
18713 (link-abbrevs (mapcar #'car
18714 (append org-link-abbrev-alist-local
18715 org-link-abbrev-alist)))
18716 ;; Check absolute, relative file names and explicit
18717 ;; "file:" links. Also check link abbreviations since
18718 ;; some might expand to "file" links.
18719 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18720 (if (not link-abbrevs) ""
18721 (format "\\|\\(?:%s:\\)"
18722 (regexp-opt link-abbrevs))))))
18723 (while (re-search-forward file-types-re end t)
18724 (let ((link (save-match-data (org-element-context))))
18725 ;; Check if we're at an inline image, i.e., an image file
18726 ;; link without a description (unless INCLUDE-LINKED is
18727 ;; non-nil).
18728 (when (and (equal "file" (org-element-property :type link))
18729 (or include-linked
18730 (null (org-element-contents link)))
18731 (string-match-p file-extension-re
18732 (org-element-property :path link)))
18733 (let ((file (expand-file-name
18734 (org-link-unescape
18735 (org-element-property :path link)))))
18736 (when (file-exists-p file)
18737 (let ((width
18738 ;; Apply `org-image-actual-width' specifications.
18739 (cond
18740 ((not (image-type-available-p 'imagemagick)) nil)
18741 ((eq org-image-actual-width t) nil)
18742 ((listp org-image-actual-width)
18744 ;; First try to find a width among
18745 ;; attributes associated to the paragraph
18746 ;; containing link.
18747 (let ((paragraph
18748 (let ((e link))
18749 (while (and (setq e (org-element-property
18750 :parent e))
18751 (not (eq (org-element-type e)
18752 'paragraph))))
18753 e)))
18754 (when paragraph
18755 (save-excursion
18756 (goto-char (org-element-property :begin paragraph))
18757 (when
18758 (re-search-forward
18759 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18760 (org-element-property
18761 :post-affiliated paragraph)
18763 (string-to-number (match-string 1))))))
18764 ;; Otherwise, fall-back to provided number.
18765 (car org-image-actual-width)))
18766 ((numberp org-image-actual-width)
18767 org-image-actual-width)))
18768 (old (get-char-property-and-overlay
18769 (org-element-property :begin link)
18770 'org-image-overlay)))
18771 (if (and (car-safe old) refresh)
18772 (image-refresh (overlay-get (cdr old) 'display))
18773 (let ((image (create-image file
18774 (and width 'imagemagick)
18776 :width width)))
18777 (when image
18778 (let ((ov (make-overlay
18779 (org-element-property :begin link)
18780 (progn
18781 (goto-char
18782 (org-element-property :end link))
18783 (skip-chars-backward " \t")
18784 (point)))))
18785 (overlay-put ov 'display image)
18786 (overlay-put ov 'face 'default)
18787 (overlay-put ov 'org-image-overlay t)
18788 (overlay-put
18789 ov 'modification-hooks
18790 (list 'org-display-inline-remove-overlay))
18791 (push ov org-inline-image-overlays)))))))))))))))
18793 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18794 "Remove inline-display overlay if a corresponding region is modified."
18795 (let ((inhibit-modification-hooks t))
18796 (when (and ov after)
18797 (delete ov org-inline-image-overlays)
18798 (delete-overlay ov))))
18800 (defun org-remove-inline-images ()
18801 "Remove inline display of images."
18802 (interactive)
18803 (mapc #'delete-overlay org-inline-image-overlays)
18804 (setq org-inline-image-overlays nil))
18807 ;;; Key bindings
18809 (defun org-remap (map &rest commands)
18810 "In MAP, remap the functions given in COMMANDS.
18811 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18812 (let (new old)
18813 (while commands
18814 (setq old (pop commands) new (pop commands))
18815 (org-defkey map (vector 'remap old) new))))
18817 ;;;; Outline functions that can be remapped in Org
18818 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18819 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18820 (define-key org-mode-map [remap outline-forward-same-level]
18821 #'org-forward-heading-same-level)
18822 (define-key org-mode-map [remap outline-backward-same-level]
18823 #'org-backward-heading-same-level)
18824 (define-key org-mode-map [remap outline-show-branches]
18825 #'org-kill-note-or-show-branches)
18826 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18827 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18828 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18829 (define-key org-mode-map [remap outline-next-visible-heading]
18830 #'org-next-visible-heading)
18831 (define-key org-mode-map [remap outline-previous-visible-heading]
18832 #'org-previous-visible-heading)
18833 (define-key org-mode-map [remap show-children] #'org-show-children)
18835 ;;;; Make `C-c C-x' a prefix key
18836 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18838 ;;;; TAB key with modifiers
18839 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18840 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18841 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18842 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18843 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18845 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18846 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18847 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18849 ;;;; RET key with modifiers
18850 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18851 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18852 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18853 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18854 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18856 ;;;; Cursor keys with modifiers
18857 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18858 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18859 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18860 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18861 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18862 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18863 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18865 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18866 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18867 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18868 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18869 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18870 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18871 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18872 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18873 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18874 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18876 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18877 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18878 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18879 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18881 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18882 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18883 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18884 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18886 ;;;; Babel keys
18887 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18888 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18889 (define-key org-babel-map key def))
18891 ;;;; Extra keys for TTY access.
18893 ;; We only set them when really needed because otherwise the
18894 ;; menus don't show the simple keys
18896 (when (or org-use-extra-keys (not window-system))
18897 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18898 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18899 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18900 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18901 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18902 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18903 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18904 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18905 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18906 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18907 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18908 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18909 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18910 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18911 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18912 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18913 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18914 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18915 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18916 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18918 ;;;; Narrow map
18919 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18920 (org-defkey narrow-map "b" #'org-narrow-to-block)
18921 (org-defkey narrow-map "e" #'org-narrow-to-element)
18923 ;;;; Remap usual Emacs bindings
18924 (org-remap org-mode-map
18925 'self-insert-command 'org-self-insert-command
18926 'delete-char 'org-delete-char
18927 'delete-backward-char 'org-delete-backward-char
18928 'kill-line 'org-kill-line
18929 'open-line 'org-open-line
18930 'yank 'org-yank
18931 'comment-dwim 'org-comment-dwim
18932 'move-beginning-of-line 'org-beginning-of-line
18933 'move-end-of-line 'org-end-of-line
18934 'forward-paragraph 'org-forward-paragraph
18935 'backward-paragraph 'org-backward-paragraph
18936 'backward-sentence 'org-backward-sentence
18937 'forward-sentence 'org-forward-sentence
18938 'fill-paragraph 'org-fill-paragraph
18939 'delete-indentation 'org-delete-indentation
18940 'transpose-words 'org-transpose-words)
18942 ;;;; All the other keys
18943 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18944 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18945 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18946 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18947 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18948 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18949 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18950 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18951 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18952 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18953 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18954 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18955 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18956 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18957 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18958 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18959 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18960 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18961 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18962 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18963 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18964 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18965 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18966 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18967 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18968 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18969 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18970 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18971 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18972 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18973 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18974 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18975 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18976 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18977 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18978 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18979 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18980 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18981 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18982 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18983 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18984 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
18985 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
18986 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
18987 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
18988 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
18989 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
18990 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
18991 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
18992 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
18993 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
18994 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
18995 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
18996 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
18997 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
18998 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
18999 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19000 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19001 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19002 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19003 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19004 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19005 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19006 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19007 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19008 (org-defkey org-mode-map (kbd "RET") #'org-return)
19009 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19010 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19011 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19012 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19013 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19014 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19015 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19016 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19017 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19018 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19019 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19020 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19021 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19022 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19023 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19024 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19025 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19026 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19027 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19028 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19029 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19030 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19031 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19033 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19034 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19035 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19037 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19038 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19039 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19040 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19041 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19042 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19043 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19044 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19045 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19046 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19047 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19048 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19049 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19050 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19051 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19052 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19053 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19054 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19055 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19056 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19057 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19058 (org-defkey org-mode-map (kbd "C-c C-x w") #'org-insert-structure-template)
19060 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19061 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19062 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19063 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19064 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19065 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19067 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19069 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19071 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19072 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19074 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19077 ;;; Speed commands
19079 (defconst org-speed-commands-default
19081 ("Outline Navigation")
19082 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19083 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19084 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19085 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19086 ("F" . org-next-block)
19087 ("B" . org-previous-block)
19088 ("u" . (org-speed-move-safe 'outline-up-heading))
19089 ("j" . org-goto)
19090 ("g" . (org-refile t))
19091 ("Outline Visibility")
19092 ("c" . org-cycle)
19093 ("C" . org-shifttab)
19094 (" " . org-display-outline-path)
19095 ("s" . org-narrow-to-subtree)
19096 ("=" . org-columns)
19097 ("Outline Structure Editing")
19098 ("U" . org-metaup)
19099 ("D" . org-metadown)
19100 ("r" . org-metaright)
19101 ("l" . org-metaleft)
19102 ("R" . org-shiftmetaright)
19103 ("L" . org-shiftmetaleft)
19104 ("i" . (progn (forward-char 1) (call-interactively
19105 'org-insert-heading-respect-content)))
19106 ("^" . org-sort)
19107 ("w" . org-refile)
19108 ("a" . org-archive-subtree-default-with-confirmation)
19109 ("@" . org-mark-subtree)
19110 ("#" . org-toggle-comment)
19111 ("Clock Commands")
19112 ("I" . org-clock-in)
19113 ("O" . org-clock-out)
19114 ("Meta Data Editing")
19115 ("t" . org-todo)
19116 ("," . (org-priority))
19117 ("0" . (org-priority ?\ ))
19118 ("1" . (org-priority ?A))
19119 ("2" . (org-priority ?B))
19120 ("3" . (org-priority ?C))
19121 (":" . org-set-tags-command)
19122 ("e" . org-set-effort)
19123 ("E" . org-inc-effort)
19124 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19125 (org-entry-put (point) "APPT_WARNTIME" m)))
19126 ("Agenda Views etc")
19127 ("v" . org-agenda)
19128 ("/" . org-sparse-tree)
19129 ("Misc")
19130 ("o" . org-open-at-point)
19131 ("?" . org-speed-command-help)
19132 ("<" . (org-agenda-set-restriction-lock 'subtree))
19133 (">" . (org-agenda-remove-restriction-lock))
19135 "The default speed commands.")
19137 (defun org-print-speed-command (e)
19138 (if (> (length (car e)) 1)
19139 (progn
19140 (princ "\n")
19141 (princ (car e))
19142 (princ "\n")
19143 (princ (make-string (length (car e)) ?-))
19144 (princ "\n"))
19145 (princ (car e))
19146 (princ " ")
19147 (if (symbolp (cdr e))
19148 (princ (symbol-name (cdr e)))
19149 (prin1 (cdr e)))
19150 (princ "\n")))
19152 (defun org-speed-command-help ()
19153 "Show the available speed commands."
19154 (interactive)
19155 (if (not org-use-speed-commands)
19156 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19157 (with-output-to-temp-buffer "*Help*"
19158 (princ "User-defined Speed commands\n===========================\n")
19159 (mapc #'org-print-speed-command org-speed-commands-user)
19160 (princ "\n")
19161 (princ "Built-in Speed commands\n=======================\n")
19162 (mapc #'org-print-speed-command org-speed-commands-default))
19163 (with-current-buffer "*Help*"
19164 (setq truncate-lines t))))
19166 (defun org-speed-move-safe (cmd)
19167 "Execute CMD, but make sure that the cursor always ends up in a headline.
19168 If not, return to the original position and throw an error."
19169 (interactive)
19170 (let ((pos (point)))
19171 (call-interactively cmd)
19172 (unless (and (bolp) (org-at-heading-p))
19173 (goto-char pos)
19174 (error "Boundary reached while executing %s" cmd))))
19176 (defvar org-self-insert-command-undo-counter 0)
19178 (defvar org-table-auto-blank-field) ; defined in org-table.el
19179 (defvar org-speed-command nil)
19181 (defun org-speed-command-activate (keys)
19182 "Hook for activating single-letter speed commands.
19183 `org-speed-commands-default' specifies a minimal command set.
19184 Use `org-speed-commands-user' for further customization."
19185 (when (or (and (bolp) (looking-at org-outline-regexp))
19186 (and (functionp org-use-speed-commands)
19187 (funcall org-use-speed-commands)))
19188 (cdr (assoc keys (append org-speed-commands-user
19189 org-speed-commands-default)))))
19191 (defun org-babel-speed-command-activate (keys)
19192 "Hook for activating single-letter code block commands."
19193 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19194 (cdr (assoc keys org-babel-key-bindings))))
19196 (defcustom org-speed-command-hook
19197 '(org-speed-command-activate org-babel-speed-command-activate)
19198 "Hook for activating speed commands at strategic locations.
19199 Hook functions are called in sequence until a valid handler is
19200 found.
19202 Each hook takes a single argument, a user-pressed command key
19203 which is also a `self-insert-command' from the global map.
19205 Within the hook, examine the cursor position and the command key
19206 and return nil or a valid handler as appropriate. Handler could
19207 be one of an interactive command, a function, or a form.
19209 Set `org-use-speed-commands' to non-nil value to enable this
19210 hook. The default setting is `org-speed-command-activate'."
19211 :group 'org-structure
19212 :version "24.1"
19213 :type 'hook)
19215 (defun org-self-insert-command (N)
19216 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19217 If the cursor is in a table looking at whitespace, the whitespace is
19218 overwritten, and the table is not marked as requiring realignment."
19219 (interactive "p")
19220 (org-check-before-invisible-edit 'insert)
19221 (cond
19222 ((and org-use-speed-commands
19223 (let ((kv (this-command-keys-vector)))
19224 (setq org-speed-command
19225 (run-hook-with-args-until-success
19226 'org-speed-command-hook
19227 (make-string 1 (aref kv (1- (length kv))))))))
19228 (cond
19229 ((commandp org-speed-command)
19230 (setq this-command org-speed-command)
19231 (call-interactively org-speed-command))
19232 ((functionp org-speed-command)
19233 (funcall org-speed-command))
19234 ((and org-speed-command (listp org-speed-command))
19235 (eval org-speed-command))
19236 (t (let (org-use-speed-commands)
19237 (call-interactively 'org-self-insert-command)))))
19238 ((and
19239 (= N 1)
19240 (not (org-region-active-p))
19241 (org-at-table-p)
19242 (progn
19243 ;; Check if we blank the field, and if that triggers align.
19244 (and (featurep 'org-table)
19245 org-table-auto-blank-field
19246 (memq last-command
19247 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19248 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19249 ;; Got extra space, this field does not determine
19250 ;; column width.
19251 (let (org-table-may-need-update) (org-table-blank-field))
19252 ;; No extra space, this field may determine column
19253 ;; width.
19254 (org-table-blank-field)))
19256 (looking-at "[^|\n]* |"))
19257 ;; There is room for insertion without re-aligning the table.
19258 (self-insert-command N)
19259 (org-table-with-shrunk-field
19260 (save-excursion
19261 (skip-chars-forward "^|")
19262 ;; Do not delete last space, which is
19263 ;; `org-table-separator-space', but the regular space before
19264 ;; it.
19265 (delete-region (- (point) 2) (1- (point))))))
19267 (setq org-table-may-need-update t)
19268 (self-insert-command N)
19269 (org-fix-tags-on-the-fly)
19270 (when org-self-insert-cluster-for-undo
19271 (if (not (eq last-command 'org-self-insert-command))
19272 (setq org-self-insert-command-undo-counter 1)
19273 (if (>= org-self-insert-command-undo-counter 20)
19274 (setq org-self-insert-command-undo-counter 1)
19275 (and (> org-self-insert-command-undo-counter 0)
19276 buffer-undo-list (listp buffer-undo-list)
19277 (not (cadr buffer-undo-list)) ; remove nil entry
19278 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19279 (setq org-self-insert-command-undo-counter
19280 (1+ org-self-insert-command-undo-counter))))))))
19282 (defun org-check-before-invisible-edit (kind)
19283 "Check is editing if kind KIND would be dangerous with invisible text around.
19284 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19285 ;; First, try to get out of here as quickly as possible, to reduce overhead
19286 (when (and org-catch-invisible-edits
19287 (or (not (boundp 'visible-mode)) (not visible-mode))
19288 (or (get-char-property (point) 'invisible)
19289 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19290 ;; OK, we need to take a closer look. Do not consider
19291 ;; invisibility obtained through text properties (e.g., link
19292 ;; fontification), as it cannot be toggled.
19293 (let* ((invisible-at-point
19294 (pcase (get-char-property-and-overlay (point) 'invisible)
19295 (`(,_ . ,(and (pred overlayp) o)) o)))
19296 ;; Assume that point cannot land in the middle of an
19297 ;; overlay, or between two overlays.
19298 (invisible-before-point
19299 (and (not invisible-at-point)
19300 (not (bobp))
19301 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19302 (`(,_ . ,(and (pred overlayp) o)) o))))
19303 (border-and-ok-direction
19305 ;; Check if we are acting predictably before invisible
19306 ;; text.
19307 (and invisible-at-point
19308 (memq kind '(insert delete-backward)))
19309 ;; Check if we are acting predictably after invisible text
19310 ;; This works not well, and I have turned it off. It seems
19311 ;; better to always show and stop after invisible text.
19312 ;; (and (not invisible-at-point) invisible-before-point
19313 ;; (memq kind '(insert delete)))
19315 (when (or invisible-at-point invisible-before-point)
19316 (when (eq org-catch-invisible-edits 'error)
19317 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19318 (if (and org-custom-properties-overlays
19319 (y-or-n-p "Display invisible properties in this buffer? "))
19320 (org-toggle-custom-properties-visibility)
19321 ;; Make the area visible
19322 (save-excursion
19323 (when invisible-before-point
19324 (goto-char
19325 (previous-single-char-property-change (point) 'invisible)))
19326 ;; Remove whatever overlay is currently making yet-to-be
19327 ;; edited text invisible. Also remove nested invisibility
19328 ;; related overlays.
19329 (delete-overlay (or invisible-at-point invisible-before-point))
19330 (let ((origin (if invisible-at-point (point) (1- (point)))))
19331 (while (pcase (get-char-property-and-overlay origin 'invisible)
19332 (`(,_ . ,(and (pred overlayp) o))
19333 (delete-overlay o)
19334 t)))))
19335 (cond
19336 ((eq org-catch-invisible-edits 'show)
19337 ;; That's it, we do the edit after showing
19338 (message
19339 "Unfolding invisible region around point before editing")
19340 (sit-for 1))
19341 ((and (eq org-catch-invisible-edits 'smart)
19342 border-and-ok-direction)
19343 (message "Unfolding invisible region around point before editing"))
19345 ;; Don't do the edit, make the user repeat it in full visibility
19346 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19348 (defun org-fix-tags-on-the-fly ()
19349 "Align tags in headline at point.
19350 Unlike to `org-set-tags', it ignores region and sorting."
19351 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19352 (org-at-heading-p))
19353 (let ((org-ignore-region t)
19354 (org-tags-sort-function nil))
19355 (org-set-tags nil t))))
19357 (defun org-delete-backward-char (N)
19358 "Like `delete-backward-char', insert whitespace at field end in tables.
19359 When deleting backwards, in tables this function will insert whitespace in
19360 front of the next \"|\" separator, to keep the table aligned. The table will
19361 still be marked for re-alignment if the field did fill the entire column,
19362 because, in this case the deletion might narrow the column."
19363 (interactive "p")
19364 (save-match-data
19365 (org-check-before-invisible-edit 'delete-backward)
19366 (if (and (= N 1)
19367 (not overwrite-mode)
19368 (not (org-region-active-p))
19369 (not (eq (char-before) ?|))
19370 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19371 (looking-at-p ".*?|")
19372 (org-at-table-p))
19373 (progn (forward-char -1) (org-delete-char 1))
19374 (backward-delete-char N)
19375 (org-fix-tags-on-the-fly))))
19377 (defun org-delete-char (N)
19378 "Like `delete-char', but insert whitespace at field end in tables.
19379 When deleting characters, in tables this function will insert whitespace in
19380 front of the next \"|\" separator, to keep the table aligned. The table will
19381 still be marked for re-alignment if the field did fill the entire column,
19382 because, in this case the deletion might narrow the column."
19383 (interactive "p")
19384 (save-match-data
19385 (org-check-before-invisible-edit 'delete)
19386 (cond
19387 ((or (/= N 1)
19388 (eq (char-after) ?|)
19389 (save-excursion (skip-chars-backward " \t") (bolp))
19390 (not (org-at-table-p)))
19391 (delete-char N)
19392 (org-fix-tags-on-the-fly))
19393 ((looking-at ".\\(.*?\\)|")
19394 (let* ((update? org-table-may-need-update)
19395 (noalign (looking-at-p ".*? |")))
19396 (delete-char 1)
19397 (org-table-with-shrunk-field
19398 (save-excursion
19399 ;; Last space is `org-table-separator-space', so insert
19400 ;; a regular one before it instead.
19401 (goto-char (- (match-end 0) 2))
19402 (insert " ")))
19403 ;; If there were two spaces at the end, this field does not
19404 ;; determine the width of the column.
19405 (when noalign (setq org-table-may-need-update update?))))
19407 (delete-char N)))))
19409 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19410 (put 'org-self-insert-command 'delete-selection
19411 (lambda ()
19412 (not (run-hook-with-args-until-success
19413 'self-insert-uses-region-functions))))
19414 (put 'orgtbl-self-insert-command 'delete-selection
19415 (lambda ()
19416 (not (run-hook-with-args-until-success
19417 'self-insert-uses-region-functions))))
19418 (put 'org-delete-char 'delete-selection 'supersede)
19419 (put 'org-delete-backward-char 'delete-selection 'supersede)
19420 (put 'org-yank 'delete-selection 'yank)
19422 ;; Make `flyspell-mode' delay after some commands
19423 (put 'org-self-insert-command 'flyspell-delayed t)
19424 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19425 (put 'org-delete-char 'flyspell-delayed t)
19426 (put 'org-delete-backward-char 'flyspell-delayed t)
19428 ;; Make pabbrev-mode expand after Org mode commands
19429 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19430 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19432 (defun org-transpose-words ()
19433 "Transpose words for Org.
19434 This uses the `org-mode-transpose-word-syntax-table' syntax
19435 table, which interprets characters in `org-emphasis-alist' as
19436 word constituents."
19437 (interactive)
19438 (with-syntax-table org-mode-transpose-word-syntax-table
19439 (call-interactively 'transpose-words)))
19441 (defvar org-ctrl-c-ctrl-c-hook nil
19442 "Hook for functions attaching themselves to `C-c C-c'.
19444 This can be used to add additional functionality to the C-c C-c
19445 key which executes context-dependent commands. This hook is run
19446 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19447 run after the last test.
19449 Each function will be called with no arguments. The function
19450 must check if the context is appropriate for it to act. If yes,
19451 it should do its thing and then return a non-nil value. If the
19452 context is wrong, just do nothing and return nil.")
19454 (defvar org-ctrl-c-ctrl-c-final-hook nil
19455 "Hook for functions attaching themselves to `C-c C-c'.
19457 This can be used to add additional functionality to the C-c C-c
19458 key which executes context-dependent commands. This hook is run
19459 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19460 before the first test.
19462 Each function will be called with no arguments. The function
19463 must check if the context is appropriate for it to act. If yes,
19464 it should do its thing and then return a non-nil value. If the
19465 context is wrong, just do nothing and return nil.")
19467 (defvar org-tab-first-hook nil
19468 "Hook for functions to attach themselves to TAB.
19469 See `org-ctrl-c-ctrl-c-hook' for more information.
19470 This hook runs as the first action when TAB is pressed, even before
19471 `org-cycle' messes around with the `outline-regexp' to cater for
19472 inline tasks and plain list item folding.
19473 If any function in this hook returns t, any other actions that
19474 would have been caused by TAB (such as table field motion or visibility
19475 cycling) will not occur.")
19477 (defvar org-tab-after-check-for-table-hook nil
19478 "Hook for functions to attach themselves to TAB.
19479 See `org-ctrl-c-ctrl-c-hook' for more information.
19480 This hook runs after it has been established that the cursor is not in a
19481 table, but before checking if the cursor is in a headline or if global cycling
19482 should be done.
19483 If any function in this hook returns t, not other actions like visibility
19484 cycling will be done.")
19486 (defvar org-tab-after-check-for-cycling-hook nil
19487 "Hook for functions to attach themselves to TAB.
19488 See `org-ctrl-c-ctrl-c-hook' for more information.
19489 This hook runs after it has been established that not table field motion and
19490 not visibility should be done because of current context. This is probably
19491 the place where a package like yasnippets can hook in.")
19493 (defvar org-tab-before-tab-emulation-hook nil
19494 "Hook for functions to attach themselves to TAB.
19495 See `org-ctrl-c-ctrl-c-hook' for more information.
19496 This hook runs after every other options for TAB have been exhausted, but
19497 before indentation and \t insertion takes place.")
19499 (defvar org-metaleft-hook nil
19500 "Hook for functions attaching themselves to `M-left'.
19501 See `org-ctrl-c-ctrl-c-hook' for more information.")
19502 (defvar org-metaright-hook nil
19503 "Hook for functions attaching themselves to `M-right'.
19504 See `org-ctrl-c-ctrl-c-hook' for more information.")
19505 (defvar org-metaup-hook nil
19506 "Hook for functions attaching themselves to `M-up'.
19507 See `org-ctrl-c-ctrl-c-hook' for more information.")
19508 (defvar org-metadown-hook nil
19509 "Hook for functions attaching themselves to `M-down'.
19510 See `org-ctrl-c-ctrl-c-hook' for more information.")
19511 (defvar org-shiftmetaleft-hook nil
19512 "Hook for functions attaching themselves to `M-S-left'.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.")
19514 (defvar org-shiftmetaright-hook nil
19515 "Hook for functions attaching themselves to `M-S-right'.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.")
19517 (defvar org-shiftmetaup-hook nil
19518 "Hook for functions attaching themselves to `M-S-up'.
19519 See `org-ctrl-c-ctrl-c-hook' for more information.")
19520 (defvar org-shiftmetadown-hook nil
19521 "Hook for functions attaching themselves to `M-S-down'.
19522 See `org-ctrl-c-ctrl-c-hook' for more information.")
19523 (defvar org-metareturn-hook nil
19524 "Hook for functions attaching themselves to `M-RET'.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.")
19526 (defvar org-shiftup-hook nil
19527 "Hook for functions attaching themselves to `S-up'.
19528 See `org-ctrl-c-ctrl-c-hook' for more information.")
19529 (defvar org-shiftup-final-hook nil
19530 "Hook for functions attaching themselves to `S-up'.
19531 This one runs after all other options except shift-select have been excluded.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.")
19533 (defvar org-shiftdown-hook nil
19534 "Hook for functions attaching themselves to `S-down'.
19535 See `org-ctrl-c-ctrl-c-hook' for more information.")
19536 (defvar org-shiftdown-final-hook nil
19537 "Hook for functions attaching themselves to `S-down'.
19538 This one runs after all other options except shift-select have been excluded.
19539 See `org-ctrl-c-ctrl-c-hook' for more information.")
19540 (defvar org-shiftleft-hook nil
19541 "Hook for functions attaching themselves to `S-left'.
19542 See `org-ctrl-c-ctrl-c-hook' for more information.")
19543 (defvar org-shiftleft-final-hook nil
19544 "Hook for functions attaching themselves to `S-left'.
19545 This one runs after all other options except shift-select have been excluded.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-shiftright-hook nil
19548 "Hook for functions attaching themselves to `S-right'.
19549 See `org-ctrl-c-ctrl-c-hook' for more information.")
19550 (defvar org-shiftright-final-hook nil
19551 "Hook for functions attaching themselves to `S-right'.
19552 This one runs after all other options except shift-select have been excluded.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defun org-modifier-cursor-error ()
19556 "Throw an error, a modified cursor command was applied in wrong context."
19557 (user-error "This command is active in special context like tables, headlines or items"))
19559 (defun org-shiftselect-error ()
19560 "Throw an error because Shift-Cursor command was applied in wrong context."
19561 (if (and (boundp 'shift-select-mode) shift-select-mode)
19562 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19563 (user-error "This command works only in special context like headlines or timestamps")))
19565 (defun org-call-for-shift-select (cmd)
19566 (let ((this-command-keys-shift-translated t))
19567 (call-interactively cmd)))
19569 (defun org-shifttab (&optional arg)
19570 "Global visibility cycling or move to previous table field.
19571 Call `org-table-previous-field' within a table.
19572 When ARG is nil, cycle globally through visibility states.
19573 When ARG is a numeric prefix, show contents of this level."
19574 (interactive "P")
19575 (cond
19576 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19577 ((integerp arg)
19578 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19579 (message "Content view to level: %d" arg)
19580 (org-content (prefix-numeric-value arg2))
19581 (org-cycle-show-empty-lines t)
19582 (setq org-cycle-global-status 'overview)))
19583 (t (call-interactively 'org-global-cycle))))
19585 (defun org-shiftmetaleft ()
19586 "Promote subtree or delete table column.
19587 Calls `org-promote-subtree', `org-outdent-item-tree', or
19588 `org-table-delete-column', depending on context. See the
19589 individual commands for more information."
19590 (interactive)
19591 (cond
19592 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19593 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19594 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19595 ((if (not (org-region-active-p)) (org-at-item-p)
19596 (save-excursion (goto-char (region-beginning))
19597 (org-at-item-p)))
19598 (call-interactively 'org-outdent-item-tree))
19599 (t (org-modifier-cursor-error))))
19601 (defun org-shiftmetaright ()
19602 "Demote subtree or insert table column.
19603 Calls `org-demote-subtree', `org-indent-item-tree', or
19604 `org-table-insert-column', depending on context. See the
19605 individual commands for more information."
19606 (interactive)
19607 (cond
19608 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19609 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19610 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19611 ((if (not (org-region-active-p)) (org-at-item-p)
19612 (save-excursion (goto-char (region-beginning))
19613 (org-at-item-p)))
19614 (call-interactively 'org-indent-item-tree))
19615 (t (org-modifier-cursor-error))))
19617 (defun org-shiftmetaup (&optional _arg)
19618 "Drag the line at point up.
19619 In a table, kill the current row.
19620 On a clock timestamp, update the value of the timestamp like `S-<up>'
19621 but also adjust the previous clocked item in the clock history.
19622 Everywhere else, drag the line at point up."
19623 (interactive "P")
19624 (cond
19625 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19626 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19627 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19628 (call-interactively 'org-timestamp-up)))
19629 (t (call-interactively 'org-drag-line-backward))))
19631 (defun org-shiftmetadown (&optional _arg)
19632 "Drag the line at point down.
19633 In a table, insert an empty row at the current line.
19634 On a clock timestamp, update the value of the timestamp like `S-<down>'
19635 but also adjust the previous clocked item in the clock history.
19636 Everywhere else, drag the line at point down."
19637 (interactive "P")
19638 (cond
19639 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19640 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19641 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19642 (call-interactively 'org-timestamp-down)))
19643 (t (call-interactively 'org-drag-line-forward))))
19645 (defsubst org-hidden-tree-error ()
19646 (user-error
19647 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19649 (defun org-metaleft (&optional _arg)
19650 "Promote heading, list item at point or move table column left.
19652 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19653 depending on context. With no specific context, calls the Emacs
19654 default `backward-word'. See the individual commands for more
19655 information.
19657 This function runs the hook `org-metaleft-hook' as a first step,
19658 and returns at first non-nil value."
19659 (interactive "P")
19660 (cond
19661 ((run-hook-with-args-until-success 'org-metaleft-hook))
19662 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19663 ((org-with-limited-levels
19664 (or (org-at-heading-p)
19665 (and (org-region-active-p)
19666 (save-excursion
19667 (goto-char (region-beginning))
19668 (org-at-heading-p)))))
19669 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19670 (call-interactively 'org-do-promote))
19671 ;; At an inline task.
19672 ((org-at-heading-p)
19673 (call-interactively 'org-inlinetask-promote))
19674 ((or (org-at-item-p)
19675 (and (org-region-active-p)
19676 (save-excursion
19677 (goto-char (region-beginning))
19678 (org-at-item-p))))
19679 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19680 (call-interactively 'org-outdent-item))
19681 (t (call-interactively 'backward-word))))
19683 (defun org-metaright (&optional _arg)
19684 "Demote heading, list item at point or move table column right.
19686 In front of a drawer or a block keyword, indent it correctly.
19688 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19689 `org-indent-drawer' or `org-indent-block' depending on context.
19690 With no specific context, calls the Emacs default `forward-word'.
19691 See the individual commands for more information.
19693 This function runs the hook `org-metaright-hook' as a first step,
19694 and returns at first non-nil value."
19695 (interactive "P")
19696 (cond
19697 ((run-hook-with-args-until-success 'org-metaright-hook))
19698 ((org-at-table-p) (call-interactively 'org-table-move-column))
19699 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19700 ((org-at-block-p) (call-interactively 'org-indent-block))
19701 ((org-with-limited-levels
19702 (or (org-at-heading-p)
19703 (and (org-region-active-p)
19704 (save-excursion
19705 (goto-char (region-beginning))
19706 (org-at-heading-p)))))
19707 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19708 (call-interactively 'org-do-demote))
19709 ;; At an inline task.
19710 ((org-at-heading-p)
19711 (call-interactively 'org-inlinetask-demote))
19712 ((or (org-at-item-p)
19713 (and (org-region-active-p)
19714 (save-excursion
19715 (goto-char (region-beginning))
19716 (org-at-item-p))))
19717 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19718 (call-interactively 'org-indent-item))
19719 (t (call-interactively 'forward-word))))
19721 (defun org-check-for-hidden (what)
19722 "Check if there are hidden headlines/items in the current visual line.
19723 WHAT can be either `headlines' or `items'. If the current line is
19724 an outline or item heading and it has a folded subtree below it,
19725 this function returns t, nil otherwise."
19726 (let ((re (cond
19727 ((eq what 'headlines) org-outline-regexp-bol)
19728 ((eq what 'items) (org-item-beginning-re))
19729 (t (error "This should not happen"))))
19730 beg end)
19731 (save-excursion
19732 (catch 'exit
19733 (unless (org-region-active-p)
19734 (setq beg (point-at-bol))
19735 (beginning-of-line 2)
19736 (while (and (not (eobp)) ;; this is like `next-line'
19737 (get-char-property (1- (point)) 'invisible))
19738 (beginning-of-line 2))
19739 (setq end (point))
19740 (goto-char beg)
19741 (goto-char (point-at-eol))
19742 (setq end (max end (point)))
19743 (while (re-search-forward re end t)
19744 (when (get-char-property (match-beginning 0) 'invisible)
19745 (throw 'exit t))))
19746 nil))))
19748 (defun org-metaup (&optional _arg)
19749 "Move subtree up or move table row up.
19750 Calls `org-move-subtree-up' or `org-table-move-row' or
19751 `org-move-item-up', depending on context. See the individual commands
19752 for more information."
19753 (interactive "P")
19754 (cond
19755 ((run-hook-with-args-until-success 'org-metaup-hook))
19756 ((org-region-active-p)
19757 (let* ((a (min (region-beginning) (region-end)))
19758 (b (1- (max (region-beginning) (region-end))))
19759 (c (save-excursion (goto-char a)
19760 (move-beginning-of-line 0)))
19761 (d (save-excursion (goto-char a)
19762 (move-end-of-line 0) (point))))
19763 (transpose-regions a b c d)
19764 (goto-char c)))
19765 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19766 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19767 ((org-at-item-p) (call-interactively 'org-move-item-up))
19768 (t (org-drag-element-backward))))
19770 (defun org-metadown (&optional _arg)
19771 "Move subtree down or move table row down.
19772 Calls `org-move-subtree-down' or `org-table-move-row' or
19773 `org-move-item-down', depending on context. See the individual
19774 commands for more information."
19775 (interactive "P")
19776 (cond
19777 ((run-hook-with-args-until-success 'org-metadown-hook))
19778 ((org-region-active-p)
19779 (let* ((a (min (region-beginning) (region-end)))
19780 (b (max (region-beginning) (region-end)))
19781 (c (save-excursion (goto-char b)
19782 (move-beginning-of-line 1)))
19783 (d (save-excursion (goto-char b)
19784 (move-end-of-line 1) (1+ (point)))))
19785 (transpose-regions a b c d)
19786 (goto-char d)))
19787 ((org-at-table-p) (call-interactively 'org-table-move-row))
19788 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19789 ((org-at-item-p) (call-interactively 'org-move-item-down))
19790 (t (org-drag-element-forward))))
19792 (defun org-shiftup (&optional arg)
19793 "Increase item in timestamp or increase priority of current headline.
19794 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19795 depending on context. See the individual commands for more information."
19796 (interactive "P")
19797 (cond
19798 ((run-hook-with-args-until-success 'org-shiftup-hook))
19799 ((and org-support-shift-select (org-region-active-p))
19800 (org-call-for-shift-select 'previous-line))
19801 ((org-at-timestamp-p 'lax)
19802 (call-interactively (if org-edit-timestamp-down-means-later
19803 'org-timestamp-down 'org-timestamp-up)))
19804 ((and (not (eq org-support-shift-select 'always))
19805 org-enable-priority-commands
19806 (org-at-heading-p))
19807 (call-interactively 'org-priority-up))
19808 ((and (not org-support-shift-select) (org-at-item-p))
19809 (call-interactively 'org-previous-item))
19810 ((org-clocktable-try-shift 'up arg))
19811 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19812 (org-support-shift-select
19813 (org-call-for-shift-select 'previous-line))
19814 (t (org-shiftselect-error))))
19816 (defun org-shiftdown (&optional arg)
19817 "Decrease item in timestamp or decrease priority of current headline.
19818 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19819 depending on context. See the individual commands for more information."
19820 (interactive "P")
19821 (cond
19822 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19823 ((and org-support-shift-select (org-region-active-p))
19824 (org-call-for-shift-select 'next-line))
19825 ((org-at-timestamp-p 'lax)
19826 (call-interactively (if org-edit-timestamp-down-means-later
19827 'org-timestamp-up 'org-timestamp-down)))
19828 ((and (not (eq org-support-shift-select 'always))
19829 org-enable-priority-commands
19830 (org-at-heading-p))
19831 (call-interactively 'org-priority-down))
19832 ((and (not org-support-shift-select) (org-at-item-p))
19833 (call-interactively 'org-next-item))
19834 ((org-clocktable-try-shift 'down arg))
19835 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19836 (org-support-shift-select
19837 (org-call-for-shift-select 'next-line))
19838 (t (org-shiftselect-error))))
19840 (defun org-shiftright (&optional arg)
19841 "Cycle the thing at point or in the current line, depending on context.
19842 Depending on context, this does one of the following:
19844 - switch a timestamp at point one day into the future
19845 - on a headline, switch to the next TODO keyword.
19846 - on an item, switch entire list to the next bullet type
19847 - on a property line, switch to the next allowed value
19848 - on a clocktable definition line, move time block into the future"
19849 (interactive "P")
19850 (cond
19851 ((run-hook-with-args-until-success 'org-shiftright-hook))
19852 ((and org-support-shift-select (org-region-active-p))
19853 (org-call-for-shift-select 'forward-char))
19854 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19855 ((and (not (eq org-support-shift-select 'always))
19856 (org-at-heading-p))
19857 (let ((org-inhibit-logging
19858 (not org-treat-S-cursor-todo-selection-as-state-change))
19859 (org-inhibit-blocking
19860 (not org-treat-S-cursor-todo-selection-as-state-change)))
19861 (org-call-with-arg 'org-todo 'right)))
19862 ((or (and org-support-shift-select
19863 (not (eq org-support-shift-select 'always))
19864 (org-at-item-bullet-p))
19865 (and (not org-support-shift-select) (org-at-item-p)))
19866 (org-call-with-arg 'org-cycle-list-bullet nil))
19867 ((and (not (eq org-support-shift-select 'always))
19868 (org-at-property-p))
19869 (call-interactively 'org-property-next-allowed-value))
19870 ((org-clocktable-try-shift 'right arg))
19871 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19872 (org-support-shift-select
19873 (org-call-for-shift-select 'forward-char))
19874 (t (org-shiftselect-error))))
19876 (defun org-shiftleft (&optional arg)
19877 "Cycle the thing at point or in the current line, depending on context.
19878 Depending on context, this does one of the following:
19880 - switch a timestamp at point one day into the past
19881 - on a headline, switch to the previous TODO keyword.
19882 - on an item, switch entire list to the previous bullet type
19883 - on a property line, switch to the previous allowed value
19884 - on a clocktable definition line, move time block into the past"
19885 (interactive "P")
19886 (cond
19887 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19888 ((and org-support-shift-select (org-region-active-p))
19889 (org-call-for-shift-select 'backward-char))
19890 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19891 ((and (not (eq org-support-shift-select 'always))
19892 (org-at-heading-p))
19893 (let ((org-inhibit-logging
19894 (not org-treat-S-cursor-todo-selection-as-state-change))
19895 (org-inhibit-blocking
19896 (not org-treat-S-cursor-todo-selection-as-state-change)))
19897 (org-call-with-arg 'org-todo 'left)))
19898 ((or (and org-support-shift-select
19899 (not (eq org-support-shift-select 'always))
19900 (org-at-item-bullet-p))
19901 (and (not org-support-shift-select) (org-at-item-p)))
19902 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19903 ((and (not (eq org-support-shift-select 'always))
19904 (org-at-property-p))
19905 (call-interactively 'org-property-previous-allowed-value))
19906 ((org-clocktable-try-shift 'left arg))
19907 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19908 (org-support-shift-select
19909 (org-call-for-shift-select 'backward-char))
19910 (t (org-shiftselect-error))))
19912 (defun org-shiftcontrolright ()
19913 "Switch to next TODO set."
19914 (interactive)
19915 (cond
19916 ((and org-support-shift-select (org-region-active-p))
19917 (org-call-for-shift-select 'forward-word))
19918 ((and (not (eq org-support-shift-select 'always))
19919 (org-at-heading-p))
19920 (org-call-with-arg 'org-todo 'nextset))
19921 (org-support-shift-select
19922 (org-call-for-shift-select 'forward-word))
19923 (t (org-shiftselect-error))))
19925 (defun org-shiftcontrolleft ()
19926 "Switch to previous TODO set."
19927 (interactive)
19928 (cond
19929 ((and org-support-shift-select (org-region-active-p))
19930 (org-call-for-shift-select 'backward-word))
19931 ((and (not (eq org-support-shift-select 'always))
19932 (org-at-heading-p))
19933 (org-call-with-arg 'org-todo 'previousset))
19934 (org-support-shift-select
19935 (org-call-for-shift-select 'backward-word))
19936 (t (org-shiftselect-error))))
19938 (defun org-shiftcontrolup (&optional n)
19939 "Change timestamps synchronously up in CLOCK log lines.
19940 Optional argument N tells to change by that many units."
19941 (interactive "P")
19942 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19943 (let (org-support-shift-select)
19944 (org-clock-timestamps-up n))
19945 (user-error "Not at a clock log")))
19947 (defun org-shiftcontroldown (&optional n)
19948 "Change timestamps synchronously down in CLOCK log lines.
19949 Optional argument N tells to change by that many units."
19950 (interactive "P")
19951 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19952 (let (org-support-shift-select)
19953 (org-clock-timestamps-down n))
19954 (user-error "Not at a clock log")))
19956 (defun org-increase-number-at-point (&optional inc)
19957 "Increment the number at point.
19958 With an optional prefix numeric argument INC, increment using
19959 this numeric value."
19960 (interactive "p")
19961 (if (not (number-at-point))
19962 (user-error "Not on a number")
19963 (unless inc (setq inc 1))
19964 (let ((pos (point))
19965 (beg (skip-chars-backward "-+^/*0-9eE."))
19966 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19967 (setq nap (buffer-substring-no-properties
19968 (+ pos beg) (+ pos beg end)))
19969 (delete-region (+ pos beg) (+ pos beg end))
19970 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19971 (when (org-at-table-p)
19972 (org-table-align)
19973 (org-table-end-of-field 1))))
19975 (defun org-decrease-number-at-point (&optional inc)
19976 "Decrement the number at point.
19977 With an optional prefix numeric argument INC, decrement using
19978 this numeric value."
19979 (interactive "p")
19980 (org-increase-number-at-point (- (or inc 1))))
19982 (defun org-ctrl-c-ret ()
19983 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19984 (interactive)
19985 (cond
19986 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19987 (t (call-interactively 'org-insert-heading))))
19989 (defun org-find-visible ()
19990 (let ((s (point)))
19991 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19992 (get-char-property s 'invisible)))
19994 (defun org-find-invisible ()
19995 (let ((s (point)))
19996 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19997 (not (get-char-property s 'invisible))))
20000 (defun org-copy-visible (beg end)
20001 "Copy the visible parts of the region."
20002 (interactive "r")
20003 (let ((result ""))
20004 (while (/= beg end)
20005 (when (get-char-property beg 'invisible)
20006 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20007 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20008 (setq result (concat result (buffer-substring beg next)))
20009 (setq beg next)))
20010 (kill-new result)))
20012 (defun org-copy-special ()
20013 "Copy region in table or copy current subtree.
20014 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20015 context. See the individual commands for more information."
20016 (interactive)
20017 (call-interactively
20018 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20020 (defun org-cut-special ()
20021 "Cut region in table or cut current subtree.
20022 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20023 context. See the individual commands for more information."
20024 (interactive)
20025 (call-interactively
20026 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20028 (defun org-paste-special (arg)
20029 "Paste rectangular region into table, or past subtree relative to level.
20030 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20031 See the individual commands for more information."
20032 (interactive "P")
20033 (if (org-at-table-p)
20034 (org-table-paste-rectangle)
20035 (org-paste-subtree arg)))
20037 (defun org-edit-special (&optional arg)
20038 "Call a special editor for the element at point.
20039 When at a table, call the formula editor with `org-table-edit-formulas'.
20040 When in a source code block, call `org-edit-src-code'.
20041 When in a fixed-width region, call `org-edit-fixed-width-region'.
20042 When in an export block, call `org-edit-export-block'.
20043 When in a LaTeX environment, call `org-edit-latex-environment'.
20044 When at an #+INCLUDE keyword, visit the included file.
20045 When at a footnote reference, call `org-edit-footnote-reference'
20046 On a link, call `ffap' to visit the link at point.
20047 Otherwise, return a user error."
20048 (interactive "P")
20049 (let ((element (org-element-at-point)))
20050 (barf-if-buffer-read-only)
20051 (pcase (org-element-type element)
20052 (`src-block
20053 (if (not arg) (org-edit-src-code)
20054 (let* ((info (org-babel-get-src-block-info))
20055 (lang (nth 0 info))
20056 (params (nth 2 info))
20057 (session (cdr (assq :session params))))
20058 (if (not session) (org-edit-src-code)
20059 ;; At a src-block with a session and function called with
20060 ;; an ARG: switch to the buffer related to the inferior
20061 ;; process.
20062 (switch-to-buffer
20063 (funcall (intern (concat "org-babel-prep-session:" lang))
20064 session params))))))
20065 (`keyword
20066 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20067 (org-open-link-from-string
20068 (format "[[%s]]"
20069 (expand-file-name
20070 (let ((value (org-element-property :value element)))
20071 (cond ((org-file-url-p value)
20072 (user-error "The file is specified as a URL, cannot be edited"))
20073 ((not (org-string-nw-p value))
20074 (user-error "No file to edit"))
20075 ((string-match "\\`\"\\(.*?\\)\"" value)
20076 (match-string 1 value))
20077 ((string-match "\\`[^ \t\"]\\S-*" value)
20078 (match-string 0 value))
20079 (t (user-error "No valid file specified")))))))
20080 (user-error "No special environment to edit here")))
20081 (`table
20082 (if (eq (org-element-property :type element) 'table.el)
20083 (org-edit-table.el)
20084 (call-interactively 'org-table-edit-formulas)))
20085 ;; Only Org tables contain `table-row' type elements.
20086 (`table-row (call-interactively 'org-table-edit-formulas))
20087 (`example-block (org-edit-src-code))
20088 (`export-block (org-edit-export-block))
20089 (`fixed-width (org-edit-fixed-width-region))
20090 (`latex-environment (org-edit-latex-environment))
20092 ;; No notable element at point. Though, we may be at a link or
20093 ;; a footnote reference, which are objects. Thus, scan deeper.
20094 (let ((context (org-element-context element)))
20095 (pcase (org-element-type context)
20096 (`footnote-reference (org-edit-footnote-reference))
20097 (`inline-src-block (org-edit-inline-src-code))
20098 (`link (call-interactively #'ffap))
20099 (_ (user-error "No special environment to edit here"))))))))
20101 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20102 (defun org-ctrl-c-ctrl-c (&optional arg)
20103 "Set tags in headline, or update according to changed information at point.
20105 This command does many different things, depending on context:
20107 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20108 this is what we do.
20110 - If the cursor is on a statistics cookie, update it.
20112 - If the cursor is in a headline, prompt for tags and insert them
20113 into the current line, aligned to `org-tags-column'. When called
20114 with prefix arg, realign all tags in the current buffer.
20116 - If the cursor is in one of the special #+KEYWORD lines, this
20117 triggers scanning the buffer for these lines and updating the
20118 information.
20120 - If the cursor is inside a table, realign the table. This command
20121 works even if the automatic table editor has been turned off.
20123 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20124 the entire table.
20126 - If the cursor is at a footnote reference or definition, jump to
20127 the corresponding definition or references, respectively.
20129 - If the cursor is a the beginning of a dynamic block, update it.
20131 - If the current buffer is a capture buffer, close note and file it.
20133 - If the cursor is on a <<<target>>>, update radio targets and
20134 corresponding links in this buffer.
20136 - If the cursor is on a numbered item in a plain list, renumber the
20137 ordered list.
20139 - If the cursor is on a checkbox, toggle it.
20141 - If the cursor is on a code block, evaluate it. The variable
20142 `org-confirm-babel-evaluate' can be used to control prompting
20143 before code block evaluation, by default every code block
20144 evaluation requires confirmation. Code block evaluation can be
20145 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20146 (interactive "P")
20147 (cond
20148 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20149 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20150 (org-remove-occur-highlights)
20151 (message "Temporary highlights/overlays removed from current buffer"))
20152 ((and (local-variable-p 'org-finish-function)
20153 (fboundp org-finish-function))
20154 (funcall org-finish-function))
20155 ((org-babel-hash-at-point))
20156 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20158 (let* ((context
20159 (org-element-lineage
20160 (org-element-context)
20161 ;; Limit to supported contexts.
20162 '(babel-call clock dynamic-block footnote-definition
20163 footnote-reference inline-babel-call inline-src-block
20164 inlinetask item keyword node-property paragraph
20165 plain-list planning property-drawer radio-target
20166 src-block statistics-cookie table table-cell table-row
20167 timestamp)
20169 (type (org-element-type context)))
20170 ;; For convenience: at the first line of a paragraph on the same
20171 ;; line as an item, apply function on that item instead.
20172 (when (eq type 'paragraph)
20173 (let ((parent (org-element-property :parent context)))
20174 (when (and (eq (org-element-type parent) 'item)
20175 (= (line-beginning-position)
20176 (org-element-property :begin parent)))
20177 (setq context parent)
20178 (setq type 'item))))
20179 ;; Act according to type of element or object at point.
20181 ;; Do nothing on a blank line, except if it is contained in
20182 ;; a src block. Hence, we first check if point is in such
20183 ;; a block and then if it is at a blank line.
20184 (pcase type
20185 ((or `inline-src-block `src-block)
20186 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20187 (org-babel-eval-wipe-error-buffer)
20188 (org-babel-execute-src-block
20189 current-prefix-arg (org-babel-get-src-block-info nil context))))
20190 ((guard (org-match-line "[ \t]*$"))
20191 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20192 (user-error
20193 (substitute-command-keys
20194 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20195 ((or `babel-call `inline-babel-call)
20196 (let ((info (org-babel-lob-get-info context)))
20197 (when info (org-babel-execute-src-block nil info))))
20198 (`clock (org-clock-update-time-maybe))
20199 (`dynamic-block
20200 (save-excursion
20201 (goto-char (org-element-property :post-affiliated context))
20202 (org-update-dblock)))
20203 (`footnote-definition
20204 (goto-char (org-element-property :post-affiliated context))
20205 (call-interactively 'org-footnote-action))
20206 (`footnote-reference (call-interactively #'org-footnote-action))
20207 ((or `headline `inlinetask)
20208 (save-excursion (goto-char (org-element-property :begin context))
20209 (call-interactively #'org-set-tags)))
20210 (`item
20211 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20212 ;; unconditionally, whereas `C-u' will toggle its presence.
20213 ;; Without a universal argument, if the item has a checkbox,
20214 ;; toggle it. Otherwise repair the list.
20215 (let* ((box (org-element-property :checkbox context))
20216 (struct (org-element-property :structure context))
20217 (old-struct (copy-tree struct))
20218 (parents (org-list-parents-alist struct))
20219 (prevs (org-list-prevs-alist struct))
20220 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20221 (org-list-set-checkbox
20222 (org-element-property :begin context) struct
20223 (cond ((equal arg '(16)) "[-]")
20224 ((and (not box) (equal arg '(4))) "[ ]")
20225 ((or (not box) (equal arg '(4))) nil)
20226 ((eq box 'on) "[ ]")
20227 (t "[X]")))
20228 ;; Mimic `org-list-write-struct' but with grabbing a return
20229 ;; value from `org-list-struct-fix-box'.
20230 (org-list-struct-fix-ind struct parents 2)
20231 (org-list-struct-fix-item-end struct)
20232 (org-list-struct-fix-bul struct prevs)
20233 (org-list-struct-fix-ind struct parents)
20234 (let ((block-item
20235 (org-list-struct-fix-box struct parents prevs orderedp)))
20236 (if (and box (equal struct old-struct))
20237 (if (equal arg '(16))
20238 (message "Checkboxes already reset")
20239 (user-error "Cannot toggle this checkbox: %s"
20240 (if (eq box 'on)
20241 "all subitems checked"
20242 "unchecked subitems")))
20243 (org-list-struct-apply-struct struct old-struct)
20244 (org-update-checkbox-count-maybe))
20245 (when block-item
20246 (message "Checkboxes were removed due to empty box at line %d"
20247 (org-current-line block-item))))))
20248 (`keyword
20249 (let ((org-inhibit-startup-visibility-stuff t)
20250 (org-startup-align-all-tables nil))
20251 (when (boundp 'org-table-coordinate-overlays)
20252 (mapc #'delete-overlay org-table-coordinate-overlays)
20253 (setq org-table-coordinate-overlays nil))
20254 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20255 (message "Local setup has been refreshed"))
20256 (`plain-list
20257 ;; At a plain list, with a double C-u argument, set
20258 ;; checkboxes of each item to "[-]", whereas a single one
20259 ;; will toggle their presence according to the state of the
20260 ;; first item in the list. Without an argument, repair the
20261 ;; list.
20262 (let* ((begin (org-element-property :contents-begin context))
20263 (struct (org-element-property :structure context))
20264 (old-struct (copy-tree struct))
20265 (first-box (save-excursion
20266 (goto-char begin)
20267 (looking-at org-list-full-item-re)
20268 (match-string-no-properties 3)))
20269 (new-box (cond ((equal arg '(16)) "[-]")
20270 ((equal arg '(4)) (unless first-box "[ ]"))
20271 ((equal first-box "[X]") "[ ]")
20272 (t "[X]"))))
20273 (cond
20274 (arg
20275 (dolist (pos
20276 (org-list-get-all-items
20277 begin struct (org-list-prevs-alist struct)))
20278 (org-list-set-checkbox pos struct new-box)))
20279 ((and first-box (eq (point) begin))
20280 ;; For convenience, when point is at bol on the first
20281 ;; item of the list and no argument is provided, simply
20282 ;; toggle checkbox of that item, if any.
20283 (org-list-set-checkbox begin struct new-box)))
20284 (org-list-write-struct
20285 struct (org-list-parents-alist struct) old-struct)
20286 (org-update-checkbox-count-maybe)))
20287 ((or `property-drawer `node-property)
20288 (call-interactively #'org-property-action))
20289 (`radio-target
20290 (call-interactively #'org-update-radio-target-regexp))
20291 (`statistics-cookie
20292 (call-interactively #'org-update-statistics-cookies))
20293 ((or `table `table-cell `table-row)
20294 ;; At a table, recalculate every field and align it. Also
20295 ;; send the table if necessary. If the table has
20296 ;; a `table.el' type, just give up. At a table row or cell,
20297 ;; maybe recalculate line but always align table.
20298 (if (eq (org-element-property :type context) 'table.el)
20299 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20300 Use `\\[org-edit-special]' to edit table.el tables"))
20301 (if (or (eq type 'table)
20302 ;; Check if point is at a TBLFM line.
20303 (and (eq type 'table-row)
20304 (= (point) (org-element-property :end context))))
20305 (save-excursion
20306 (if (org-at-TBLFM-p)
20307 (progn (require 'org-table)
20308 (org-table-calc-current-TBLFM))
20309 (goto-char (org-element-property :contents-begin context))
20310 (org-call-with-arg 'org-table-recalculate (or arg t))
20311 (orgtbl-send-table 'maybe)))
20312 (org-table-maybe-eval-formula)
20313 (cond (arg (call-interactively #'org-table-recalculate))
20314 ((org-table-maybe-recalculate-line))
20315 (t (org-table-align))))))
20316 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20317 (org-timestamp-change 0 'day))
20318 ((and `nil (guard (org-at-heading-p)))
20319 ;; When point is on an unsupported object type, we can miss
20320 ;; the fact that it also is at a heading. Handle it here.
20321 (call-interactively #'org-set-tags))
20322 ((guard
20323 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20325 (user-error
20326 (substitute-command-keys
20327 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20329 (defun org-mode-restart ()
20330 (interactive)
20331 (let ((indent-status (bound-and-true-p org-indent-mode)))
20332 (funcall major-mode)
20333 (hack-local-variables)
20334 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20335 (org-indent-mode -1))
20336 (org-reset-file-cache))
20337 (message "%s restarted" major-mode))
20339 (defun org-kill-note-or-show-branches ()
20340 "Abort storing current note, or call `outline-show-branches'."
20341 (interactive)
20342 (if (not org-finish-function)
20343 (save-excursion
20344 (save-restriction
20345 (org-narrow-to-subtree)
20346 (org-flag-subtree t)
20347 (call-interactively 'outline-show-branches)
20348 (org-hide-archived-subtrees (point-min) (point-max))))
20349 (let ((org-note-abort t))
20350 (funcall org-finish-function))))
20352 (defun org-delete-indentation (&optional arg)
20353 "Join current line to previous and fix whitespace at join.
20355 If previous line is a headline add to headline title. Otherwise
20356 the function calls `delete-indentation'.
20358 With a non-nil optional argument, join it to the following one."
20359 (interactive "*P")
20360 (if (save-excursion
20361 (beginning-of-line (if arg 1 0))
20362 (let ((case-fold-search nil))
20363 (looking-at org-complex-heading-regexp)))
20364 ;; At headline.
20365 (let ((tags-column (when (match-beginning 5)
20366 (save-excursion (goto-char (match-beginning 5))
20367 (current-column))))
20368 (string (concat " " (progn (when arg (forward-line 1))
20369 (org-trim (delete-and-extract-region
20370 (line-beginning-position)
20371 (line-end-position)))))))
20372 (unless (bobp) (delete-region (point) (1- (point))))
20373 (goto-char (or (match-end 4)
20374 (match-beginning 5)
20375 (match-end 0)))
20376 (skip-chars-backward " \t")
20377 (save-excursion (insert string))
20378 ;; Adjust alignment of tags.
20379 (cond
20380 ((not tags-column)) ;no tags
20381 (org-auto-align-tags (org-set-tags nil t))
20382 (t (org--align-tags-here tags-column)))) ;preserve tags column
20383 (delete-indentation arg)))
20385 (defun org-open-line (n)
20386 "Insert a new row in tables, call `open-line' elsewhere.
20387 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20388 As a special case, when a document starts with a table, allow to
20389 call `open-line' on the very first character."
20390 (interactive "*p")
20391 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20392 (org-table-insert-row)
20393 (open-line n)))
20395 (defun org-return (&optional indent)
20396 "Goto next table row or insert a newline.
20398 Calls `org-table-next-row' or `newline', depending on context.
20400 When optional INDENT argument is non-nil, call
20401 `newline-and-indent' instead of `newline'.
20403 When `org-return-follows-link' is non-nil and point is on
20404 a timestamp or a link, call `org-open-at-point'. However, it
20405 will not happen if point is in a table or on a \"dead\"
20406 object (e.g., within a comment). In these case, you need to use
20407 `org-open-at-point' directly."
20408 (interactive)
20409 (let ((context (if org-return-follows-link (org-element-context)
20410 (org-element-at-point))))
20411 (cond
20412 ;; In a table, call `org-table-next-row'. However, before first
20413 ;; column or after last one, split the table.
20414 ((or (and (eq (org-element-type context) 'table)
20415 (>= (point) (org-element-property :contents-begin context))
20416 (< (point) (org-element-property :contents-end context)))
20417 (org-element-lineage context '(table-row table-cell) t))
20418 (if (or (looking-at-p "[ \t]*$")
20419 (save-excursion (skip-chars-backward " \t") (bolp)))
20420 (insert "\n")
20421 (org-table-justify-field-maybe)
20422 (call-interactively #'org-table-next-row)))
20423 ;; On a link or a timestamp, call `org-open-at-point' if
20424 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20425 ;; locations, e.g., in a comment, as `org-open-at-point'.
20426 ((and org-return-follows-link
20427 (or (org-in-regexp org-ts-regexp-both nil t)
20428 (org-in-regexp org-tsr-regexp-both nil t)
20429 (org-in-regexp org-any-link-re nil t)))
20430 (call-interactively #'org-open-at-point))
20431 ;; Insert newline in heading, but preserve tags.
20432 ((and (not (bolp))
20433 (save-excursion (beginning-of-line)
20434 (let ((case-fold-search nil))
20435 (looking-at org-complex-heading-regexp))))
20436 ;; At headline. Split line. However, if point is on keyword,
20437 ;; priority cookie or tags, do not break any of them: add
20438 ;; a newline after the headline instead.
20439 (let ((tags-column (and (match-beginning 5)
20440 (save-excursion (goto-char (match-beginning 5))
20441 (current-column))))
20442 (string
20443 (when (and (match-end 4) (org-point-in-group (point) 4))
20444 (delete-and-extract-region (point) (match-end 4)))))
20445 ;; Adjust tag alignment.
20446 (cond
20447 ((not (and tags-column string)))
20448 (org-auto-align-tags (org-set-tags nil t))
20449 (t (org--align-tags-here tags-column))) ;preserve tags column
20450 (end-of-line)
20451 (org-show-entry)
20452 (if indent (newline-and-indent) (newline))
20453 (when string (save-excursion (insert (org-trim string))))))
20454 ;; In a list, make sure indenting keeps trailing text within.
20455 ((and indent
20456 (not (eolp))
20457 (org-element-lineage context '(item)))
20458 (let ((trailing-data
20459 (delete-and-extract-region (point) (line-end-position))))
20460 (newline-and-indent)
20461 (save-excursion (insert trailing-data))))
20462 (t (if indent (newline-and-indent) (newline))))))
20464 (defun org-return-indent ()
20465 "Goto next table row or insert a newline and indent.
20466 Calls `org-table-next-row' or `newline-and-indent', depending on
20467 context. See the individual commands for more information."
20468 (interactive)
20469 (org-return t))
20471 (defun org-ctrl-c-tab (&optional _arg)
20472 "Toggle columns width in a table, or show children.
20473 Call `org-table-toggle-column-width' if point is in a table.
20474 Otherwise, call `org-show-children'."
20475 (interactive "p")
20476 (call-interactively
20477 (if (org-at-table-p) #'org-table-toggle-column-width
20478 #'org-show-children)))
20480 (defun org-ctrl-c-star ()
20481 "Compute table, or change heading status of lines.
20482 Calls `org-table-recalculate' or `org-toggle-heading',
20483 depending on context."
20484 (interactive)
20485 (cond
20486 ((org-at-table-p)
20487 (call-interactively 'org-table-recalculate))
20489 ;; Convert all lines in region to list items
20490 (call-interactively 'org-toggle-heading))))
20492 (defun org-ctrl-c-minus ()
20493 "Insert separator line in table or modify bullet status of line.
20494 Also turns a plain line or a region of lines into list items.
20495 Calls `org-table-insert-hline', `org-toggle-item', or
20496 `org-cycle-list-bullet', depending on context."
20497 (interactive)
20498 (cond
20499 ((org-at-table-p)
20500 (call-interactively 'org-table-insert-hline))
20501 ((org-region-active-p)
20502 (call-interactively 'org-toggle-item))
20503 ((org-in-item-p)
20504 (call-interactively 'org-cycle-list-bullet))
20506 (call-interactively 'org-toggle-item))))
20508 (defun org-toggle-heading (&optional nstars)
20509 "Convert headings to normal text, or items or text to headings.
20510 If there is no active region, only convert the current line.
20512 With a `\\[universal-argument]' prefix, convert the whole list at
20513 point into heading.
20515 In a region:
20517 - If the first non blank line is a headline, remove the stars
20518 from all headlines in the region.
20520 - If it is a normal line, turn each and every normal line (i.e.,
20521 not an heading or an item) in the region into headings. If you
20522 want to convert only the first line of this region, use one
20523 universal prefix argument.
20525 - If it is a plain list item, turn all plain list items into headings.
20527 When converting a line into a heading, the number of stars is chosen
20528 such that the lines become children of the current entry. However,
20529 when a numeric prefix argument is given, its value determines the
20530 number of stars to add."
20531 (interactive "P")
20532 (let ((skip-blanks
20533 (function
20534 ;; Return beginning of first non-blank line, starting from
20535 ;; line at POS.
20536 (lambda (pos)
20537 (save-excursion
20538 (goto-char pos)
20539 (while (org-at-comment-p) (forward-line))
20540 (skip-chars-forward " \r\t\n")
20541 (point-at-bol)))))
20542 beg end toggled)
20543 ;; Determine boundaries of changes. If a universal prefix has
20544 ;; been given, put the list in a region. If region ends at a bol,
20545 ;; do not consider the last line to be in the region.
20547 (when (and current-prefix-arg (org-at-item-p))
20548 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20549 (org-mark-element))
20551 (if (org-region-active-p)
20552 (setq beg (funcall skip-blanks (region-beginning))
20553 end (copy-marker (save-excursion
20554 (goto-char (region-end))
20555 (if (bolp) (point) (point-at-eol)))))
20556 (setq beg (funcall skip-blanks (point-at-bol))
20557 end (copy-marker (point-at-eol))))
20558 ;; Ensure inline tasks don't count as headings.
20559 (org-with-limited-levels
20560 (save-excursion
20561 (goto-char beg)
20562 (cond
20563 ;; Case 1. Started at an heading: de-star headings.
20564 ((org-at-heading-p)
20565 (while (< (point) end)
20566 (when (org-at-heading-p t)
20567 (looking-at org-outline-regexp) (replace-match "")
20568 (setq toggled t))
20569 (forward-line)))
20570 ;; Case 2. Started at an item: change items into headlines.
20571 ;; One star will be added by `org-list-to-subtree'.
20572 ((org-at-item-p)
20573 (while (< (point) end)
20574 (when (org-at-item-p)
20575 ;; Pay attention to cases when region ends before list.
20576 (let* ((struct (org-list-struct))
20577 (list-end
20578 (min (org-list-get-bottom-point struct) (1+ end))))
20579 (save-restriction
20580 (narrow-to-region (point) list-end)
20581 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20582 (setq toggled t))
20583 (forward-line)))
20584 ;; Case 3. Started at normal text: make every line an heading,
20585 ;; skipping headlines and items.
20586 (t (let* ((stars
20587 (make-string
20588 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20589 (add-stars
20590 (cond (nstars "") ; stars from prefix only
20591 ((equal stars "") "*") ; before first heading
20592 (org-odd-levels-only "**") ; inside heading, odd
20593 (t "*"))) ; inside heading, oddeven
20594 (rpl (concat stars add-stars " "))
20595 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20596 (while (< (point) (if (equal nstars '(4)) lend end))
20597 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20598 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20599 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20600 (forward-line)))))))
20601 (unless toggled (message "Cannot toggle heading from here"))))
20603 (defun org-meta-return (&optional arg)
20604 "Insert a new heading or wrap a region in a table.
20605 Calls `org-insert-heading', `org-insert-item' or
20606 `org-table-wrap-region', depending on context. When called with
20607 an argument, unconditionally call `org-insert-heading'."
20608 (interactive "P")
20609 (org-check-before-invisible-edit 'insert)
20610 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20611 (call-interactively (cond (arg #'org-insert-heading)
20612 ((org-at-table-p) #'org-table-wrap-region)
20613 ((org-in-item-p) #'org-insert-item)
20614 (t #'org-insert-heading)))))
20616 ;;; Menu entries
20618 (defsubst org-in-subtree-not-table-p ()
20619 "Are we in a subtree and not in a table?"
20620 (and (not (org-before-first-heading-p))
20621 (not (org-at-table-p))))
20623 ;; Define the Org mode menus
20624 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20625 '("Tbl"
20626 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20627 ["Next Field" org-cycle (org-at-table-p)]
20628 ["Previous Field" org-shifttab (org-at-table-p)]
20629 ["Next Row" org-return (org-at-table-p)]
20630 "--"
20631 ["Blank Field" org-table-blank-field (org-at-table-p)]
20632 ["Edit Field" org-table-edit-field (org-at-table-p)]
20633 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20634 "--"
20635 ("Column"
20636 ["Move Column Left" org-metaleft (org-at-table-p)]
20637 ["Move Column Right" org-metaright (org-at-table-p)]
20638 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20639 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20640 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20641 ("Row"
20642 ["Move Row Up" org-metaup (org-at-table-p)]
20643 ["Move Row Down" org-metadown (org-at-table-p)]
20644 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20645 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20646 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20647 "--"
20648 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20649 ("Rectangle"
20650 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20651 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20652 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20653 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20654 "--"
20655 ("Calculate"
20656 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20657 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20658 ["Edit Formulas" org-edit-special (org-at-table-p)]
20659 "--"
20660 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20661 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20662 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20663 "--"
20664 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20665 "--"
20666 ["Sum Column/Rectangle" org-table-sum
20667 (or (org-at-table-p) (org-region-active-p))]
20668 ["Which Column?" org-table-current-column (org-at-table-p)])
20669 ["Debug Formulas"
20670 org-table-toggle-formula-debugger
20671 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20672 ["Show Col/Row Numbers"
20673 org-table-toggle-coordinate-overlays
20674 :style toggle
20675 :selected (bound-and-true-p org-table-overlay-coordinates)]
20676 "--"
20677 ["Create" org-table-create (not (org-at-table-p))]
20678 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20679 ["Import from File" org-table-import (not (org-at-table-p))]
20680 ["Export to File" org-table-export (org-at-table-p)]
20681 "--"
20682 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20683 "--"
20684 ("Plot"
20685 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20686 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20688 (easy-menu-define org-org-menu org-mode-map "Org menu"
20689 '("Org"
20690 ("Show/Hide"
20691 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20692 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20693 ["Sparse Tree..." org-sparse-tree t]
20694 ["Reveal Context" org-reveal t]
20695 ["Show All" org-show-all t]
20696 "--"
20697 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20698 "--"
20699 ["New Heading" org-insert-heading t]
20700 ("Navigate Headings"
20701 ["Up" outline-up-heading t]
20702 ["Next" outline-next-visible-heading t]
20703 ["Previous" outline-previous-visible-heading t]
20704 ["Next Same Level" outline-forward-same-level t]
20705 ["Previous Same Level" outline-backward-same-level t]
20706 "--"
20707 ["Jump" org-goto t])
20708 ("Edit Structure"
20709 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20710 "--"
20711 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20712 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20713 "--"
20714 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20715 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20716 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20717 "--"
20718 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20719 "--"
20720 ["Copy visible text" org-copy-visible t]
20721 "--"
20722 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20723 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20724 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20725 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20726 "--"
20727 ["Sort Region/Children" org-sort t]
20728 "--"
20729 ["Convert to odd levels" org-convert-to-odd-levels t]
20730 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20731 ("Editing"
20732 ["Emphasis..." org-emphasize t]
20733 ["Edit Source Example" org-edit-special t]
20734 "--"
20735 ["Footnote new/jump" org-footnote-action t]
20736 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20737 ("Archive"
20738 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20739 "--"
20740 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20741 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20742 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20744 "--"
20745 ("Hyperlinks"
20746 ["Store Link (Global)" org-store-link t]
20747 ["Find existing link to here" org-occur-link-in-agenda-files t]
20748 ["Insert Link" org-insert-link t]
20749 ["Follow Link" org-open-at-point t]
20750 "--"
20751 ["Next link" org-next-link t]
20752 ["Previous link" org-previous-link t]
20753 "--"
20754 ["Descriptive Links"
20755 org-toggle-link-display
20756 :style radio
20757 :selected org-descriptive-links
20759 ["Literal Links"
20760 org-toggle-link-display
20761 :style radio
20762 :selected (not org-descriptive-links)])
20763 "--"
20764 ("TODO Lists"
20765 ["TODO/DONE/-" org-todo t]
20766 ("Select keyword"
20767 ["Next keyword" org-shiftright (org-at-heading-p)]
20768 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20769 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20770 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20771 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20772 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20773 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20774 "--"
20775 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20776 :selected org-enforce-todo-dependencies :style toggle :active t]
20777 "Settings for tree at point"
20778 ["Do Children sequentially" org-toggle-ordered-property :style radio
20779 :selected (org-entry-get nil "ORDERED")
20780 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20781 ["Do Children parallel" org-toggle-ordered-property :style radio
20782 :selected (not (org-entry-get nil "ORDERED"))
20783 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20784 "--"
20785 ["Set Priority" org-priority t]
20786 ["Priority Up" org-shiftup t]
20787 ["Priority Down" org-shiftdown t]
20788 "--"
20789 ["Get news from all feeds" org-feed-update-all t]
20790 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20791 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20792 ("TAGS and Properties"
20793 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20794 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20795 "--"
20796 ["Set property" org-set-property (not (org-before-first-heading-p))]
20797 ["Column view of properties" org-columns t]
20798 ["Insert Column View DBlock" org-columns-insert-dblock t])
20799 ("Dates and Scheduling"
20800 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20801 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20802 ("Change Date"
20803 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20804 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20805 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20806 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20807 ["Compute Time Range" org-evaluate-time-range t]
20808 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20809 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20810 "--"
20811 ["Custom time format" org-toggle-time-stamp-overlays
20812 :style radio :selected org-display-custom-times]
20813 "--"
20814 ["Goto Calendar" org-goto-calendar t]
20815 ["Date from Calendar" org-date-from-calendar t]
20816 "--"
20817 ["Start/Restart Timer" org-timer-start t]
20818 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20819 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20820 ["Insert Timer String" org-timer t]
20821 ["Insert Timer Item" org-timer-item t])
20822 ("Logging work"
20823 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20824 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20825 ["Clock out" org-clock-out t]
20826 ["Clock cancel" org-clock-cancel t]
20827 "--"
20828 ["Mark as default task" org-clock-mark-default-task t]
20829 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20830 ["Goto running clock" org-clock-goto t]
20831 "--"
20832 ["Display times" org-clock-display t]
20833 ["Create clock table" org-clock-report t]
20834 "--"
20835 ["Record DONE time"
20836 (progn (setq org-log-done (not org-log-done))
20837 (message "Switching to %s will %s record a timestamp"
20838 (car org-done-keywords)
20839 (if org-log-done "automatically" "not")))
20840 :style toggle :selected org-log-done])
20841 "--"
20842 ["Agenda Command..." org-agenda t]
20843 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20844 ("File List for Agenda")
20845 ("Special views current file"
20846 ["TODO Tree" org-show-todo-tree t]
20847 ["Check Deadlines" org-check-deadlines t]
20848 ["Tags/Property tree" org-match-sparse-tree t])
20849 "--"
20850 ["Export/Publish..." org-export-dispatch t]
20851 ("LaTeX"
20852 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20853 :style toggle :selected org-cdlatex-mode]
20854 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20855 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20856 ["Modify math symbol" org-cdlatex-math-modify
20857 (org-inside-LaTeX-fragment-p)]
20858 ["Insert citation" org-reftex-citation t])
20859 "--"
20860 ("MobileOrg"
20861 ["Push Files and Views" org-mobile-push t]
20862 ["Get Captured and Flagged" org-mobile-pull t]
20863 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20864 "--"
20865 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20866 "--"
20867 ("Documentation"
20868 ["Show Version" org-version t]
20869 ["Info Documentation" org-info t])
20870 ("Customize"
20871 ["Browse Org Group" org-customize t]
20872 "--"
20873 ["Expand This Menu" org-create-customize-menu
20874 (fboundp 'customize-menu-create)])
20875 ["Send bug report" org-submit-bug-report t]
20876 "--"
20877 ("Refresh/Reload"
20878 ["Refresh setup current buffer" org-mode-restart t]
20879 ["Reload Org (after update)" org-reload t]
20880 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20883 (defun org-info (&optional node)
20884 "Read documentation for Org in the info system.
20885 With optional NODE, go directly to that node."
20886 (interactive)
20887 (info (format "(org)%s" (or node ""))))
20889 ;;;###autoload
20890 (defun org-submit-bug-report ()
20891 "Submit a bug report on Org via mail.
20893 Don't hesitate to report any problems or inaccurate documentation.
20895 If you don't have setup sending mail from (X)Emacs, please copy the
20896 output buffer into your mail program, as it gives us important
20897 information about your Org version and configuration."
20898 (interactive)
20899 (require 'reporter)
20900 (defvar reporter-prompt-for-summary-p)
20901 (org-load-modules-maybe)
20902 (org-require-autoloaded-modules)
20903 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20904 (reporter-submit-bug-report
20905 "emacs-orgmode@gnu.org"
20906 (org-version nil 'full)
20907 (let (list)
20908 (save-window-excursion
20909 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20910 (delete-other-windows)
20911 (erase-buffer)
20912 (insert "You are about to submit a bug report to the Org mailing list.
20914 We would like to add your full Org and Outline configuration to the
20915 bug report. This greatly simplifies the work of the maintainer and
20916 other experts on the mailing list.
20918 HOWEVER, some variables you have customized may contain private
20919 information. The names of customers, colleagues, or friends, might
20920 appear in the form of file names, tags, todo states, or search strings.
20921 If you answer yes to the prompt, you might want to check and remove
20922 such private information before sending the email.")
20923 (add-text-properties (point-min) (point-max) '(face org-warning))
20924 (when (yes-or-no-p "Include your Org configuration ")
20925 (mapatoms
20926 (lambda (v)
20927 (and (boundp v)
20928 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20929 (or (and (symbol-value v)
20930 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20931 (and
20932 (get v 'custom-type) (get v 'standard-value)
20933 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20934 (push v list)))))
20935 (kill-buffer (get-buffer "*Warn about privacy*"))
20936 list))
20937 nil nil
20938 "Remember to cover the basics, that is, what you expected to happen and
20939 what in fact did happen. You don't know how to make a good report? See
20941 https://orgmode.org/manual/Feedback.html#Feedback
20943 Your bug report will be posted to the Org mailing list.
20944 ------------------------------------------------------------------------")
20945 (save-excursion
20946 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20947 (replace-match "\\1Bug: \\3 [\\2]")))))
20950 (defun org-install-agenda-files-menu ()
20951 (let ((bl (buffer-list)))
20952 (save-excursion
20953 (while bl
20954 (set-buffer (pop bl))
20955 (when (derived-mode-p 'org-mode) (setq bl nil)))
20956 (when (derived-mode-p 'org-mode)
20957 (easy-menu-change
20958 '("Org") "File List for Agenda"
20959 (append
20960 (list
20961 ["Edit File List" (org-edit-agenda-file-list) t]
20962 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20963 ["Remove Current File from List" org-remove-file t]
20964 ["Cycle through agenda files" org-cycle-agenda-files t]
20965 ["Occur in all agenda files" org-occur-in-agenda-files t]
20966 "--")
20967 (mapcar 'org-file-menu-entry
20968 ;; Prevent initialization from failing.
20969 (ignore-errors (org-agenda-files t)))))))))
20971 ;;;; Documentation
20973 (defun org-require-autoloaded-modules ()
20974 (interactive)
20975 (mapc #'require
20976 '(org-agenda org-archive org-attach org-clock org-colview org-id
20977 org-table org-timer)))
20979 ;;;###autoload
20980 (defun org-reload (&optional uncompiled)
20981 "Reload all Org Lisp files.
20982 With prefix arg UNCOMPILED, load the uncompiled versions."
20983 (interactive "P")
20984 (require 'loadhist)
20985 (let* ((org-dir (org-find-library-dir "org"))
20986 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20987 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20988 (remove-re (format "\\`%s\\'"
20989 (regexp-opt '("org" "org-loaddefs" "org-version"))))
20990 (feats (delete-dups
20991 (mapcar 'file-name-sans-extension
20992 (mapcar 'file-name-nondirectory
20993 (delq nil
20994 (mapcar 'feature-file
20995 features))))))
20996 (lfeat (append
20997 (sort
20998 (setq feats
20999 (delq nil (mapcar
21000 (lambda (f)
21001 (if (and (string-match feature-re f)
21002 (not (string-match remove-re f)))
21003 f nil))
21004 feats)))
21005 'string-lessp)
21006 (list "org-version" "org")))
21007 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21008 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21009 load-uncore load-misses)
21010 (setq load-misses
21011 (delq 't
21012 (mapcar (lambda (f)
21013 (or (org-load-noerror-mustsuffix (concat org-dir f))
21014 (and (string= org-dir contrib-dir)
21015 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21016 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21017 (add-to-list 'load-uncore f 'append)
21020 lfeat)))
21021 (when load-uncore
21022 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21023 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21024 (if load-misses
21025 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21026 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21027 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21029 ;;;###autoload
21030 (defun org-customize ()
21031 "Call the customize function with org as argument."
21032 (interactive)
21033 (org-load-modules-maybe)
21034 (org-require-autoloaded-modules)
21035 (customize-browse 'org))
21037 (defun org-create-customize-menu ()
21038 "Create a full customization menu for Org mode, insert it into the menu."
21039 (interactive)
21040 (org-load-modules-maybe)
21041 (org-require-autoloaded-modules)
21042 (if (fboundp 'customize-menu-create)
21043 (progn
21044 (easy-menu-change
21045 '("Org") "Customize"
21046 `(["Browse Org group" org-customize t]
21047 "--"
21048 ,(customize-menu-create 'org)
21049 ["Set" Custom-set t]
21050 ["Save" Custom-save t]
21051 ["Reset to Current" Custom-reset-current t]
21052 ["Reset to Saved" Custom-reset-saved t]
21053 ["Reset to Standard Settings" Custom-reset-standard t]))
21054 (message "\"Org\"-menu now contains full customization menu"))
21055 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21057 ;;;; Miscellaneous stuff
21059 ;;; Generally useful functions
21061 (defun org-link-display-format (s)
21062 "Replace links in string S with their description.
21063 If there is no description, use the link target."
21064 (save-match-data
21065 (replace-regexp-in-string
21066 org-bracket-link-analytic-regexp
21067 (lambda (m)
21068 (if (match-end 5) (match-string 5 m)
21069 (concat (match-string 1 m) (match-string 3 m))))
21070 s nil t)))
21072 (defun org-toggle-link-display ()
21073 "Toggle the literal or descriptive display of links."
21074 (interactive)
21075 (if org-descriptive-links
21076 (progn (org-remove-from-invisibility-spec '(org-link))
21077 (org-restart-font-lock)
21078 (setq org-descriptive-links nil))
21079 (progn (add-to-invisibility-spec '(org-link))
21080 (org-restart-font-lock)
21081 (setq org-descriptive-links t))))
21083 (defun org-in-clocktable-p ()
21084 "Check if the cursor is in a clocktable."
21085 (let ((pos (point)) start)
21086 (save-excursion
21087 (end-of-line 1)
21088 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21089 (setq start (match-beginning 0))
21090 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21091 (>= (match-end 0) pos)
21092 start))))
21094 (defun org-in-verbatim-emphasis ()
21095 (save-match-data
21096 (and (org-in-regexp org-verbatim-re 2)
21097 (>= (point) (match-beginning 3))
21098 (<= (point) (match-end 4)))))
21100 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21101 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21102 (if (and marker (marker-buffer marker)
21103 (buffer-live-p (marker-buffer marker)))
21104 (progn
21105 (pop-to-buffer-same-window (marker-buffer marker))
21106 (when (or (> marker (point-max)) (< marker (point-min)))
21107 (widen))
21108 (goto-char marker)
21109 (org-show-context 'org-goto))
21110 (if bookmark
21111 (bookmark-jump bookmark)
21112 (error "Cannot find location"))))
21114 (defun org-quote-csv-field (s)
21115 "Quote field for inclusion in CSV material."
21116 (if (string-match "[\",]" s)
21117 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21120 (defun org-force-self-insert (N)
21121 "Needed to enforce self-insert under remapping."
21122 (interactive "p")
21123 (self-insert-command N))
21125 (defun org-fill-template (template alist)
21126 "Find each %key of ALIST in TEMPLATE and replace it."
21127 (let ((case-fold-search nil))
21128 (dolist (entry (sort (copy-sequence alist)
21129 (lambda (a b) (< (length (car a)) (length (car b))))))
21130 (setq template
21131 (replace-regexp-in-string
21132 (concat "%" (regexp-quote (car entry)))
21133 (or (cdr entry) "") template t t)))
21134 template))
21136 (defun org-quote-vert (s)
21137 "Replace \"|\" with \"\\vert\"."
21138 (while (string-match "|" s)
21139 (setq s (replace-match "\\vert" t t s)))
21142 (defun org-uuidgen-p (s)
21143 "Is S an ID created by UUIDGEN?"
21144 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21146 (defun org-in-src-block-p (&optional inside)
21147 "Whether point is in a code source block.
21148 When INSIDE is non-nil, don't consider we are within a src block
21149 when point is at #+BEGIN_SRC or #+END_SRC."
21150 (let ((case-fold-search t))
21151 (or (and (eq (get-char-property (point) 'src-block) t))
21152 (and (not inside)
21153 (save-match-data
21154 (save-excursion
21155 (beginning-of-line)
21156 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21158 (defun org-context ()
21159 "Return a list of contexts of the current cursor position.
21160 If several contexts apply, all are returned.
21161 Each context entry is a list with a symbol naming the context, and
21162 two positions indicating start and end of the context. Possible
21163 contexts are:
21165 :headline anywhere in a headline
21166 :headline-stars on the leading stars in a headline
21167 :todo-keyword on a TODO keyword (including DONE) in a headline
21168 :tags on the TAGS in a headline
21169 :priority on the priority cookie in a headline
21170 :item on the first line of a plain list item
21171 :item-bullet on the bullet/number of a plain list item
21172 :checkbox on the checkbox in a plain list item
21173 :table in an Org table
21174 :table-special on a special filed in a table
21175 :table-table in a table.el table
21176 :clocktable in a clocktable
21177 :src-block in a source block
21178 :link on a hyperlink
21179 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21180 :target on a <<target>>
21181 :radio-target on a <<<radio-target>>>
21182 :latex-fragment on a LaTeX fragment
21183 :latex-preview on a LaTeX fragment with overlaid preview image
21185 This function expects the position to be visible because it uses font-lock
21186 faces as a help to recognize the following contexts: :table-special, :link,
21187 and :keyword."
21188 (let* ((f (get-text-property (point) 'face))
21189 (faces (if (listp f) f (list f)))
21190 (case-fold-search t)
21191 (p (point)) clist o)
21192 ;; First the large context
21193 (cond
21194 ((org-at-heading-p t)
21195 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21196 (when (progn
21197 (beginning-of-line 1)
21198 (looking-at org-todo-line-tags-regexp))
21199 (push (org-point-in-group p 1 :headline-stars) clist)
21200 (push (org-point-in-group p 2 :todo-keyword) clist)
21201 (push (org-point-in-group p 4 :tags) clist))
21202 (goto-char p)
21203 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21204 (when (looking-at "\\[#[A-Z0-9]\\]")
21205 (push (org-point-in-group p 0 :priority) clist)))
21207 ((org-at-item-p)
21208 (push (org-point-in-group p 2 :item-bullet) clist)
21209 (push (list :item (point-at-bol)
21210 (save-excursion (org-end-of-item) (point)))
21211 clist)
21212 (and (org-at-item-checkbox-p)
21213 (push (org-point-in-group p 0 :checkbox) clist)))
21215 ((org-at-table-p)
21216 (push (list :table (org-table-begin) (org-table-end)) clist)
21217 (when (memq 'org-formula faces)
21218 (push (list :table-special
21219 (previous-single-property-change p 'face)
21220 (next-single-property-change p 'face)) clist)))
21221 ((org-at-table-p 'any)
21222 (push (list :table-table) clist)))
21223 (goto-char p)
21225 (let ((case-fold-search t))
21226 ;; New the "medium" contexts: clocktables, source blocks
21227 (cond ((org-in-clocktable-p)
21228 (push (list :clocktable
21229 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21230 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21231 (match-beginning 1))
21232 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21233 (match-end 0))) clist))
21234 ((org-in-src-block-p)
21235 (push (list :src-block
21236 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21237 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21238 (match-beginning 1))
21239 (and (search-forward "#+END_SRC" nil t)
21240 (match-beginning 0))) clist))))
21241 (goto-char p)
21243 ;; Now the small context
21244 (cond
21245 ((org-at-timestamp-p)
21246 (push (org-point-in-group p 0 :timestamp) clist))
21247 ((memq 'org-link faces)
21248 (push (list :link
21249 (previous-single-property-change p 'face)
21250 (next-single-property-change p 'face)) clist))
21251 ((memq 'org-special-keyword faces)
21252 (push (list :keyword
21253 (previous-single-property-change p 'face)
21254 (next-single-property-change p 'face)) clist))
21255 ((org-at-target-p)
21256 (push (org-point-in-group p 0 :target) clist)
21257 (goto-char (1- (match-beginning 0)))
21258 (when (looking-at org-radio-target-regexp)
21259 (push (org-point-in-group p 0 :radio-target) clist))
21260 (goto-char p))
21261 ((setq o (cl-some
21262 (lambda (o)
21263 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21265 (overlays-at (point))))
21266 (push (list :latex-fragment
21267 (overlay-start o) (overlay-end o)) clist)
21268 (push (list :latex-preview
21269 (overlay-start o) (overlay-end o)) clist))
21270 ((org-inside-LaTeX-fragment-p)
21271 ;; FIXME: positions wrong.
21272 (push (list :latex-fragment (point) (point)) clist)))
21274 (setq clist (nreverse (delq nil clist)))
21275 clist))
21277 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21278 "Non-nil when point is between matches of START-RE and END-RE.
21280 Also return a non-nil value when point is on one of the matches.
21282 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21283 buffer positions. Default values are the positions of headlines
21284 surrounding the point.
21286 The functions returns a cons cell whose car (resp. cdr) is the
21287 position before START-RE (resp. after END-RE)."
21288 (save-match-data
21289 (let ((pos (point))
21290 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21291 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21292 beg end)
21293 (save-excursion
21294 ;; Point is on a block when on START-RE or if START-RE can be
21295 ;; found before it...
21296 (and (or (org-in-regexp start-re)
21297 (re-search-backward start-re limit-up t))
21298 (setq beg (match-beginning 0))
21299 ;; ... and END-RE after it...
21300 (goto-char (match-end 0))
21301 (re-search-forward end-re limit-down t)
21302 (> (setq end (match-end 0)) pos)
21303 ;; ... without another START-RE in-between.
21304 (goto-char (match-beginning 0))
21305 (not (re-search-backward start-re (1+ beg) t))
21306 ;; Return value.
21307 (cons beg end))))))
21309 (defun org-in-block-p (names)
21310 "Non-nil when point belongs to a block whose name belongs to NAMES.
21312 NAMES is a list of strings containing names of blocks.
21314 Return first block name matched, or nil. Beware that in case of
21315 nested blocks, the returned name may not belong to the closest
21316 block from point."
21317 (save-match-data
21318 (catch 'exit
21319 (let ((case-fold-search t)
21320 (lim-up (save-excursion (outline-previous-heading)))
21321 (lim-down (save-excursion (outline-next-heading))))
21322 (dolist (name names)
21323 (let ((n (regexp-quote name)))
21324 (when (org-between-regexps-p
21325 (concat "^[ \t]*#\\+begin_" n)
21326 (concat "^[ \t]*#\\+end_" n)
21327 lim-up lim-down)
21328 (throw 'exit n)))))
21329 nil)))
21331 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21332 "Call `multi-occur' with buffers for all agenda files."
21333 (interactive "sOrg-files matching: ")
21334 (let* ((files (org-agenda-files))
21335 (tnames (mapcar #'file-truename files))
21336 (extra org-agenda-text-search-extra-files))
21337 (when (eq (car extra) 'agenda-archives)
21338 (setq extra (cdr extra))
21339 (setq files (org-add-archive-files files)))
21340 (dolist (f extra)
21341 (unless (member (file-truename f) tnames)
21342 (unless (member f files) (setq files (append files (list f))))
21343 (setq tnames (append tnames (list (file-truename f))))))
21344 (multi-occur
21345 (mapcar (lambda (x)
21346 (with-current-buffer
21347 ;; FIXME: Why not just (find-file-noselect x)?
21348 ;; Is it to avoid the "revert buffer" prompt?
21349 (or (get-file-buffer x) (find-file-noselect x))
21350 (widen)
21351 (current-buffer)))
21352 files)
21353 regexp)))
21355 (add-hook 'occur-mode-find-occurrence-hook
21356 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21358 (defun org-occur-link-in-agenda-files ()
21359 "Create a link and search for it in the agendas.
21360 The link is not stored in `org-stored-links', it is just created
21361 for the search purpose."
21362 (interactive)
21363 (let ((link (condition-case nil
21364 (org-store-link nil)
21365 (error "Unable to create a link to here"))))
21366 (org-occur-in-agenda-files (regexp-quote link))))
21368 (defun org-back-over-empty-lines ()
21369 "Move backwards over whitespace, to the beginning of the first empty line.
21370 Returns the number of empty lines passed."
21371 (let ((pos (point)))
21372 (if (cdr (assq 'heading org-blank-before-new-entry))
21373 (skip-chars-backward " \t\n\r")
21374 (unless (eobp)
21375 (forward-line -1)))
21376 (beginning-of-line 2)
21377 (goto-char (min (point) pos))
21378 (count-lines (point) pos)))
21380 (defun org-switch-to-buffer-other-window (&rest args)
21381 "Switch to buffer in a second window on the current frame.
21382 In particular, do not allow pop-up frames.
21383 Returns the newly created buffer."
21384 (org-no-popups
21385 (apply 'switch-to-buffer-other-window args)))
21387 (defun org-replace-escapes (string table)
21388 "Replace %-escapes in STRING with values in TABLE.
21389 TABLE is an association list with keys like \"%a\" and string values.
21390 The sequences in STRING may contain normal field width and padding information,
21391 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21392 so values can contain further %-escapes if they are define later in TABLE."
21393 (let ((tbl (copy-alist table))
21394 (case-fold-search nil)
21395 (pchg 0)
21396 re rpl)
21397 (dolist (e tbl)
21398 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21399 (when (and (cdr e) (string-match re (cdr e)))
21400 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21401 (safe "SREF"))
21402 (add-text-properties 0 3 (list 'sref sref) safe)
21403 (setcdr e (replace-match safe t t (cdr e)))))
21404 (while (string-match re string)
21405 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21406 (cdr e)))
21407 (setq string (replace-match rpl t t string))))
21408 (while (setq pchg (next-property-change pchg string))
21409 (let ((sref (get-text-property pchg 'sref string)))
21410 (when (and sref (string-match "SREF" string pchg))
21411 (setq string (replace-match sref t t string)))))
21412 string))
21414 ;;; TODO: Only called once, from ox-odt which should probably use
21415 ;;; org-export-inline-image-p or something.
21416 (defun org-file-image-p (file)
21417 "Return non-nil if FILE is an image."
21418 (save-match-data
21419 (string-match (image-file-name-regexp) file)))
21421 (defun org-get-cursor-date (&optional with-time)
21422 "Return the date at cursor in as a time.
21423 This works in the calendar and in the agenda, anywhere else it just
21424 returns the current time.
21425 If WITH-TIME is non-nil, returns the time of the event at point (in
21426 the agenda) or the current time of the day."
21427 (let (date day defd tp hod mod)
21428 (when with-time
21429 (setq tp (get-text-property (point) 'time))
21430 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21431 (setq hod (string-to-number (match-string 1 tp))
21432 mod (string-to-number (match-string 2 tp))))
21433 (or tp (let ((now (decode-time)))
21434 (setq hod (nth 2 now)
21435 mod (nth 1 now)))))
21436 (cond
21437 ((eq major-mode 'calendar-mode)
21438 (setq date (calendar-cursor-to-date)
21439 defd (encode-time 0 (or mod 0) (or hod 0)
21440 (nth 1 date) (nth 0 date) (nth 2 date))))
21441 ((eq major-mode 'org-agenda-mode)
21442 (setq day (get-text-property (point) 'day))
21443 (when day
21444 (setq date (calendar-gregorian-from-absolute day)
21445 defd (encode-time 0 (or mod 0) (or hod 0)
21446 (nth 1 date) (nth 0 date) (nth 2 date))))))
21447 (or defd (current-time))))
21449 (defun org-mark-subtree (&optional up)
21450 "Mark the current subtree.
21451 This puts point at the start of the current subtree, and mark at
21452 the end. If a numeric prefix UP is given, move up into the
21453 hierarchy of headlines by UP levels before marking the subtree."
21454 (interactive "P")
21455 (org-with-limited-levels
21456 (cond ((org-at-heading-p) (beginning-of-line))
21457 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21458 (t (outline-previous-visible-heading 1))))
21459 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21460 (if (called-interactively-p 'any)
21461 (call-interactively 'org-mark-element)
21462 (org-mark-element)))
21464 (defun org-file-newer-than-p (file time)
21465 "Non-nil if FILE is newer than TIME.
21466 FILE is a filename, as a string, TIME is a list of integers, as
21467 returned by, e.g., `current-time'."
21468 (and (file-exists-p file)
21469 ;; Only compare times up to whole seconds as some file-systems
21470 ;; (e.g. HFS+) do not retain any finer granularity. As
21471 ;; a consequence, make sure we return non-nil when the two
21472 ;; times are equal.
21473 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21474 (cl-subseq time 0 2)))))
21476 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21477 "Compile a SOURCE file using PROCESS.
21479 PROCESS is either a function or a list of shell commands, as
21480 strings. EXT is a file extension, without the leading dot, as
21481 a string. It is used to check if the process actually succeeded.
21483 PROCESS must create a file with the same base name and directory
21484 as SOURCE, but ending with EXT. The function then returns its
21485 filename. Otherwise, it raises an error. The error message can
21486 then be refined by providing string ERR-MSG, which is appended to
21487 the standard message.
21489 If PROCESS is a function, it is called with a single argument:
21490 the SOURCE file.
21492 If it is a list of commands, each of them is called using
21493 `shell-command'. By default, in each command, %b, %f, %F, %o and
21494 %O are replaced with, respectively, SOURCE base name, name, full
21495 name, directory and absolute output file name. It is possible,
21496 however, to use more place-holders by specifying them in optional
21497 argument SPEC, as an alist following the pattern
21499 (CHARACTER . REPLACEMENT-STRING).
21501 When PROCESS is a list of commands, optional argument LOG-BUF can
21502 be set to a buffer or a buffer name. `shell-command' then uses
21503 it for output."
21504 (let* ((base-name (file-name-base source))
21505 (full-name (file-truename source))
21506 (out-dir (or (file-name-directory source) "./"))
21507 (output (expand-file-name (concat base-name "." ext) out-dir))
21508 (time (current-time))
21509 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21510 (save-window-excursion
21511 (pcase process
21512 ((pred functionp) (funcall process (shell-quote-argument source)))
21513 ((pred consp)
21514 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21515 (spec (append spec
21516 `((?b . ,(shell-quote-argument base-name))
21517 (?f . ,(shell-quote-argument source))
21518 (?F . ,(shell-quote-argument full-name))
21519 (?o . ,(shell-quote-argument out-dir))
21520 (?O . ,(shell-quote-argument output))))))
21521 (dolist (command process)
21522 (shell-command (format-spec command spec) log-buf))
21523 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21524 (_ (error "No valid command to process %S%s" source err-msg))))
21525 ;; Check for process failure. Output file is expected to be
21526 ;; located in the same directory as SOURCE.
21527 (unless (org-file-newer-than-p output time)
21528 (error (format "File %S wasn't produced%s" output err-msg)))
21529 output))
21531 ;;; Indentation
21533 (defvar org-element-greater-elements)
21534 (defun org--get-expected-indentation (element contentsp)
21535 "Expected indentation column for current line, according to ELEMENT.
21536 ELEMENT is an element containing point. CONTENTSP is non-nil
21537 when indentation is to be computed according to contents of
21538 ELEMENT."
21539 (let ((type (org-element-type element))
21540 (start (org-element-property :begin element))
21541 (post-affiliated (org-element-property :post-affiliated element)))
21542 (org-with-wide-buffer
21543 (cond
21544 (contentsp
21545 (cl-case type
21546 ((diary-sexp footnote-definition) 0)
21547 ((headline inlinetask nil)
21548 (if (not org-adapt-indentation) 0
21549 (let ((level (org-current-level)))
21550 (if level (1+ level) 0))))
21551 ((item plain-list) (org-list-item-body-column post-affiliated))
21553 (goto-char start)
21554 (org-get-indentation))))
21555 ((memq type '(headline inlinetask nil))
21556 (if (org-match-line "[ \t]*$")
21557 (org--get-expected-indentation element t)
21559 ((memq type '(diary-sexp footnote-definition)) 0)
21560 ;; First paragraph of a footnote definition or an item.
21561 ;; Indent like parent.
21562 ((< (line-beginning-position) start)
21563 (org--get-expected-indentation
21564 (org-element-property :parent element) t))
21565 ;; At first line: indent according to previous sibling, if any,
21566 ;; ignoring footnote definitions and inline tasks, or parent's
21567 ;; contents.
21568 ((= (line-beginning-position) start)
21569 (catch 'exit
21570 (while t
21571 (if (= (point-min) start) (throw 'exit 0)
21572 (goto-char (1- start))
21573 (let* ((previous (org-element-at-point))
21574 (parent previous))
21575 (while (and parent (<= (org-element-property :end parent) start))
21576 (setq previous parent
21577 parent (org-element-property :parent parent)))
21578 (cond
21579 ((not previous) (throw 'exit 0))
21580 ((> (org-element-property :end previous) start)
21581 (throw 'exit (org--get-expected-indentation previous t)))
21582 ((memq (org-element-type previous)
21583 '(footnote-definition inlinetask))
21584 (setq start (org-element-property :begin previous)))
21585 (t (goto-char (org-element-property :begin previous))
21586 (throw 'exit
21587 (if (bolp) (org-get-indentation)
21588 ;; At first paragraph in an item or
21589 ;; a footnote definition.
21590 (org--get-expected-indentation
21591 (org-element-property :parent previous) t))))))))))
21592 ;; Otherwise, move to the first non-blank line above.
21594 (beginning-of-line)
21595 (let ((pos (point)))
21596 (skip-chars-backward " \r\t\n")
21597 (cond
21598 ;; Two blank lines end a footnote definition or a plain
21599 ;; list. When we indent an empty line after them, the
21600 ;; containing list or footnote definition is over, so it
21601 ;; qualifies as a previous sibling. Therefore, we indent
21602 ;; like its first line.
21603 ((and (memq type '(footnote-definition plain-list))
21604 (> (count-lines (point) pos) 2))
21605 (goto-char start)
21606 (org-get-indentation))
21607 ;; Line above is the first one of a paragraph at the
21608 ;; beginning of an item or a footnote definition. Indent
21609 ;; like parent.
21610 ((< (line-beginning-position) start)
21611 (org--get-expected-indentation
21612 (org-element-property :parent element) t))
21613 ;; Line above is the beginning of an element, i.e., point
21614 ;; was originally on the blank lines between element's start
21615 ;; and contents.
21616 ((= (line-beginning-position) post-affiliated)
21617 (org--get-expected-indentation element t))
21618 ;; POS is after contents in a greater element. Indent like
21619 ;; the beginning of the element.
21620 ((and (memq type org-element-greater-elements)
21621 (let ((cend (org-element-property :contents-end element)))
21622 (and cend (<= cend pos))))
21623 ;; As a special case, if point is at the end of a footnote
21624 ;; definition or an item, indent like the very last element
21625 ;; within. If that last element is an item, indent like
21626 ;; its contents.
21627 (if (memq type '(footnote-definition item plain-list))
21628 (let ((last (org-element-at-point)))
21629 (goto-char pos)
21630 (org--get-expected-indentation
21631 last (eq (org-element-type last) 'item)))
21632 (goto-char start)
21633 (org-get-indentation)))
21634 ;; In any other case, indent like the current line.
21635 (t (org-get-indentation)))))))))
21637 (defun org--align-node-property ()
21638 "Align node property at point.
21639 Alignment is done according to `org-property-format', which see."
21640 (when (save-excursion
21641 (beginning-of-line)
21642 (looking-at org-property-re))
21643 (replace-match
21644 (concat (match-string 4)
21645 (org-trim
21646 (format org-property-format (match-string 1) (match-string 3))))
21647 t t)))
21649 (defun org-indent-line ()
21650 "Indent line depending on context.
21652 Indentation is done according to the following rules:
21654 - Footnote definitions, diary sexps, headlines and inline tasks
21655 have to start at column 0.
21657 - On the very first line of an element, consider, in order, the
21658 next rules until one matches:
21660 1. If there's a sibling element before, ignoring footnote
21661 definitions and inline tasks, indent like its first line.
21663 2. If element has a parent, indent like its contents. More
21664 precisely, if parent is an item, indent after the
21665 description part, if any, or the bullet (see
21666 `org-list-description-max-indent'). Else, indent like
21667 parent's first line.
21669 3. Otherwise, indent relatively to current level, if
21670 `org-adapt-indentation' is non-nil, or to left margin.
21672 - On a blank line at the end of an element, indent according to
21673 the type of the element. More precisely
21675 1. If element is a plain list, an item, or a footnote
21676 definition, indent like the very last element within.
21678 2. If element is a paragraph, indent like its last non blank
21679 line.
21681 3. Otherwise, indent like its very first line.
21683 - In the code part of a source block, use language major mode
21684 to indent current line if `org-src-tab-acts-natively' is
21685 non-nil. If it is nil, do nothing.
21687 - Otherwise, indent like the first non-blank line above.
21689 The function doesn't indent an item as it could break the whole
21690 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21691 `\\[org-shiftmetaright]'.
21693 Also align node properties according to `org-property-format'."
21694 (interactive)
21695 (cond
21696 ((org-at-heading-p) 'noindent)
21698 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21699 (type (org-element-type element)))
21700 (cond ((and (memq type '(plain-list item))
21701 (= (line-beginning-position)
21702 (org-element-property :post-affiliated element)))
21703 'noindent)
21704 ((and (eq type 'latex-environment)
21705 (>= (point) (org-element-property :post-affiliated element))
21706 (< (point) (org-with-wide-buffer
21707 (goto-char (org-element-property :end element))
21708 (skip-chars-backward " \r\t\n")
21709 (line-beginning-position 2))))
21710 'noindent)
21711 ((and (eq type 'src-block)
21712 org-src-tab-acts-natively
21713 (> (line-beginning-position)
21714 (org-element-property :post-affiliated element))
21715 (< (line-beginning-position)
21716 (org-with-wide-buffer
21717 (goto-char (org-element-property :end element))
21718 (skip-chars-backward " \r\t\n")
21719 (line-beginning-position))))
21720 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21722 (let ((column (org--get-expected-indentation element nil)))
21723 ;; Preserve current column.
21724 (if (<= (current-column) (current-indentation))
21725 (indent-line-to column)
21726 (save-excursion (indent-line-to column))))
21727 ;; Align node property. Also preserve current column.
21728 (when (eq type 'node-property)
21729 (let ((column (current-column)))
21730 (org--align-node-property)
21731 (org-move-to-column column)))))))))
21733 (defun org-indent-region (start end)
21734 "Indent each non-blank line in the region.
21735 Called from a program, START and END specify the region to
21736 indent. The function will not indent contents of example blocks,
21737 verse blocks and export blocks as leading white spaces are
21738 assumed to be significant there."
21739 (interactive "r")
21740 (save-excursion
21741 (goto-char start)
21742 (skip-chars-forward " \r\t\n")
21743 (unless (eobp) (beginning-of-line))
21744 (let ((indent-to
21745 (lambda (ind pos)
21746 ;; Set IND as indentation for all lines between point and
21747 ;; POS. Blank lines are ignored. Leave point after POS
21748 ;; once done.
21749 (let ((limit (copy-marker pos)))
21750 (while (< (point) limit)
21751 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21752 (forward-line))
21753 (set-marker limit nil))))
21754 (end (copy-marker end)))
21755 (while (< (point) end)
21756 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21757 (let* ((element (org-element-at-point))
21758 (type (org-element-type element))
21759 (element-end (copy-marker (org-element-property :end element)))
21760 (ind (org--get-expected-indentation element nil)))
21761 (cond
21762 ;; Element indented as a single block. Example blocks
21763 ;; preserving indentation are a special case since the
21764 ;; "contents" must not be indented whereas the block
21765 ;; boundaries can.
21766 ((or (memq type '(export-block latex-environment))
21767 (and (eq type 'example-block)
21768 (not
21769 (or org-src-preserve-indentation
21770 (org-element-property :preserve-indent element)))))
21771 (let ((offset (- ind (org-get-indentation))))
21772 (unless (zerop offset)
21773 (indent-rigidly (org-element-property :begin element)
21774 (org-element-property :end element)
21775 offset)))
21776 (goto-char element-end))
21777 ;; Elements indented line wise. Be sure to exclude
21778 ;; example blocks (preserving indentation) and source
21779 ;; blocks from this category as they are treated
21780 ;; specially later.
21781 ((or (memq type '(paragraph table table-row))
21782 (not (or (org-element-property :contents-begin element)
21783 (memq type '(example-block src-block)))))
21784 (when (eq type 'node-property)
21785 (org--align-node-property)
21786 (beginning-of-line))
21787 (funcall indent-to ind (min element-end end)))
21788 ;; Elements consisting of three parts: before the
21789 ;; contents, the contents, and after the contents. The
21790 ;; contents are treated specially, according to the
21791 ;; element type, or not indented at all. Other parts are
21792 ;; indented as a single block.
21794 (let* ((post (copy-marker
21795 (org-element-property :post-affiliated element)))
21796 (cbeg
21797 (copy-marker
21798 (cond
21799 ((not (org-element-property :contents-begin element))
21800 ;; Fake contents for source blocks.
21801 (org-with-wide-buffer
21802 (goto-char post)
21803 (line-beginning-position 2)))
21804 ((memq type '(footnote-definition item plain-list))
21805 ;; Contents in these elements could start on
21806 ;; the same line as the beginning of the
21807 ;; element. Make sure we start indenting
21808 ;; from the second line.
21809 (org-with-wide-buffer
21810 (goto-char post)
21811 (end-of-line)
21812 (skip-chars-forward " \r\t\n")
21813 (if (eobp) (point) (line-beginning-position))))
21814 (t (org-element-property :contents-begin element)))))
21815 (cend (copy-marker
21816 (or (org-element-property :contents-end element)
21817 ;; Fake contents for source blocks.
21818 (org-with-wide-buffer
21819 (goto-char element-end)
21820 (skip-chars-backward " \r\t\n")
21821 (line-beginning-position)))
21822 t)))
21823 ;; Do not change items indentation individually as it
21824 ;; might break the list as a whole. On the other
21825 ;; hand, when at a plain list, indent it as a whole.
21826 (cond ((eq type 'plain-list)
21827 (let ((offset (- ind (org-get-indentation))))
21828 (unless (zerop offset)
21829 (indent-rigidly (org-element-property :begin element)
21830 (org-element-property :end element)
21831 offset))
21832 (goto-char cbeg)))
21833 ((eq type 'item) (goto-char cbeg))
21834 (t (funcall indent-to ind (min cbeg end))))
21835 (when (< (point) end)
21836 (cl-case type
21837 ((example-block verse-block))
21838 (src-block
21839 ;; In a source block, indent source code
21840 ;; according to language major mode, but only if
21841 ;; `org-src-tab-acts-natively' is non-nil.
21842 (when (and (< (point) end) org-src-tab-acts-natively)
21843 (ignore-errors
21844 (org-babel-do-in-edit-buffer
21845 (indent-region (point-min) (point-max))))))
21846 (t (org-indent-region (point) (min cend end))))
21847 (goto-char (min cend end))
21848 (when (< (point) end)
21849 (funcall indent-to ind (min element-end end))))
21850 (set-marker post nil)
21851 (set-marker cbeg nil)
21852 (set-marker cend nil))))
21853 (set-marker element-end nil))))
21854 (set-marker end nil))))
21856 (defun org-indent-drawer ()
21857 "Indent the drawer at point."
21858 (interactive)
21859 (unless (save-excursion
21860 (beginning-of-line)
21861 (looking-at-p org-drawer-regexp))
21862 (user-error "Not at a drawer"))
21863 (let ((element (org-element-at-point)))
21864 (unless (memq (org-element-type element) '(drawer property-drawer))
21865 (user-error "Not at a drawer"))
21866 (org-with-wide-buffer
21867 (org-indent-region (org-element-property :begin element)
21868 (org-element-property :end element))))
21869 (message "Drawer at point indented"))
21871 (defun org-indent-block ()
21872 "Indent the block at point."
21873 (interactive)
21874 (unless (save-excursion
21875 (beginning-of-line)
21876 (let ((case-fold-search t))
21877 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21878 (user-error "Not at a block"))
21879 (let ((element (org-element-at-point)))
21880 (unless (memq (org-element-type element)
21881 '(comment-block center-block dynamic-block example-block
21882 export-block quote-block special-block
21883 src-block verse-block))
21884 (user-error "Not at a block"))
21885 (org-with-wide-buffer
21886 (org-indent-region (org-element-property :begin element)
21887 (org-element-property :end element))))
21888 (message "Block at point indented"))
21891 ;;; Filling
21893 ;; We use our own fill-paragraph and auto-fill functions.
21895 ;; `org-fill-paragraph' relies on adaptive filling and context
21896 ;; checking. Appropriate `fill-prefix' is computed with
21897 ;; `org-adaptive-fill-function'.
21899 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21900 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21901 ;; `org-adaptive-fill-function' value. Internally,
21902 ;; `org-comment-line-break-function' breaks the line.
21904 ;; `org-setup-filling' installs filling and auto-filling related
21905 ;; variables during `org-mode' initialization.
21907 (defun org-setup-filling ()
21908 (require 'org-element)
21909 ;; Prevent auto-fill from inserting unwanted new items.
21910 (when (boundp 'fill-nobreak-predicate)
21911 (setq-local
21912 fill-nobreak-predicate
21913 (org-uniquify
21914 (append fill-nobreak-predicate
21915 '(org-fill-line-break-nobreak-p
21916 org-fill-n-macro-as-item-nobreak-p
21917 org-fill-paragraph-with-timestamp-nobreak-p)))))
21918 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21919 (setq-local paragraph-start paragraph-ending)
21920 (setq-local paragraph-separate paragraph-ending))
21921 (setq-local fill-paragraph-function 'org-fill-paragraph)
21922 (setq-local auto-fill-inhibit-regexp nil)
21923 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21924 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21925 (setq-local comment-line-break-function 'org-comment-line-break-function))
21927 (defun org-fill-line-break-nobreak-p ()
21928 "Non-nil when a new line at point would create an Org line break."
21929 (save-excursion
21930 (skip-chars-backward "[ \t]")
21931 (skip-chars-backward "\\\\")
21932 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21934 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21935 "Non-nil when a new line at point would split a timestamp."
21936 (and (org-at-timestamp-p 'lax)
21937 (not (looking-at org-ts-regexp-both))))
21939 (defun org-fill-n-macro-as-item-nobreak-p ()
21940 "Non-nil when a new line at point would create a new list."
21941 ;; During export, a "n" macro followed by a dot or a closing
21942 ;; parenthesis can end up being parsed as a new list item.
21943 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21945 (defvar orgtbl-line-start-regexp) ; From org-table.el
21946 (defun org-adaptive-fill-function ()
21947 "Compute a fill prefix for the current line.
21948 Return fill prefix, as a string, or nil if current line isn't
21949 meant to be filled. For convenience, if `adaptive-fill-regexp'
21950 matches in paragraphs or comments, use it."
21951 (org-with-wide-buffer
21952 (unless (org-at-heading-p)
21953 (let* ((p (line-beginning-position))
21954 (element (save-excursion
21955 (beginning-of-line)
21956 (org-element-at-point)))
21957 (type (org-element-type element))
21958 (post-affiliated (org-element-property :post-affiliated element)))
21959 (unless (< p post-affiliated)
21960 (cl-case type
21961 (comment
21962 (save-excursion
21963 (beginning-of-line)
21964 (looking-at "[ \t]*")
21965 (concat (match-string 0) "# ")))
21966 (footnote-definition "")
21967 ((item plain-list)
21968 (make-string (org-list-item-body-column post-affiliated) ?\s))
21969 (paragraph
21970 ;; Fill prefix is usually the same as the current line,
21971 ;; unless the paragraph is at the beginning of an item.
21972 (let ((parent (org-element-property :parent element)))
21973 (save-excursion
21974 (beginning-of-line)
21975 (cond ((eq (org-element-type parent) 'item)
21976 (make-string (org-list-item-body-column
21977 (org-element-property :begin parent))
21978 ?\s))
21979 ((and adaptive-fill-regexp
21980 ;; Locally disable
21981 ;; `adaptive-fill-function' to let
21982 ;; `fill-context-prefix' handle
21983 ;; `adaptive-fill-regexp' variable.
21984 (let (adaptive-fill-function)
21985 (fill-context-prefix
21986 post-affiliated
21987 (org-element-property :end element)))))
21988 ((looking-at "[ \t]+") (match-string 0))
21989 (t "")))))
21990 (comment-block
21991 ;; Only fill contents if P is within block boundaries.
21992 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21993 (forward-line)
21994 (point)))
21995 (cend (save-excursion
21996 (goto-char (org-element-property :end element))
21997 (skip-chars-backward " \r\t\n")
21998 (line-beginning-position))))
21999 (when (and (>= p cbeg) (< p cend))
22000 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22001 (match-string 0)
22002 ""))))))))))
22004 (defun org-fill-element (&optional justify)
22005 "Fill element at point, when applicable.
22007 This function only applies to comment blocks, comments, example
22008 blocks and paragraphs. Also, as a special case, re-align table
22009 when point is at one.
22011 If JUSTIFY is non-nil (interactively, with prefix argument),
22012 justify as well. If `sentence-end-double-space' is non-nil, then
22013 period followed by one space does not end a sentence, so don't
22014 break a line there. The variable `fill-column' controls the
22015 width for filling.
22017 For convenience, when point is at a plain list, an item or
22018 a footnote definition, try to fill the first paragraph within."
22019 (with-syntax-table org-mode-transpose-word-syntax-table
22020 ;; Move to end of line in order to get the first paragraph within
22021 ;; a plain list or a footnote definition.
22022 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22023 ;; First check if point is in a blank line at the beginning of
22024 ;; the buffer. In that case, ignore filling.
22025 (cl-case (org-element-type element)
22026 ;; Use major mode filling function is src blocks.
22027 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22028 ;; Align Org tables, leave table.el tables as-is.
22029 (table-row (org-table-align) t)
22030 (table
22031 (when (eq (org-element-property :type element) 'org)
22032 (save-excursion
22033 (goto-char (org-element-property :post-affiliated element))
22034 (org-table-align)))
22036 (paragraph
22037 ;; Paragraphs may contain `line-break' type objects.
22038 (let ((beg (max (point-min)
22039 (org-element-property :contents-begin element)))
22040 (end (min (point-max)
22041 (org-element-property :contents-end element))))
22042 ;; Do nothing if point is at an affiliated keyword.
22043 (if (< (line-end-position) beg) t
22044 ;; Fill paragraph, taking line breaks into account.
22045 (save-excursion
22046 (goto-char beg)
22047 (let ((cuts (list beg)))
22048 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22049 (when (eq 'line-break
22050 (org-element-type
22051 (save-excursion (backward-char)
22052 (org-element-context))))
22053 (push (point) cuts)))
22054 (dolist (c (delq end cuts))
22055 (fill-region-as-paragraph c end justify)
22056 (setq end c))))
22057 t)))
22058 ;; Contents of `comment-block' type elements should be
22059 ;; filled as plain text, but only if point is within block
22060 ;; markers.
22061 (comment-block
22062 (let* ((case-fold-search t)
22063 (beg (save-excursion
22064 (goto-char (org-element-property :begin element))
22065 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22066 (forward-line)
22067 (point)))
22068 (end (save-excursion
22069 (goto-char (org-element-property :end element))
22070 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22071 (line-beginning-position))))
22072 (if (or (< (point) beg) (> (point) end)) t
22073 (fill-region-as-paragraph
22074 (save-excursion (end-of-line)
22075 (re-search-backward "^[ \t]*$" beg 'move)
22076 (line-beginning-position))
22077 (save-excursion (beginning-of-line)
22078 (re-search-forward "^[ \t]*$" end 'move)
22079 (line-beginning-position))
22080 justify))))
22081 ;; Fill comments.
22082 (comment
22083 (let ((begin (org-element-property :post-affiliated element))
22084 (end (org-element-property :end element)))
22085 (when (and (>= (point) begin) (<= (point) end))
22086 (let ((begin (save-excursion
22087 (end-of-line)
22088 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22089 (progn (forward-line) (point))
22090 begin)))
22091 (end (save-excursion
22092 (end-of-line)
22093 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22094 (1- (line-beginning-position))
22095 (skip-chars-backward " \r\t\n")
22096 (line-end-position)))))
22097 ;; Do not fill comments when at a blank line.
22098 (when (> end begin)
22099 (let ((fill-prefix
22100 (save-excursion
22101 (beginning-of-line)
22102 (looking-at "[ \t]*#")
22103 (let ((comment-prefix (match-string 0)))
22104 (goto-char (match-end 0))
22105 (if (looking-at adaptive-fill-regexp)
22106 (concat comment-prefix (match-string 0))
22107 (concat comment-prefix " "))))))
22108 (save-excursion
22109 (fill-region-as-paragraph begin end justify))))))
22111 ;; Ignore every other element.
22112 (otherwise t)))))
22114 (defun org-fill-paragraph (&optional justify region)
22115 "Fill element at point, when applicable.
22117 This function only applies to comment blocks, comments, example
22118 blocks and paragraphs. Also, as a special case, re-align table
22119 when point is at one.
22121 For convenience, when point is at a plain list, an item or
22122 a footnote definition, try to fill the first paragraph within.
22124 If JUSTIFY is non-nil (interactively, with prefix argument),
22125 justify as well. If `sentence-end-double-space' is non-nil, then
22126 period followed by one space does not end a sentence, so don't
22127 break a line there. The variable `fill-column' controls the
22128 width for filling.
22130 The REGION argument is non-nil if called interactively; in that
22131 case, if Transient Mark mode is enabled and the mark is active,
22132 fill each of the elements in the active region, instead of just
22133 filling the current element."
22134 (interactive (progn
22135 (barf-if-buffer-read-only)
22136 (list (if current-prefix-arg 'full) t)))
22137 (cond
22138 ((and region transient-mark-mode mark-active
22139 (not (eq (region-beginning) (region-end))))
22140 (let ((origin (point-marker))
22141 (start (region-beginning)))
22142 (unwind-protect
22143 (progn
22144 (goto-char (region-end))
22145 (while (> (point) start)
22146 (org-backward-paragraph)
22147 (org-fill-element justify)))
22148 (goto-char origin)
22149 (set-marker origin nil))))
22150 (t (org-fill-element justify))))
22152 (defun org-auto-fill-function ()
22153 "Auto-fill function."
22154 ;; Check if auto-filling is meaningful.
22155 (let ((fc (current-fill-column)))
22156 (when (and fc (> (current-column) fc))
22157 (let* ((fill-prefix (org-adaptive-fill-function))
22158 ;; Enforce empty fill prefix, if required. Otherwise, it
22159 ;; will be computed again.
22160 (adaptive-fill-mode (not (equal fill-prefix ""))))
22161 (when fill-prefix (do-auto-fill))))))
22163 (defun org-comment-line-break-function (&optional soft)
22164 "Break line at point and indent, continuing comment if within one.
22165 The inserted newline is marked hard if variable
22166 `use-hard-newlines' is true, unless optional argument SOFT is
22167 non-nil."
22168 (if soft (insert-and-inherit ?\n) (newline 1))
22169 (save-excursion (forward-char -1) (delete-horizontal-space))
22170 (delete-horizontal-space)
22171 (indent-to-left-margin)
22172 (insert-before-markers-and-inherit fill-prefix))
22175 ;;; Fixed Width Areas
22177 (defun org-toggle-fixed-width ()
22178 "Toggle fixed-width markup.
22180 Add or remove fixed-width markup on current line, whenever it
22181 makes sense. Return an error otherwise.
22183 If a region is active and if it contains only fixed-width areas
22184 or blank lines, remove all fixed-width markup in it. If the
22185 region contains anything else, convert all non-fixed-width lines
22186 to fixed-width ones.
22188 Blank lines at the end of the region are ignored unless the
22189 region only contains such lines."
22190 (interactive)
22191 (if (not (org-region-active-p))
22192 ;; No region:
22194 ;; Remove fixed width marker only in a fixed-with element.
22196 ;; Add fixed width maker in paragraphs, in blank lines after
22197 ;; elements or at the beginning of a headline or an inlinetask,
22198 ;; and before any one-line elements (e.g., a clock).
22199 (progn
22200 (beginning-of-line)
22201 (let* ((element (org-element-at-point))
22202 (type (org-element-type element)))
22203 (cond
22204 ((and (eq type 'fixed-width)
22205 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22206 (replace-match
22207 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22208 ((and (memq type '(babel-call clock comment diary-sexp headline
22209 horizontal-rule keyword paragraph
22210 planning))
22211 (<= (org-element-property :post-affiliated element) (point)))
22212 (skip-chars-forward " \t")
22213 (insert ": "))
22214 ((and (looking-at-p "[ \t]*$")
22215 (or (eq type 'inlinetask)
22216 (save-excursion
22217 (skip-chars-forward " \r\t\n")
22218 (<= (org-element-property :end element) (point)))))
22219 (delete-region (point) (line-end-position))
22220 (org-indent-line)
22221 (insert ": "))
22222 (t (user-error "Cannot insert a fixed-width line here")))))
22223 ;; Region active.
22224 (let* ((begin (save-excursion
22225 (goto-char (region-beginning))
22226 (line-beginning-position)))
22227 (end (copy-marker
22228 (save-excursion
22229 (goto-char (region-end))
22230 (unless (eolp) (beginning-of-line))
22231 (if (save-excursion (re-search-backward "\\S-" begin t))
22232 (progn (skip-chars-backward " \r\t\n") (point))
22233 (point)))))
22234 (all-fixed-width-p
22235 (catch 'not-all-p
22236 (save-excursion
22237 (goto-char begin)
22238 (skip-chars-forward " \r\t\n")
22239 (when (eobp) (throw 'not-all-p nil))
22240 (while (< (point) end)
22241 (let ((element (org-element-at-point)))
22242 (if (eq (org-element-type element) 'fixed-width)
22243 (goto-char (org-element-property :end element))
22244 (throw 'not-all-p nil))))
22245 t))))
22246 (if all-fixed-width-p
22247 (save-excursion
22248 (goto-char begin)
22249 (while (< (point) end)
22250 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22251 (replace-match
22252 "" nil nil nil
22253 (if (= (line-end-position) (match-end 0)) 0 1)))
22254 (forward-line)))
22255 (let ((min-ind (point-max)))
22256 ;; Find minimum indentation across all lines.
22257 (save-excursion
22258 (goto-char begin)
22259 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22260 (setq min-ind 0)
22261 (catch 'zerop
22262 (while (< (point) end)
22263 (unless (looking-at-p "[ \t]*$")
22264 (let ((ind (org-get-indentation)))
22265 (setq min-ind (min min-ind ind))
22266 (when (zerop ind) (throw 'zerop t))))
22267 (forward-line)))))
22268 ;; Loop over all lines and add fixed-width markup everywhere
22269 ;; but in fixed-width lines.
22270 (save-excursion
22271 (goto-char begin)
22272 (while (< (point) end)
22273 (cond
22274 ((org-at-heading-p)
22275 (insert ": ")
22276 (forward-line)
22277 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22278 (insert ":")
22279 (forward-line)))
22280 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22281 (let* ((element (org-element-at-point))
22282 (element-end (org-element-property :end element)))
22283 (if (eq (org-element-type element) 'fixed-width)
22284 (progn (goto-char element-end)
22285 (skip-chars-backward " \r\t\n")
22286 (forward-line))
22287 (let ((limit (min end element-end)))
22288 (while (< (point) limit)
22289 (org-move-to-column min-ind t)
22290 (insert ": ")
22291 (forward-line))))))
22293 (org-move-to-column min-ind t)
22294 (insert ": ")
22295 (forward-line)))))))
22296 (set-marker end nil))))
22299 ;;; Blocks
22301 (defun org-block-map (function &optional start end)
22302 "Call FUNCTION at the head of all source blocks in the current buffer.
22303 Optional arguments START and END can be used to limit the range."
22304 (let ((start (or start (point-min)))
22305 (end (or end (point-max))))
22306 (save-excursion
22307 (goto-char start)
22308 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22309 (save-excursion
22310 (save-match-data
22311 (goto-char (match-beginning 0))
22312 (funcall function)))))))
22314 (defun org-next-block (arg &optional backward block-regexp)
22315 "Jump to the next block.
22317 With a prefix argument ARG, jump forward ARG many blocks.
22319 When BACKWARD is non-nil, jump to the previous block.
22321 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22322 Match data is set according to this regexp when the function
22323 returns.
22325 Return point at beginning of the opening line of found block.
22326 Throw an error if no block is found."
22327 (interactive "p")
22328 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22329 (case-fold-search t)
22330 (search-fn (if backward #'re-search-backward #'re-search-forward))
22331 (count (or arg 1))
22332 (origin (point))
22333 last-element)
22334 (if backward (beginning-of-line) (end-of-line))
22335 (while (and (> count 0) (funcall search-fn re nil t))
22336 (let ((element (save-excursion
22337 (goto-char (match-beginning 0))
22338 (save-match-data (org-element-at-point)))))
22339 (when (and (memq (org-element-type element)
22340 '(center-block comment-block dynamic-block
22341 example-block export-block quote-block
22342 special-block src-block verse-block))
22343 (<= (match-beginning 0)
22344 (org-element-property :post-affiliated element)))
22345 (setq last-element element)
22346 (cl-decf count))))
22347 (if (= count 0)
22348 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22349 (save-match-data (org-show-context)))
22350 (goto-char origin)
22351 (user-error "No %s code blocks" (if backward "previous" "further")))))
22353 (defun org-previous-block (arg &optional block-regexp)
22354 "Jump to the previous block.
22355 With a prefix argument ARG, jump backward ARG many source blocks.
22356 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22357 (interactive "p")
22358 (org-next-block arg t block-regexp))
22361 ;;; Comments
22363 ;; Org comments syntax is quite complex. It requires the entire line
22364 ;; to be just a comment. Also, even with the right syntax at the
22365 ;; beginning of line, some elements (e.g., verse-block or
22366 ;; example-block) don't accept comments. Usual Emacs comment commands
22367 ;; cannot cope with those requirements. Therefore, Org replaces them.
22369 ;; Org still relies on `comment-dwim', but cannot trust
22370 ;; `comment-only-p'. So, `comment-region-function' and
22371 ;; `uncomment-region-function' both point
22372 ;; to`org-comment-or-uncomment-region'. Eventually,
22373 ;; `org-insert-comment' takes care of insertion of comments at the
22374 ;; beginning of line.
22376 ;; `org-setup-comments-handling' install comments related variables
22377 ;; during `org-mode' initialization.
22379 (defun org-setup-comments-handling ()
22380 (interactive)
22381 (setq-local comment-use-syntax nil)
22382 (setq-local comment-start "# ")
22383 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22384 (setq-local comment-insert-comment-function 'org-insert-comment)
22385 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22386 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22388 (defun org-insert-comment ()
22389 "Insert an empty comment above current line.
22390 If the line is empty, insert comment at its beginning. When
22391 point is within a source block, comment according to the related
22392 major mode."
22393 (if (let ((element (org-element-at-point)))
22394 (and (eq (org-element-type element) 'src-block)
22395 (< (save-excursion
22396 (goto-char (org-element-property :post-affiliated element))
22397 (line-end-position))
22398 (point))
22399 (> (save-excursion
22400 (goto-char (org-element-property :end element))
22401 (skip-chars-backward " \r\t\n")
22402 (line-beginning-position))
22403 (point))))
22404 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22405 (beginning-of-line)
22406 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22407 (open-line 1))
22408 (org-indent-line)
22409 (insert "# ")))
22411 (defvar comment-empty-lines) ; From newcomment.el.
22412 (defun org-comment-or-uncomment-region (beg end &rest _)
22413 "Comment or uncomment each non-blank line in the region.
22414 Uncomment each non-blank line between BEG and END if it only
22415 contains commented lines. Otherwise, comment them. If region is
22416 strictly within a source block, use appropriate comment syntax."
22417 (if (let ((element (org-element-at-point)))
22418 (and (eq (org-element-type element) 'src-block)
22419 (< (save-excursion
22420 (goto-char (org-element-property :post-affiliated element))
22421 (line-end-position))
22422 beg)
22423 (>= (save-excursion
22424 (goto-char (org-element-property :end element))
22425 (skip-chars-backward " \r\t\n")
22426 (line-beginning-position))
22427 end)))
22428 ;; Translate region boundaries for the Org buffer to the source
22429 ;; buffer.
22430 (let ((offset (- end beg)))
22431 (save-excursion
22432 (goto-char beg)
22433 (org-babel-do-in-edit-buffer
22434 (comment-or-uncomment-region (point) (+ offset (point))))))
22435 (save-restriction
22436 ;; Restrict region
22437 (narrow-to-region (save-excursion (goto-char beg)
22438 (skip-chars-forward " \r\t\n" end)
22439 (line-beginning-position))
22440 (save-excursion (goto-char end)
22441 (skip-chars-backward " \r\t\n" beg)
22442 (line-end-position)))
22443 (let ((uncommentp
22444 ;; UNCOMMENTP is non-nil when every non blank line between
22445 ;; BEG and END is a comment.
22446 (save-excursion
22447 (goto-char (point-min))
22448 (while (and (not (eobp))
22449 (let ((element (org-element-at-point)))
22450 (and (eq (org-element-type element) 'comment)
22451 (goto-char (min (point-max)
22452 (org-element-property
22453 :end element)))))))
22454 (eobp))))
22455 (if uncommentp
22456 ;; Only blank lines and comments in region: uncomment it.
22457 (save-excursion
22458 (goto-char (point-min))
22459 (while (not (eobp))
22460 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22461 (replace-match "" nil nil nil 1))
22462 (forward-line)))
22463 ;; Comment each line in region.
22464 (let ((min-indent (point-max)))
22465 ;; First find the minimum indentation across all lines.
22466 (save-excursion
22467 (goto-char (point-min))
22468 (while (and (not (eobp)) (not (zerop min-indent)))
22469 (unless (looking-at "[ \t]*$")
22470 (setq min-indent (min min-indent (current-indentation))))
22471 (forward-line)))
22472 ;; Then loop over all lines.
22473 (save-excursion
22474 (goto-char (point-min))
22475 (while (not (eobp))
22476 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22477 ;; Don't get fooled by invisible text (e.g. link path)
22478 ;; when moving to column MIN-INDENT.
22479 (let ((buffer-invisibility-spec nil))
22480 (org-move-to-column min-indent t))
22481 (insert comment-start))
22482 (forward-line)))))))))
22484 (defun org-comment-dwim (_arg)
22485 "Call the comment command you mean.
22486 Call `org-toggle-comment' if on a heading, otherwise call
22487 `comment-dwim', within a source edit buffer if needed."
22488 (interactive "*P")
22489 (cond ((org-at-heading-p)
22490 (call-interactively #'org-toggle-comment))
22491 ((org-in-src-block-p)
22492 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22493 (t (call-interactively #'comment-dwim))))
22496 ;;; Timestamps API
22498 ;; This section contains tools to operate on, or create, timestamp
22499 ;; objects, as returned by, e.g. `org-element-context'.
22501 (defun org-timestamp-from-string (s)
22502 "Convert Org timestamp S, as a string, into a timestamp object.
22503 Return nil if S is not a valid timestamp string."
22504 (when (org-string-nw-p s)
22505 (with-temp-buffer
22506 (save-excursion (insert s))
22507 (org-element-timestamp-parser))))
22509 (defun org-timestamp-from-time (time &optional with-time inactive)
22510 "Convert a time value into a timestamp object.
22512 TIME is an Emacs internal time representation, as returned, e.g.,
22513 by `current-time'.
22515 When optional argument WITH-TIME is non-nil, return a timestamp
22516 object with a time part, i.e., with hours and minutes.
22518 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22519 return an active timestamp."
22520 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22521 (org-element-create 'timestamp
22522 (list :type (if inactive 'inactive 'active)
22523 :year-start year
22524 :month-start month
22525 :day-start day
22526 :hour-start (and with-time hour)
22527 :minute-start (and with-time minute)))))
22529 (defun org-timestamp-to-time (timestamp &optional end)
22530 "Convert TIMESTAMP object into an Emacs internal time value.
22531 Use end of date range or time range when END is non-nil.
22532 Otherwise, use its start."
22533 (apply #'encode-time
22534 (cons 0
22535 (mapcar
22536 (lambda (prop) (or (org-element-property prop timestamp) 0))
22537 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22538 '(:minute-start :hour-start :day-start :month-start
22539 :year-start))))))
22541 (defun org-timestamp-has-time-p (timestamp)
22542 "Non-nil when TIMESTAMP has a time specified."
22543 (org-element-property :hour-start timestamp))
22545 (defun org-timestamp-format (timestamp format &optional end utc)
22546 "Format a TIMESTAMP object into a string.
22548 FORMAT is a format specifier to be passed to
22549 `format-time-string'.
22551 When optional argument END is non-nil, use end of date-range or
22552 time-range, if possible.
22554 When optional argument UTC is non-nil, time is be expressed as
22555 Universal Time."
22556 (format-time-string format (org-timestamp-to-time timestamp end)
22557 (and utc t)))
22559 (defun org-timestamp-split-range (timestamp &optional end)
22560 "Extract a TIMESTAMP object from a date or time range.
22562 END, when non-nil, means extract the end of the range.
22563 Otherwise, extract its start.
22565 Return a new timestamp object."
22566 (let ((type (org-element-property :type timestamp)))
22567 (if (memq type '(active inactive diary)) timestamp
22568 (let ((split-ts (org-element-copy timestamp)))
22569 ;; Set new type.
22570 (org-element-put-property
22571 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22572 ;; Copy start properties over end properties if END is
22573 ;; non-nil. Otherwise, copy end properties over `start' ones.
22574 (let ((p-alist '((:minute-start . :minute-end)
22575 (:hour-start . :hour-end)
22576 (:day-start . :day-end)
22577 (:month-start . :month-end)
22578 (:year-start . :year-end))))
22579 (dolist (p-cell p-alist)
22580 (org-element-put-property
22581 split-ts
22582 (funcall (if end #'car #'cdr) p-cell)
22583 (org-element-property
22584 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22585 ;; Eventually refresh `:raw-value'.
22586 (org-element-put-property split-ts :raw-value nil)
22587 (org-element-put-property
22588 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22590 (defun org-timestamp-translate (timestamp &optional boundary)
22591 "Translate TIMESTAMP object to custom format.
22593 Format string is defined in `org-time-stamp-custom-formats',
22594 which see.
22596 When optional argument BOUNDARY is non-nil, it is either the
22597 symbol `start' or `end'. In this case, only translate the
22598 starting or ending part of TIMESTAMP if it is a date or time
22599 range. Otherwise, translate both parts.
22601 Return timestamp as-is if `org-display-custom-times' is nil or if
22602 it has a `diary' type."
22603 (let ((type (org-element-property :type timestamp)))
22604 (if (or (not org-display-custom-times) (eq type 'diary))
22605 (org-element-interpret-data timestamp)
22606 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22607 org-time-stamp-custom-formats)))
22608 (if (and (not boundary) (memq type '(active-range inactive-range)))
22609 (concat (org-timestamp-format timestamp fmt)
22610 "--"
22611 (org-timestamp-format timestamp fmt t))
22612 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22616 ;;; Other stuff.
22618 (defvar reftex-docstruct-symbol)
22619 (defvar org--rds)
22621 (defun org-reftex-citation ()
22622 "Use reftex-citation to insert a citation into the buffer.
22623 This looks for a line like
22625 #+BIBLIOGRAPHY: foo plain option:-d
22627 and derives from it that foo.bib is the bibliography file relevant
22628 for this document. It then installs the necessary environment for RefTeX
22629 to work in this buffer and calls `reftex-citation' to insert a citation
22630 into the buffer.
22632 Export of such citations to both LaTeX and HTML is handled by the contributed
22633 package ox-bibtex by Taru Karttunen."
22634 (interactive)
22635 (let ((reftex-docstruct-symbol 'org--rds)
22636 org--rds bib)
22637 (org-with-wide-buffer
22638 (let ((case-fold-search t)
22639 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22640 (if (not (save-excursion
22641 (or (re-search-forward re nil t)
22642 (re-search-backward re nil t))))
22643 (user-error "No bibliography defined in file")
22644 (setq bib (concat (match-string 1) ".bib")
22645 org--rds (list (list 'bib bib))))))
22646 (call-interactively 'reftex-citation)))
22648 ;;;; Functions extending outline functionality
22650 (defun org-beginning-of-line (&optional n)
22651 "Go to the beginning of the current visible line.
22653 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22654 tags on the first attempt, and only move to after the tags when
22655 the cursor is already beyond the end of the headline.
22657 With argument N not nil or 1, move forward N - 1 lines first."
22658 (interactive "^p")
22659 (let ((origin (point))
22660 (special (pcase org-special-ctrl-a/e
22661 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22662 deactivate-mark)
22663 ;; First move to a visible line.
22664 (if (bound-and-true-p visual-line-mode)
22665 (beginning-of-visual-line n)
22666 (move-beginning-of-line n)
22667 ;; `move-beginning-of-line' may leave point after invisible
22668 ;; characters if line starts with such of these (e.g., with
22669 ;; a link at column 0). Really move to the beginning of the
22670 ;; current visible line.
22671 (beginning-of-line))
22672 (cond
22673 ;; No special behavior. Point is already at the beginning of
22674 ;; a line, logical or visual.
22675 ((not special))
22676 ;; `beginning-of-visual-line' left point before logical beginning
22677 ;; of line: point is at the beginning of a visual line. Bail
22678 ;; out.
22679 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22680 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22681 ;; At a headline, special position is before the title, but
22682 ;; after any TODO keyword or priority cookie.
22683 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22684 (line-end-position)))
22685 (bol (point)))
22686 (if (eq special 'reversed)
22687 (when (and (= origin bol) (eq last-command this-command))
22688 (goto-char refpos))
22689 (when (or (> origin refpos) (= origin bol))
22690 (goto-char refpos)))))
22691 ((and (looking-at org-list-full-item-re)
22692 (memq (org-element-type (save-match-data (org-element-at-point)))
22693 '(item plain-list)))
22694 ;; Set special position at first white space character after
22695 ;; bullet, and check-box, if any.
22696 (let ((after-bullet
22697 (let ((box (match-end 3)))
22698 (cond ((not box) (match-end 1))
22699 ((eq (char-after box) ?\s) (1+ box))
22700 (t box)))))
22701 (if (eq special 'reversed)
22702 (when (and (= (point) origin) (eq last-command this-command))
22703 (goto-char after-bullet))
22704 (when (or (> origin after-bullet) (= (point) origin))
22705 (goto-char after-bullet)))))
22706 ;; No special context. Point is already at beginning of line.
22707 (t nil))))
22709 (defun org-end-of-line (&optional n)
22710 "Go to the end of the line, but before ellipsis, if any.
22712 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22713 tags on the first attempt, and only move to after the tags when
22714 the cursor is already beyond the end of the headline.
22716 With argument N not nil or 1, move forward N - 1 lines first."
22717 (interactive "^p")
22718 (let ((origin (point))
22719 (special (pcase org-special-ctrl-a/e
22720 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22721 deactivate-mark)
22722 ;; First move to a visible line.
22723 (if (bound-and-true-p visual-line-mode)
22724 (beginning-of-visual-line n)
22725 (move-beginning-of-line n))
22726 (cond
22727 ;; At a headline, with tags.
22728 ((and special
22729 (save-excursion
22730 (beginning-of-line)
22731 (let ((case-fold-search nil))
22732 (looking-at org-complex-heading-regexp)))
22733 (match-end 5))
22734 (let ((tags (save-excursion
22735 (goto-char (match-beginning 5))
22736 (skip-chars-backward " \t")
22737 (point)))
22738 (visual-end (and (bound-and-true-p visual-line-mode)
22739 (save-excursion
22740 (end-of-visual-line)
22741 (point)))))
22742 ;; If `end-of-visual-line' brings us before end of line or
22743 ;; even tags, i.e., the headline spans over multiple visual
22744 ;; lines, move there.
22745 (cond ((and visual-end
22746 (< visual-end tags)
22747 (<= origin visual-end))
22748 (goto-char visual-end))
22749 ((eq special 'reversed)
22750 (if (and (= origin (line-end-position))
22751 (eq this-command last-command))
22752 (goto-char tags)
22753 (end-of-line)))
22755 (if (or (< origin tags) (= origin (line-end-position)))
22756 (goto-char tags)
22757 (end-of-line))))))
22758 ((bound-and-true-p visual-line-mode)
22759 (let ((bol (line-beginning-position)))
22760 (end-of-visual-line)
22761 ;; If `end-of-visual-line' gets us past the ellipsis at the
22762 ;; end of a line, backtrack and use `end-of-line' instead.
22763 (when (/= bol (line-beginning-position))
22764 (goto-char bol)
22765 (end-of-line))))
22766 (t (end-of-line)))))
22768 (defun org-backward-sentence (&optional _arg)
22769 "Go to beginning of sentence, or beginning of table field.
22770 This will call `backward-sentence' or `org-table-beginning-of-field',
22771 depending on context."
22772 (interactive)
22773 (let* ((element (org-element-at-point))
22774 (contents-begin (org-element-property :contents-begin element))
22775 (table (org-element-lineage element '(table) t)))
22776 (if (and table
22777 (> (point) contents-begin)
22778 (<= (point) (org-element-property :contents-end table)))
22779 (call-interactively #'org-table-beginning-of-field)
22780 (save-restriction
22781 (when (and contents-begin
22782 (< (point-min) contents-begin)
22783 (> (point) contents-begin))
22784 (narrow-to-region contents-begin
22785 (org-element-property :contents-end element)))
22786 (call-interactively #'backward-sentence)))))
22788 (defun org-forward-sentence (&optional _arg)
22789 "Go to end of sentence, or end of table field.
22790 This will call `forward-sentence' or `org-table-end-of-field',
22791 depending on context."
22792 (interactive)
22793 (if (and (org-at-heading-p)
22794 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22795 (save-restriction
22796 (narrow-to-region (line-beginning-position) (line-end-position))
22797 (call-interactively #'forward-sentence))
22798 (let* ((element (org-element-at-point))
22799 (contents-end (org-element-property :contents-end element))
22800 (table (org-element-lineage element '(table) t)))
22801 (if (and table
22802 (>= (point) (org-element-property :contents-begin table))
22803 (< (point) contents-end))
22804 (call-interactively #'org-table-end-of-field)
22805 (save-restriction
22806 (when (and contents-end
22807 (> (point-max) contents-end)
22808 ;; Skip blank lines between elements.
22809 (< (org-element-property :end element)
22810 (save-excursion (goto-char contents-end)
22811 (skip-chars-forward " \r\t\n"))))
22812 (narrow-to-region (org-element-property :contents-begin element)
22813 contents-end))
22814 ;; End of heading is considered as the end of a sentence.
22815 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22816 (call-interactively #'forward-sentence)))))))
22818 (defun org-kill-line (&optional _arg)
22819 "Kill line, to tags or end of line."
22820 (interactive)
22821 (cond
22822 ((or (not org-special-ctrl-k)
22823 (bolp)
22824 (not (org-at-heading-p)))
22825 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22826 org-ctrl-k-protect-subtree
22827 (or (eq org-ctrl-k-protect-subtree 'error)
22828 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22829 (user-error "C-k aborted as it would kill a hidden subtree"))
22830 (call-interactively
22831 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22832 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22833 (kill-region (point) (match-beginning 1))
22834 (org-set-tags nil t))
22835 (t (kill-region (point) (point-at-eol)))))
22837 (defun org-yank (&optional arg)
22838 "Yank. If the kill is a subtree, treat it specially.
22839 This command will look at the current kill and check if is a single
22840 subtree, or a series of subtrees[1]. If it passes the test, and if the
22841 cursor is at the beginning of a line or after the stars of a currently
22842 empty headline, then the yank is handled specially. How exactly depends
22843 on the value of the following variables.
22845 `org-yank-folded-subtrees'
22846 By default, this variable is non-nil, which results in
22847 subtree(s) being folded after insertion, except if doing so
22848 would swallow text after the yanked text.
22850 `org-yank-adjusted-subtrees'
22851 When non-nil (the default value is nil), the subtree will be
22852 promoted or demoted in order to fit into the local outline tree
22853 structure, which means that the level will be adjusted so that it
22854 becomes the smaller one of the two *visible* surrounding headings.
22856 Any prefix to this command will cause `yank' to be called directly with
22857 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22858 will just
22859 plainly yank the text as it is.
22861 \[1] The test checks if the first non-white line is a heading
22862 and if there are no other headings with fewer stars."
22863 (interactive "P")
22864 (org-yank-generic 'yank arg))
22866 (defun org-yank-generic (command arg)
22867 "Perform some yank-like command.
22869 This function implements the behavior described in the `org-yank'
22870 documentation. However, it has been generalized to work for any
22871 interactive command with similar behavior."
22873 ;; pretend to be command COMMAND
22874 (setq this-command command)
22876 (if arg
22877 (call-interactively command)
22879 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22880 (and (org-kill-is-subtree-p)
22881 (or (bolp)
22882 (and (looking-at "[ \t]*$")
22883 (string-match
22884 "\\`\\*+\\'"
22885 (buffer-substring (point-at-bol) (point)))))))
22886 swallowp)
22887 (cond
22888 ((and subtreep org-yank-folded-subtrees)
22889 (let ((beg (point))
22890 end)
22891 (if (and subtreep org-yank-adjusted-subtrees)
22892 (org-paste-subtree nil nil 'for-yank)
22893 (call-interactively command))
22895 (setq end (point))
22896 (goto-char beg)
22897 (when (and (bolp) subtreep
22898 (not (setq swallowp
22899 (org-yank-folding-would-swallow-text beg end))))
22900 (org-with-limited-levels
22901 (or (looking-at org-outline-regexp)
22902 (re-search-forward org-outline-regexp-bol end t))
22903 (while (and (< (point) end) (looking-at org-outline-regexp))
22904 (outline-hide-subtree)
22905 (org-cycle-show-empty-lines 'folded)
22906 (condition-case nil
22907 (outline-forward-same-level 1)
22908 (error (goto-char end))))))
22909 (when swallowp
22910 (message
22911 "Inserted text not folded because that would swallow text"))
22913 (goto-char end)
22914 (skip-chars-forward " \t\n\r")
22915 (beginning-of-line 1)
22916 (push-mark beg 'nomsg)))
22917 ((and subtreep org-yank-adjusted-subtrees)
22918 (let ((beg (point-at-bol)))
22919 (org-paste-subtree nil nil 'for-yank)
22920 (push-mark beg 'nomsg)))
22922 (call-interactively command))))))
22924 (defun org-yank-folding-would-swallow-text (beg end)
22925 "Would hide-subtree at BEG swallow any text after END?"
22926 (let (level)
22927 (org-with-limited-levels
22928 (save-excursion
22929 (goto-char beg)
22930 (when (or (looking-at org-outline-regexp)
22931 (re-search-forward org-outline-regexp-bol end t))
22932 (setq level (org-outline-level)))
22933 (goto-char end)
22934 (skip-chars-forward " \t\r\n\v\f")
22935 (not (or (eobp)
22936 (and (bolp) (looking-at-p org-outline-regexp)
22937 (<= (org-outline-level) level))))))))
22939 (defun org-back-to-heading (&optional invisible-ok)
22940 "Call `outline-back-to-heading', but provide a better error message."
22941 (condition-case nil
22942 (outline-back-to-heading invisible-ok)
22943 (error (error "Before first headline at position %d in buffer %s"
22944 (point) (current-buffer)))))
22946 (defun org-before-first-heading-p ()
22947 "Before first heading?"
22948 (save-excursion
22949 (end-of-line)
22950 (null (re-search-backward org-outline-regexp-bol nil t))))
22952 (defun org-at-heading-p (&optional ignored)
22953 (outline-on-heading-p t))
22955 (defun org-in-commented-heading-p (&optional no-inheritance)
22956 "Non-nil if point is under a commented heading.
22957 This function also checks ancestors of the current headline,
22958 unless optional argument NO-INHERITANCE is non-nil."
22959 (cond
22960 ((org-before-first-heading-p) nil)
22961 ((let ((headline (nth 4 (org-heading-components))))
22962 (and headline
22963 (let ((case-fold-search nil))
22964 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22965 headline)))))
22966 (no-inheritance nil)
22968 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22970 (defun org-at-comment-p nil
22971 "Is cursor in a commented line?"
22972 (save-excursion
22973 (save-match-data
22974 (beginning-of-line)
22975 (looking-at "^[ \t]*# "))))
22977 (defun org-at-drawer-p nil
22978 "Is cursor at a drawer keyword?"
22979 (save-excursion
22980 (move-beginning-of-line 1)
22981 (looking-at org-drawer-regexp)))
22983 (defun org-at-block-p nil
22984 "Is cursor at a block keyword?"
22985 (save-excursion
22986 (move-beginning-of-line 1)
22987 (looking-at org-block-regexp)))
22989 (defun org-point-at-end-of-empty-headline ()
22990 "If point is at the end of an empty headline, return t, else nil.
22991 If the heading only contains a TODO keyword, it is still still considered
22992 empty."
22993 (let ((case-fold-search nil))
22994 (and (looking-at "[ \t]*$")
22995 org-todo-line-regexp
22996 (save-excursion
22997 (beginning-of-line)
22998 (looking-at org-todo-line-regexp)
22999 (string= (match-string 3) "")))))
23001 (defun org-at-heading-or-item-p ()
23002 (or (org-at-heading-p) (org-at-item-p)))
23004 (defun org-at-target-p ()
23005 (or (org-in-regexp org-radio-target-regexp)
23006 (org-in-regexp org-target-regexp)))
23007 ;; Compatibility alias with Org versions < 7.8.03
23008 (defalias 'org-on-target-p 'org-at-target-p)
23010 (defun org-up-heading-all (arg)
23011 "Move to the heading line of which the present line is a subheading.
23012 This function considers both visible and invisible heading lines.
23013 With argument, move up ARG levels."
23014 (outline-up-heading arg t))
23016 (defun org-up-heading-safe ()
23017 "Move to the heading line of which the present line is a subheading.
23018 This version will not throw an error. It will return the level of the
23019 headline found, or nil if no higher level is found.
23021 Also, this function will be a lot faster than `outline-up-heading',
23022 because it relies on stars being the outline starters. This can really
23023 make a significant difference in outlines with very many siblings."
23024 (when (ignore-errors (org-back-to-heading t))
23025 (let ((level-up (1- (funcall outline-level))))
23026 (and (> level-up 0)
23027 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23028 (funcall outline-level)))))
23030 (defun org-first-sibling-p ()
23031 "Is this heading the first child of its parents?"
23032 (interactive)
23033 (let ((re org-outline-regexp-bol)
23034 level l)
23035 (unless (org-at-heading-p t)
23036 (user-error "Not at a heading"))
23037 (setq level (funcall outline-level))
23038 (save-excursion
23039 (if (not (re-search-backward re nil t))
23041 (setq l (funcall outline-level))
23042 (< l level)))))
23044 (defun org-goto-sibling (&optional previous)
23045 "Goto the next sibling, even if it is invisible.
23046 When PREVIOUS is set, go to the previous sibling instead. Returns t
23047 when a sibling was found. When none is found, return nil and don't
23048 move point."
23049 (let ((fun (if previous 're-search-backward 're-search-forward))
23050 (pos (point))
23051 (re org-outline-regexp-bol)
23052 level l)
23053 (when (ignore-errors (org-back-to-heading t))
23054 (setq level (funcall outline-level))
23055 (catch 'exit
23056 (or previous (forward-char 1))
23057 (while (funcall fun re nil t)
23058 (setq l (funcall outline-level))
23059 (when (< l level) (goto-char pos) (throw 'exit nil))
23060 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23061 (goto-char pos)
23062 nil))))
23064 (defun org-show-siblings ()
23065 "Show all siblings of the current headline."
23066 (save-excursion
23067 (while (org-goto-sibling) (org-flag-heading nil)))
23068 (save-excursion
23069 (while (org-goto-sibling 'previous)
23070 (org-flag-heading nil))))
23072 (defun org-goto-first-child ()
23073 "Goto the first child, even if it is invisible.
23074 Return t when a child was found. Otherwise don't move point and
23075 return nil."
23076 (let (level (pos (point)) (re org-outline-regexp-bol))
23077 (when (ignore-errors (org-back-to-heading t))
23078 (setq level (outline-level))
23079 (forward-char 1)
23080 (if (and (re-search-forward re nil t) (> (outline-level) level))
23081 (progn (goto-char (match-beginning 0)) t)
23082 (goto-char pos) nil))))
23084 (defun org-show-hidden-entry ()
23085 "Show an entry where even the heading is hidden."
23086 (save-excursion
23087 (org-show-entry)))
23089 (defun org-flag-heading (flag &optional entry)
23090 "Flag the current heading. FLAG non-nil means make invisible.
23091 When ENTRY is non-nil, show the entire entry."
23092 (save-excursion
23093 (org-back-to-heading t)
23094 ;; Check if we should show the entire entry
23095 (if (not entry)
23096 (org-flag-region
23097 (line-end-position 0) (line-end-position) flag 'outline)
23098 (org-show-entry)
23099 (save-excursion
23100 (and (outline-next-heading)
23101 (org-flag-heading nil))))))
23103 (defun org-get-next-sibling ()
23104 "Move to next heading of the same level, and return point.
23105 If there is no such heading, return nil.
23106 This is like outline-next-sibling, but invisible headings are ok."
23107 (let ((level (funcall outline-level)))
23108 (outline-next-heading)
23109 (while (and (not (eobp)) (> (funcall outline-level) level))
23110 (outline-next-heading))
23111 (unless (or (eobp) (< (funcall outline-level) level))
23112 (point))))
23114 (defun org-get-last-sibling ()
23115 "Move to previous heading of the same level, and return point.
23116 If there is no such heading, return nil."
23117 (let ((opoint (point))
23118 (level (funcall outline-level)))
23119 (outline-previous-heading)
23120 (when (and (/= (point) opoint) (outline-on-heading-p t))
23121 (while (and (> (funcall outline-level) level)
23122 (not (bobp)))
23123 (outline-previous-heading))
23124 (unless (< (funcall outline-level) level)
23125 (point)))))
23127 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23128 "Goto to the end of a subtree."
23129 ;; This contains an exact copy of the original function, but it uses
23130 ;; `org-back-to-heading', to make it work also in invisible
23131 ;; trees. And is uses an invisible-ok argument.
23132 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23133 ;; Furthermore, when used inside Org, finding the end of a large subtree
23134 ;; with many children and grandchildren etc, this can be much faster
23135 ;; than the outline version.
23136 (org-back-to-heading invisible-ok)
23137 (let ((first t)
23138 (level (funcall outline-level)))
23139 (if (and (derived-mode-p 'org-mode) (< level 1000))
23140 ;; A true heading (not a plain list item), in Org
23141 ;; This means we can easily find the end by looking
23142 ;; only for the right number of stars. Using a regexp to do
23143 ;; this is so much faster than using a Lisp loop.
23144 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23145 (forward-char 1)
23146 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23147 ;; something else, do it the slow way
23148 (while (and (not (eobp))
23149 (or first (> (funcall outline-level) level)))
23150 (setq first nil)
23151 (outline-next-heading)))
23152 (unless to-heading
23153 (when (memq (preceding-char) '(?\n ?\^M))
23154 ;; Go to end of line before heading
23155 (forward-char -1)
23156 (when (memq (preceding-char) '(?\n ?\^M))
23157 ;; leave blank line before heading
23158 (forward-char -1)))))
23159 (point))
23161 (defun org-end-of-meta-data (&optional full)
23162 "Skip planning line and properties drawer in current entry.
23163 When optional argument FULL is non-nil, also skip empty lines,
23164 clocking lines and regular drawers at the beginning of the
23165 entry."
23166 (org-back-to-heading t)
23167 (forward-line)
23168 (when (looking-at-p org-planning-line-re) (forward-line))
23169 (when (looking-at org-property-drawer-re)
23170 (goto-char (match-end 0))
23171 (forward-line))
23172 (when (and full (not (org-at-heading-p)))
23173 (catch 'exit
23174 (let ((end (save-excursion (outline-next-heading) (point)))
23175 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23176 (while (not (eobp))
23177 (cond ((looking-at-p org-drawer-regexp)
23178 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23179 (forward-line)
23180 (throw 'exit t)))
23181 ((looking-at-p re) (forward-line))
23182 (t (throw 'exit t))))))))
23184 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23185 "Move forward to the ARG'th subheading at same level as this one.
23186 Stop at the first and last subheadings of a superior heading.
23187 Normally this only looks at visible headings, but when INVISIBLE-OK is
23188 non-nil it will also look at invisible ones."
23189 (interactive "p")
23190 (let ((backward? (and arg (< arg 0))))
23191 (if (org-before-first-heading-p)
23192 (if backward? (goto-char (point-min)) (outline-next-heading))
23193 (org-back-to-heading invisible-ok)
23194 (unless backward? (end-of-line)) ;do not match current headline
23195 (let ((level (- (match-end 0) (match-beginning 0) 1))
23196 (f (if backward? #'re-search-backward #'re-search-forward))
23197 (count (if arg (abs arg) 1))
23198 (result (point)))
23199 (while (and (> count 0)
23200 (funcall f org-outline-regexp-bol nil 'move))
23201 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23202 (cond ((< l level) (setq count 0))
23203 ((and (= l level)
23204 (or invisible-ok
23205 (not (org-invisible-p
23206 (line-beginning-position)))))
23207 (cl-decf count)
23208 (when (= l level) (setq result (point)))))))
23209 (goto-char result))
23210 (beginning-of-line))))
23212 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23213 "Move backward to the ARG'th subheading at same level as this one.
23214 Stop at the first and last subheadings of a superior heading."
23215 (interactive "p")
23216 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23218 (defun org-next-visible-heading (arg)
23219 "Move to the next visible heading.
23221 This function wraps `outline-next-visible-heading' with
23222 `org-with-limited-levels' in order to skip over inline tasks and
23223 respect customization of `org-odd-levels-only'."
23224 (interactive "p")
23225 (org-with-limited-levels
23226 (outline-next-visible-heading arg)))
23228 (defun org-previous-visible-heading (arg)
23229 "Move to the previous visible heading.
23231 This function wraps `outline-previous-visible-heading' with
23232 `org-with-limited-levels' in order to skip over inline tasks and
23233 respect customization of `org-odd-levels-only'."
23234 (interactive "p")
23235 (org-with-limited-levels
23236 (outline-previous-visible-heading arg)))
23238 (defun org-forward-paragraph ()
23239 "Move forward to beginning of next paragraph or equivalent.
23241 The function moves point to the beginning of the next visible
23242 structural element, which can be a paragraph, a table, a list
23243 item, etc. It also provides some special moves for convenience:
23245 - On an affiliated keyword, jump to the beginning of the
23246 relative element.
23247 - On an item or a footnote definition, move to the second
23248 element inside, if any.
23249 - On a table or a property drawer, jump after it.
23250 - On a verse or source block, stop after blank lines."
23251 (interactive)
23252 (unless (eobp)
23253 (let* ((deactivate-mark nil)
23254 (element (org-element-at-point))
23255 (type (org-element-type element))
23256 (post-affiliated (org-element-property :post-affiliated element))
23257 (contents-begin (org-element-property :contents-begin element))
23258 (contents-end (org-element-property :contents-end element))
23259 (end (let ((end (org-element-property :end element)) (parent element))
23260 (while (and (setq parent (org-element-property :parent parent))
23261 (= (org-element-property :contents-end parent) end))
23262 (setq end (org-element-property :end parent)))
23263 end)))
23264 (cond ((not element)
23265 (skip-chars-forward " \r\t\n")
23266 (or (eobp) (beginning-of-line)))
23267 ;; On affiliated keywords, move to element's beginning.
23268 ((< (point) post-affiliated)
23269 (goto-char post-affiliated))
23270 ;; At a table row, move to the end of the table. Similarly,
23271 ;; at a node property, move to the end of the property
23272 ;; drawer.
23273 ((memq type '(node-property table-row))
23274 (goto-char (org-element-property
23275 :end (org-element-property :parent element))))
23276 ((memq type '(property-drawer table)) (goto-char end))
23277 ;; Consider blank lines as separators in verse and source
23278 ;; blocks to ease editing.
23279 ((memq type '(src-block verse-block))
23280 (when (eq type 'src-block)
23281 (setq contents-end
23282 (save-excursion (goto-char end)
23283 (skip-chars-backward " \r\t\n")
23284 (line-beginning-position))))
23285 (beginning-of-line)
23286 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23287 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23288 (goto-char end)
23289 (skip-chars-forward " \r\t\n")
23290 (if (= (point) contents-end) (goto-char end)
23291 (beginning-of-line))))
23292 ;; With no contents, just skip element.
23293 ((not contents-begin) (goto-char end))
23294 ;; If contents are invisible, skip the element altogether.
23295 ((org-invisible-p (line-end-position))
23296 (cl-case type
23297 (headline
23298 (org-with-limited-levels (outline-next-visible-heading 1)))
23299 ;; At a plain list, make sure we move to the next item
23300 ;; instead of skipping the whole list.
23301 (plain-list (forward-char)
23302 (org-forward-paragraph))
23303 (otherwise (goto-char end))))
23304 ((>= (point) contents-end) (goto-char end))
23305 ((>= (point) contents-begin)
23306 ;; This can only happen on paragraphs and plain lists.
23307 (cl-case type
23308 (paragraph (goto-char end))
23309 ;; At a plain list, try to move to second element in
23310 ;; first item, if possible.
23311 (plain-list (end-of-line)
23312 (org-forward-paragraph))))
23313 ;; When contents start on the middle of a line (e.g. in
23314 ;; items and footnote definitions), try to reach first
23315 ;; element starting after current line.
23316 ((> (line-end-position) contents-begin)
23317 (end-of-line)
23318 (org-forward-paragraph))
23319 (t (goto-char contents-begin))))))
23321 (defun org-backward-paragraph ()
23322 "Move backward to start of previous paragraph or equivalent.
23324 The function moves point to the beginning of the current
23325 structural element, which can be a paragraph, a table, a list
23326 item, etc., or to the beginning of the previous visible one if
23327 point is already there. It also provides some special moves for
23328 convenience:
23330 - On an affiliated keyword, jump to the first one.
23331 - On a table or a property drawer, move to its beginning.
23332 - On comment, example, export, src and verse blocks, stop
23333 before blank lines."
23334 (interactive)
23335 (unless (bobp)
23336 (let* ((deactivate-mark nil)
23337 (element (org-element-at-point))
23338 (type (org-element-type element))
23339 (contents-end (org-element-property :contents-end element))
23340 (post-affiliated (org-element-property :post-affiliated element))
23341 (begin (org-element-property :begin element))
23342 (special? ;blocks handled specially
23343 (memq type '(comment-block example-block export-block src-block
23344 verse-block)))
23345 (contents-begin
23346 (if special?
23347 ;; These types have no proper contents. Fake line
23348 ;; below the block opening line as contents beginning.
23349 (save-excursion (goto-char begin) (line-beginning-position 2))
23350 (org-element-property :contents-begin element))))
23351 (cond
23352 ((not element) (goto-char (point-min)))
23353 ((= (point) begin)
23354 (backward-char)
23355 (org-backward-paragraph))
23356 ((<= (point) post-affiliated) (goto-char begin))
23357 ;; Special behavior: on a table or a property drawer, move to
23358 ;; its beginning.
23359 ((memq type '(node-property table-row))
23360 (goto-char (org-element-property
23361 :post-affiliated (org-element-property :parent element))))
23362 (special?
23363 (if (<= (point) contents-begin) (goto-char post-affiliated)
23364 ;; Inside a verse block, see blank lines as paragraph
23365 ;; separators.
23366 (let ((origin (point)))
23367 (skip-chars-backward " \r\t\n" contents-begin)
23368 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23369 (skip-chars-forward " \r\t\n" origin)
23370 (if (= (point) origin) (goto-char contents-begin)
23371 (beginning-of-line))))))
23372 ((eq type 'paragraph) (goto-char contents-begin)
23373 ;; When at first paragraph in an item or a footnote definition,
23374 ;; move directly to beginning of line.
23375 (let ((parent-contents
23376 (org-element-property
23377 :contents-begin (org-element-property :parent element))))
23378 (when (and parent-contents (= parent-contents contents-begin))
23379 (beginning-of-line))))
23380 ;; At the end of a greater element, move to the beginning of
23381 ;; the last element within.
23382 ((and contents-end (>= (point) contents-end))
23383 (goto-char (1- contents-end))
23384 (org-backward-paragraph))
23385 (t (goto-char (or post-affiliated begin))))
23386 ;; Ensure we never leave point invisible.
23387 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23389 (defun org-forward-element ()
23390 "Move forward by one element.
23391 Move to the next element at the same level, when possible."
23392 (interactive)
23393 (cond ((eobp) (user-error "Cannot move further down"))
23394 ((org-with-limited-levels (org-at-heading-p))
23395 (let ((origin (point)))
23396 (goto-char (org-end-of-subtree nil t))
23397 (unless (org-with-limited-levels (org-at-heading-p))
23398 (goto-char origin)
23399 (user-error "Cannot move further down"))))
23401 (let* ((elem (org-element-at-point))
23402 (end (org-element-property :end elem))
23403 (parent (org-element-property :parent elem)))
23404 (cond ((and parent (= (org-element-property :contents-end parent) end))
23405 (goto-char (org-element-property :end parent)))
23406 ((integer-or-marker-p end) (goto-char end))
23407 (t (message "No element at point")))))))
23409 (defun org-backward-element ()
23410 "Move backward by one element.
23411 Move to the previous element at the same level, when possible."
23412 (interactive)
23413 (cond ((bobp) (user-error "Cannot move further up"))
23414 ((org-with-limited-levels (org-at-heading-p))
23415 ;; At a headline, move to the previous one, if any, or stay
23416 ;; here.
23417 (let ((origin (point)))
23418 (org-with-limited-levels (org-backward-heading-same-level 1))
23419 ;; When current headline has no sibling above, move to its
23420 ;; parent.
23421 (when (= (point) origin)
23422 (or (org-with-limited-levels (org-up-heading-safe))
23423 (progn (goto-char origin)
23424 (user-error "Cannot move further up"))))))
23426 (let* ((elem (org-element-at-point))
23427 (beg (org-element-property :begin elem)))
23428 (cond
23429 ;; Move to beginning of current element if point isn't
23430 ;; there already.
23431 ((null beg) (message "No element at point"))
23432 ((/= (point) beg) (goto-char beg))
23433 (t (goto-char beg)
23434 (skip-chars-backward " \r\t\n")
23435 (unless (bobp)
23436 (let ((prev (org-element-at-point)))
23437 (goto-char (org-element-property :begin prev))
23438 (while (and (setq prev (org-element-property :parent prev))
23439 (<= (org-element-property :end prev) beg))
23440 (goto-char (org-element-property :begin prev)))))))))))
23442 (defun org-up-element ()
23443 "Move to upper element."
23444 (interactive)
23445 (if (org-with-limited-levels (org-at-heading-p))
23446 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23447 (let* ((elem (org-element-at-point))
23448 (parent (org-element-property :parent elem)))
23449 (if parent (goto-char (org-element-property :begin parent))
23450 (if (org-with-limited-levels (org-before-first-heading-p))
23451 (user-error "No surrounding element")
23452 (org-with-limited-levels (org-back-to-heading)))))))
23454 (defun org-down-element ()
23455 "Move to inner element."
23456 (interactive)
23457 (let ((element (org-element-at-point)))
23458 (cond
23459 ((memq (org-element-type element) '(plain-list table))
23460 (goto-char (org-element-property :contents-begin element))
23461 (forward-char))
23462 ((memq (org-element-type element) org-element-greater-elements)
23463 ;; If contents are hidden, first disclose them.
23464 (when (org-invisible-p (line-end-position)) (org-cycle))
23465 (goto-char (or (org-element-property :contents-begin element)
23466 (user-error "No content for this element"))))
23467 (t (user-error "No inner element")))))
23469 (defun org-drag-element-backward ()
23470 "Move backward element at point."
23471 (interactive)
23472 (let ((elem (or (org-element-at-point)
23473 (user-error "No element at point"))))
23474 (if (eq (org-element-type elem) 'headline)
23475 ;; Preserve point when moving a whole tree, even if point was
23476 ;; on blank lines below the headline.
23477 (let ((offset (skip-chars-backward " \t\n")))
23478 (unwind-protect (org-move-subtree-up)
23479 (forward-char (- offset))))
23480 (let ((prev-elem
23481 (save-excursion
23482 (goto-char (org-element-property :begin elem))
23483 (skip-chars-backward " \r\t\n")
23484 (unless (bobp)
23485 (let* ((beg (org-element-property :begin elem))
23486 (prev (org-element-at-point))
23487 (up prev))
23488 (while (and (setq up (org-element-property :parent up))
23489 (<= (org-element-property :end up) beg))
23490 (setq prev up))
23491 prev)))))
23492 ;; Error out if no previous element or previous element is
23493 ;; a parent of the current one.
23494 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23495 (user-error "Cannot drag element backward")
23496 (let ((pos (point)))
23497 (org-element-swap-A-B prev-elem elem)
23498 (goto-char (+ (org-element-property :begin prev-elem)
23499 (- pos (org-element-property :begin elem))))))))))
23501 (defun org-drag-element-forward ()
23502 "Move forward element at point."
23503 (interactive)
23504 (let* ((pos (point))
23505 (elem (or (org-element-at-point)
23506 (user-error "No element at point"))))
23507 (when (= (point-max) (org-element-property :end elem))
23508 (user-error "Cannot drag element forward"))
23509 (goto-char (org-element-property :end elem))
23510 (let ((next-elem (org-element-at-point)))
23511 (when (or (org-element-nested-p elem next-elem)
23512 (and (eq (org-element-type next-elem) 'headline)
23513 (not (eq (org-element-type elem) 'headline))))
23514 (goto-char pos)
23515 (user-error "Cannot drag element forward"))
23516 ;; Compute new position of point: it's shifted by NEXT-ELEM
23517 ;; body's length (without final blanks) and by the length of
23518 ;; blanks between ELEM and NEXT-ELEM.
23519 (let ((size-next (- (save-excursion
23520 (goto-char (org-element-property :end next-elem))
23521 (skip-chars-backward " \r\t\n")
23522 (forward-line)
23523 ;; Small correction if buffer doesn't end
23524 ;; with a newline character.
23525 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23526 (org-element-property :begin next-elem)))
23527 (size-blank (- (org-element-property :end elem)
23528 (save-excursion
23529 (goto-char (org-element-property :end elem))
23530 (skip-chars-backward " \r\t\n")
23531 (forward-line)
23532 (point)))))
23533 (org-element-swap-A-B elem next-elem)
23534 (goto-char (+ pos size-next size-blank))))))
23536 (defun org-drag-line-forward (arg)
23537 "Drag the line at point ARG lines forward."
23538 (interactive "p")
23539 (dotimes (_ (abs arg))
23540 (let ((c (current-column)))
23541 (if (< 0 arg)
23542 (progn
23543 (beginning-of-line 2)
23544 (transpose-lines 1)
23545 (beginning-of-line 0))
23546 (transpose-lines 1)
23547 (beginning-of-line -1))
23548 (org-move-to-column c))))
23550 (defun org-drag-line-backward (arg)
23551 "Drag the line at point ARG lines backward."
23552 (interactive "p")
23553 (org-drag-line-forward (- arg)))
23555 (defun org-mark-element ()
23556 "Put point at beginning of this element, mark at end.
23558 Interactively, if this command is repeated or (in Transient Mark
23559 mode) if the mark is active, it marks the next element after the
23560 ones already marked."
23561 (interactive)
23562 (let (deactivate-mark)
23563 (if (and (called-interactively-p 'any)
23564 (or (and (eq last-command this-command) (mark t))
23565 (and transient-mark-mode mark-active)))
23566 (set-mark
23567 (save-excursion
23568 (goto-char (mark))
23569 (goto-char (org-element-property :end (org-element-at-point)))))
23570 (let ((element (org-element-at-point)))
23571 (end-of-line)
23572 (push-mark (org-element-property :end element) t t)
23573 (goto-char (org-element-property :begin element))))))
23575 (defun org-narrow-to-element ()
23576 "Narrow buffer to current element."
23577 (interactive)
23578 (let ((elem (org-element-at-point)))
23579 (cond
23580 ((eq (car elem) 'headline)
23581 (narrow-to-region
23582 (org-element-property :begin elem)
23583 (org-element-property :end elem)))
23584 ((memq (car elem) org-element-greater-elements)
23585 (narrow-to-region
23586 (org-element-property :contents-begin elem)
23587 (org-element-property :contents-end elem)))
23589 (narrow-to-region
23590 (org-element-property :begin elem)
23591 (org-element-property :end elem))))))
23593 (defun org-transpose-element ()
23594 "Transpose current and previous elements, keeping blank lines between.
23595 Point is moved after both elements."
23596 (interactive)
23597 (org-skip-whitespace)
23598 (let ((end (org-element-property :end (org-element-at-point))))
23599 (org-drag-element-backward)
23600 (goto-char end)))
23602 (defun org-unindent-buffer ()
23603 "Un-indent the visible part of the buffer.
23604 Relative indentation (between items, inside blocks, etc.) isn't
23605 modified."
23606 (interactive)
23607 (unless (eq major-mode 'org-mode)
23608 (user-error "Cannot un-indent a buffer not in Org mode"))
23609 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23610 (unindent-tree
23611 (lambda (contents)
23612 (dolist (element (reverse contents))
23613 (if (memq (org-element-type element) '(headline section))
23614 (funcall unindent-tree (org-element-contents element))
23615 (save-excursion
23616 (save-restriction
23617 (narrow-to-region
23618 (org-element-property :begin element)
23619 (org-element-property :end element))
23620 (org-do-remove-indentation))))))))
23621 (funcall unindent-tree (org-element-contents parse-tree))))
23623 (defun org-make-options-regexp (kwds &optional extra)
23624 "Make a regular expression for keyword lines.
23625 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23626 when non-nil, is a regexp matching keywords names."
23627 (concat "^[ \t]*#\\+\\("
23628 (regexp-opt kwds)
23629 (and extra (concat (and kwds "\\|") extra))
23630 "\\):[ \t]*\\(.*\\)"))
23633 ;;; Finish up
23635 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23636 (lambda () (add-hook 'change-major-mode-hook
23637 'org-show-all 'append 'local)))
23639 (provide 'org)
23641 (run-hooks 'org-load-hook)
23643 ;;; org.el ends here