Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob44c42b26a84ff7618a8c4eb52ee2b0abc6260f20
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-2017 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: http://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 ;; http://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 ;; http://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'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp)
188 (defvar org-element-paragraph-separate)
190 ;; load languages based on value of `org-babel-load-languages'
191 (defvar org-babel-load-languages)
193 ;;;###autoload
194 (defun org-babel-do-load-languages (sym value)
195 "Load the languages defined in `org-babel-load-languages'."
196 (set-default sym value)
197 (dolist (pair org-babel-load-languages)
198 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
199 (if active
200 (require (intern (concat "ob-" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-execute:" lang)))
203 (funcall 'fmakunbound
204 (intern (concat "org-babel-expand-body:" lang)))))))
206 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
207 ;;;###autoload
208 (defun org-babel-load-file (file &optional compile)
209 "Load Emacs Lisp source code blocks in the Org FILE.
210 This function exports the source code using `org-babel-tangle'
211 and then loads the resulting file using `load-file'. With prefix
212 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
213 file to byte-code before it is loaded."
214 (interactive "fFile to load: \nP")
215 (let* ((age (lambda (file)
216 (float-time
217 (time-subtract (current-time)
218 (nth 5 (or (file-attributes (file-truename file))
219 (file-attributes file)))))))
220 (base-name (file-name-sans-extension file))
221 (exported-file (concat base-name ".el")))
222 ;; tangle if the Org file is newer than the elisp file
223 (unless (and (file-exists-p exported-file)
224 (> (funcall age file) (funcall age exported-file)))
225 ;; Tangle-file traversal returns reversed list of tangled files
226 ;; and we want to evaluate the first target.
227 (setq exported-file
228 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
229 (message "%s %s"
230 (if compile
231 (progn (byte-compile-file exported-file 'load)
232 "Compiled and loaded")
233 (progn (load-file exported-file) "Loaded"))
234 exported-file)))
236 (defcustom org-babel-load-languages '((emacs-lisp . t))
237 "Languages which can be evaluated in Org buffers.
238 This list can be used to load support for any of the languages
239 below, note that each language will depend on a different set of
240 system executables and/or Emacs modes. When a language is
241 \"loaded\", then code blocks in that language can be evaluated
242 with `org-babel-execute-src-block' bound by default to C-c
243 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
244 be set to remove code block evaluation from the C-c C-c
245 keybinding. By default only Emacs Lisp (which has no
246 requirements) is loaded."
247 :group 'org-babel
248 :set 'org-babel-do-load-languages
249 :version "24.1"
250 :type '(alist :tag "Babel Languages"
251 :key-type
252 (choice
253 (const :tag "Awk" awk)
254 (const :tag "C" C)
255 (const :tag "R" R)
256 (const :tag "Asymptote" asymptote)
257 (const :tag "Calc" calc)
258 (const :tag "Clojure" clojure)
259 (const :tag "CSS" css)
260 (const :tag "Ditaa" ditaa)
261 (const :tag "Dot" dot)
262 (const :tag "Ebnf2ps" ebnf2ps)
263 (const :tag "Emacs Lisp" emacs-lisp)
264 (const :tag "Forth" forth)
265 (const :tag "Fortran" fortran)
266 (const :tag "Gnuplot" gnuplot)
267 (const :tag "Haskell" haskell)
268 (const :tag "hledger" hledger)
269 (const :tag "IO" io)
270 (const :tag "J" J)
271 (const :tag "Java" java)
272 (const :tag "Javascript" js)
273 (const :tag "LaTeX" latex)
274 (const :tag "Ledger" ledger)
275 (const :tag "Lilypond" lilypond)
276 (const :tag "Lisp" lisp)
277 (const :tag "Makefile" makefile)
278 (const :tag "Maxima" maxima)
279 (const :tag "Matlab" matlab)
280 (const :tag "Mscgen" mscgen)
281 (const :tag "Ocaml" ocaml)
282 (const :tag "Octave" octave)
283 (const :tag "Org" org)
284 (const :tag "Perl" perl)
285 (const :tag "Pico Lisp" picolisp)
286 (const :tag "PlantUML" plantuml)
287 (const :tag "Python" python)
288 (const :tag "Ruby" ruby)
289 (const :tag "Sass" sass)
290 (const :tag "Scala" scala)
291 (const :tag "Scheme" scheme)
292 (const :tag "Screen" screen)
293 (const :tag "Shell Script" shell)
294 (const :tag "Shen" shen)
295 (const :tag "Sql" sql)
296 (const :tag "Sqlite" sqlite)
297 (const :tag "Stan" stan)
298 (const :tag "Vala" vala))
299 :value-type (boolean :tag "Activate" :value t)))
301 ;;;; Customization variables
302 (defcustom org-clone-delete-id nil
303 "Remove ID property of clones of a subtree.
304 When non-nil, clones of a subtree don't inherit the ID property.
305 Otherwise they inherit the ID property with a new unique
306 identifier."
307 :type 'boolean
308 :version "24.1"
309 :group 'org-id)
311 ;;; Version
312 (org-check-version)
314 ;;;###autoload
315 (defun org-version (&optional here full message)
316 "Show the Org version.
317 Interactively, or when MESSAGE is non-nil, show it in echo area.
318 With prefix argument, or when HERE is non-nil, insert it at point.
319 In non-interactive uses, a reduced version string is output unless
320 FULL is given."
321 (interactive (list current-prefix-arg t (not current-prefix-arg)))
322 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
323 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
324 (load-suffixes (list ".el"))
325 (org-install-dir
326 (ignore-errors (org-find-library-dir "org-loaddefs"))))
327 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
328 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
329 (let* ((load-suffixes save-load-suffixes)
330 (release (org-release))
331 (git-version (org-git-version))
332 (version (format "Org mode version %s (%s @ %s)"
333 release
334 git-version
335 (if org-install-dir
336 (if (string= org-dir org-install-dir)
337 org-install-dir
338 (concat "mixed installation! "
339 org-install-dir
340 " and "
341 org-dir))
342 "org-loaddefs.el can not be found!")))
343 (version1 (if full version release)))
344 (when here (insert version1))
345 (when message (message "%s" version1))
346 version1)))
348 (defconst org-version (org-version))
351 ;;; Syntax Constants
353 ;;;; Block
355 (defconst org-block-regexp
356 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
357 "Regular expression for hiding blocks.")
359 (defconst org-dblock-start-re
360 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
361 "Matches the start line of a dynamic block, with parameters.")
363 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
364 "Matches the end of a dynamic block.")
366 ;;;; Clock and Planning
368 (defconst org-clock-string "CLOCK:"
369 "String used as prefix for timestamps clocking work hours on an item.")
371 (defvar org-closed-string "CLOSED:"
372 "String used as the prefix for timestamps logging closing a TODO entry.")
374 (defvar org-deadline-string "DEADLINE:"
375 "String to mark deadline entries.
376 \\<org-mode-map>
377 A deadline is this string, followed by a time stamp. It must be
378 a word, terminated by a colon. You can insert a schedule keyword
379 and a timestamp with `\\[org-deadline]'.")
381 (defvar org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 \\<org-mode-map>
384 A schedule is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-schedule]'.")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (eval-and-compile
526 (defconst org-comment-string "COMMENT"
527 "Entries starting with this keyword will never be exported.
528 \\<org-mode-map>
529 An entry can be toggled between COMMENT and normal with
530 `\\[org-toggle-comment]'."))
533 ;;;; LaTeX Environments and Fragments
535 (defconst org-latex-regexps
536 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
537 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
538 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
539 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
540 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
541 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
542 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
543 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
544 "Regular expressions for matching embedded LaTeX.")
546 ;;;; Node Property
548 (defconst org-effort-property "Effort"
549 "The property that is being used to keep track of effort estimates.
550 Effort estimates given in this property need to have the format H:MM.")
552 ;;;; Table
554 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
555 "Detect an org-type or table-type table.")
557 (defconst org-table-line-regexp "^[ \t]*|"
558 "Detect an org-type table line.")
560 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
561 "Detect an org-type table line.")
563 (defconst org-table-hline-regexp "^[ \t]*|-"
564 "Detect an org-type table hline.")
566 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
567 "Detect a table-type table hline.")
569 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
570 "Detect the first line outside a table when searching from within it.
571 This works for both table types.")
573 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
574 "Detect a #+TBLFM line.")
576 ;;;; Timestamp
578 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
579 "Regular expression for fast time stamp matching.")
581 (defconst org-ts-regexp-inactive
582 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
583 "Regular expression for fast inactive time stamp matching.")
585 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
586 "Regular expression for fast time stamp matching.")
588 (defconst org-ts-regexp0
589 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
590 "Regular expression matching time strings for analysis.
591 This one does not require the space after the date, so it can be used
592 on a string that terminates immediately after the date.")
594 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
595 "Regular expression matching time strings for analysis.")
597 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
598 "Regular expression matching time stamps, with groups.")
600 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
601 "Regular expression matching time stamps (also [..]), with groups.")
603 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
604 "Regular expression matching a time stamp range.")
606 (defconst org-tr-regexp-both
607 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
608 "Regular expression matching a time stamp range.")
610 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
611 org-ts-regexp "\\)?")
612 "Regular expression matching a time stamp or time stamp range.")
614 (defconst org-tsr-regexp-both
615 (concat org-ts-regexp-both "\\(--?-?"
616 org-ts-regexp-both "\\)?")
617 "Regular expression matching a time stamp or time stamp range.
618 The time stamps may be either active or inactive.")
620 (defconst org-repeat-re
621 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
622 "Regular expression for specifying repeated events.
623 After a match, group 1 contains the repeat expression.")
625 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
626 "Formats for `format-time-string' which are used for time stamps.")
629 ;;; The custom variables
631 (defgroup org nil
632 "Outline-based notes management and organizer."
633 :tag "Org"
634 :group 'outlines
635 :group 'calendar)
637 (defcustom org-mode-hook nil
638 "Mode hook for Org mode, run after the mode was turned on."
639 :group 'org
640 :type 'hook)
642 (defcustom org-load-hook nil
643 "Hook that is run after org.el has been loaded."
644 :group 'org
645 :type 'hook)
647 (defcustom org-log-buffer-setup-hook nil
648 "Hook that is run after an Org log buffer is created."
649 :group 'org
650 :version "24.1"
651 :type 'hook)
653 (defvar org-modules) ; defined below
654 (defvar org-modules-loaded nil
655 "Have the modules been loaded already?")
657 (defun org-load-modules-maybe (&optional force)
658 "Load all extensions listed in `org-modules'."
659 (when (or force (not org-modules-loaded))
660 (dolist (ext org-modules)
661 (condition-case nil (require ext)
662 (error (message "Problems while trying to load feature `%s'" ext))))
663 (setq org-modules-loaded t)))
665 (defun org-set-modules (var value)
666 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
667 (set var value)
668 (when (featurep 'org)
669 (org-load-modules-maybe 'force)
670 (org-element-cache-reset 'all)))
672 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
673 "Modules that should always be loaded together with org.el.
675 If a description starts with <C>, the file is not part of Emacs
676 and loading it will require that you have downloaded and properly
677 installed the Org mode distribution.
679 You can also use this system to load external packages (i.e. neither Org
680 core modules, nor modules from the CONTRIB directory). Just add symbols
681 to the end of the list. If the package is called org-xyz.el, then you need
682 to add the symbol `xyz', and the package must have a call to:
684 (provide \\='org-xyz)
686 For export specific modules, see also `org-export-backends'."
687 :group 'org
688 :set 'org-set-modules
689 :version "24.4"
690 :package-version '(Org . "8.0")
691 :type
692 '(set :greedy t
693 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
694 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
695 (const :tag " crypt: Encryption of subtrees" org-crypt)
696 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
697 (const :tag " docview: Links to doc-view buffers" org-docview)
698 (const :tag " eww: Store link to url of eww" org-eww)
699 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
700 (const :tag " habit: Track your consistency with habits" org-habit)
701 (const :tag " id: Global IDs for identifying entries" org-id)
702 (const :tag " info: Links to Info nodes" org-info)
703 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
704 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
705 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
706 (const :tag " mouse: Additional mouse support" org-mouse)
707 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
708 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
709 (const :tag " tempo: Fast completion for structures" org-tempo)
710 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
714 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
715 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
716 (const :tag "C collector: Collect properties into tables" org-collector)
717 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
718 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
719 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
720 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
721 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
722 (const :tag "C eval: Include command output as text" org-eval)
723 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
724 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
725 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
726 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
727 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org buffer" org-toc)
742 (const :tag "C track: Keep up with Org mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend) t)
752 (defcustom org-export-backends '(ascii html icalendar latex odt)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 (progn
769 (setq org-export-registered-backends
770 (cl-remove-if-not
771 (lambda (backend)
772 (let ((name (org-export-backend-name backend)))
773 (or (memq name val)
774 (catch \\='parentp
775 (dolist (b val)
776 (and (org-export-derived-backend-p b name)
777 (throw \\='parentp t)))))))
778 org-export-registered-backends))
779 (let ((new-list (mapcar #\\='org-export-backend-name
780 org-export-registered-backends)))
781 (dolist (backend val)
782 (cond
783 ((not (load (format \"ox-%s\" backend) t t))
784 (message \"Problems while trying to load export back-end \\=`%s\\='\"
785 backend))
786 ((not (memq backend new-list)) (push backend new-list))))
787 (set-default \\='org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "26.1"
794 :package-version '(Org . "9.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (cl-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(dolist (backend org-export-backends)
845 (condition-case nil (require (intern (format "ox-%s" backend)))
846 (error (message "Problems while trying to load export back-end `%s'"
847 backend)))))
849 (defcustom org-support-shift-select nil
850 "Non-nil means make shift-cursor commands select text when possible.
851 \\<org-mode-map>\
853 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
854 start selecting a region, or enlarge regions started in this way.
855 In Org mode, in special contexts, these same keys are used for
856 other purposes, important enough to compete with shift selection.
857 Org tries to balance these needs by supporting `shift-select-mode'
858 outside these special contexts, under control of this variable.
860 The default of this variable is nil, to avoid confusing behavior. Shifted
861 cursor keys will then execute Org commands in the following contexts:
862 - on a headline, changing TODO state (left/right) and priority (up/down)
863 - on a time stamp, changing the time
864 - in a plain list item, changing the bullet type
865 - in a property definition line, switching between allowed values
866 - in the BEGIN line of a clock table (changing the time block).
867 Outside these contexts, the commands will throw an error.
869 When this variable is t and the cursor is not in a special
870 context, Org mode will support shift-selection for making and
871 enlarging regions. To make this more effective, the bullet
872 cycling will no longer happen anywhere in an item line, but only
873 if the cursor is exactly on the bullet.
875 If you set this variable to the symbol `always', then the keys
876 will not be special in headlines, property lines, and item lines,
877 to make shift selection work there as well. If this is what you
878 want, you can use the following alternative commands:
879 `\\[org-todo]' and `\\[org-priority]' \
880 to change TODO state and priority,
881 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
882 can be used to switch TODO sets,
883 `\\[org-ctrl-c-minus]' to cycle item bullet types,
884 and properties can be edited by hand or in column view.
886 However, when the cursor is on a timestamp, shift-cursor commands
887 will still edit the time stamp - this is just too good to give up."
888 :group 'org
889 :type '(choice
890 (const :tag "Never" nil)
891 (const :tag "When outside special context" t)
892 (const :tag "Everywhere except timestamps" always)))
894 (defcustom org-loop-over-headlines-in-active-region nil
895 "Shall some commands act upon headlines in the active region?
897 When set to t, some commands will be performed in all headlines
898 within the active region.
900 When set to `start-level', some commands will be performed in all
901 headlines within the active region, provided that these headlines
902 are of the same level than the first one.
904 When set to a string, those commands will be performed on the
905 matching headlines within the active region. Such string must be
906 a tags/property/todo match as it is used in the agenda tags view.
908 The list of commands is: `org-schedule', `org-deadline',
909 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
910 `org-archive-to-archive-sibling'. The archiving commands skip
911 already archived entries."
912 :type '(choice (const :tag "Don't loop" nil)
913 (const :tag "All headlines in active region" t)
914 (const :tag "In active region, headlines at the same level than the first one" start-level)
915 (string :tag "Tags/Property/Todo matcher"))
916 :version "24.1"
917 :group 'org-todo
918 :group 'org-archive)
920 (defcustom org-startup-folded t
921 "Non-nil means entering Org mode will switch to OVERVIEW.
923 This can also be configured on a per-file basis by adding one of
924 the following lines anywhere in the buffer:
926 #+STARTUP: fold (or `overview', this is equivalent)
927 #+STARTUP: nofold (or `showall', this is equivalent)
928 #+STARTUP: content
929 #+STARTUP: showeverything
931 Set `org-agenda-inhibit-startup' to a non-nil value if you want
932 to ignore this option when Org opens agenda files for the first
933 time."
934 :group 'org-startup
935 :type '(choice
936 (const :tag "nofold: show all" nil)
937 (const :tag "fold: overview" t)
938 (const :tag "content: all headlines" content)
939 (const :tag "show everything, even drawers" showeverything)))
941 (defcustom org-startup-truncated t
942 "Non-nil means entering Org mode will set `truncate-lines'.
943 This is useful since some lines containing links can be very long and
944 uninteresting. Also tables look terrible when wrapped.
946 The variable `org-startup-truncated' allows to configure
947 truncation for Org mode different to the other modes that use the
948 variable `truncate-lines' and as a shortcut instead of putting
949 the variable `truncate-lines' into the `org-mode-hook'. If one
950 wants to configure truncation for Org mode not statically but
951 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
952 the variable `truncate-lines' has to be used because in such a
953 case it is too late to set the variable `org-startup-truncated'."
954 :group 'org-startup
955 :type 'boolean)
957 (defcustom org-startup-indented nil
958 "Non-nil means turn on `org-indent-mode' on startup.
959 This can also be configured on a per-file basis by adding one of
960 the following lines anywhere in the buffer:
962 #+STARTUP: indent
963 #+STARTUP: noindent"
964 :group 'org-structure
965 :type '(choice
966 (const :tag "Not" nil)
967 (const :tag "Globally (slow on startup in large files)" t)))
969 (defcustom org-use-sub-superscripts t
970 "Non-nil means interpret \"_\" and \"^\" for display.
972 If you want to control how Org exports those characters, see
973 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
974 used to be an alias for `org-export-with-sub-superscripts' in
975 Org <8.0, it is not anymore.
977 When this option is turned on, you can use TeX-like syntax for
978 sub- and superscripts within the buffer. Several characters after
979 \"_\" or \"^\" will be considered as a single item - so grouping
980 with {} is normally not needed. For example, the following things
981 will be parsed as single sub- or superscripts:
983 10^24 or 10^tau several digits will be considered 1 item.
984 10^-12 or 10^-tau a leading sign with digits or a word
985 x^2-y^3 will be read as x^2 - y^3, because items are
986 terminated by almost any nonword/nondigit char.
987 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
989 Still, ambiguity is possible. So when in doubt, use {} to enclose
990 the sub/superscript. If you set this variable to the symbol `{}',
991 the braces are *required* in order to trigger interpretations as
992 sub/superscript. This can be helpful in documents that need \"_\"
993 frequently in plain text."
994 :group 'org-startup
995 :version "24.4"
996 :package-version '(Org . "8.0")
997 :type '(choice
998 (const :tag "Always interpret" t)
999 (const :tag "Only with braces" {})
1000 (const :tag "Never interpret" nil)))
1002 (defcustom org-startup-with-beamer-mode nil
1003 "Non-nil means turn on `org-beamer-mode' on startup.
1004 This can also be configured on a per-file basis by adding one of
1005 the following lines anywhere in the buffer:
1007 #+STARTUP: beamer"
1008 :group 'org-startup
1009 :version "24.1"
1010 :type 'boolean)
1012 (defcustom org-startup-align-all-tables nil
1013 "Non-nil means align all tables when visiting a file.
1014 This can also be configured on a per-file basis by adding one of
1015 the following lines anywhere in the buffer:
1016 #+STARTUP: align
1017 #+STARTUP: noalign"
1018 :group 'org-startup
1019 :type 'boolean)
1021 (defcustom org-startup-shrink-all-tables nil
1022 "Non-nil means shrink all table columns with a width cookie.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: shrink"
1026 :group 'org-startup
1027 :type 'boolean
1028 :version "27.1"
1029 :package-version '(Org . "9.2")
1030 :safe #'booleanp)
1032 (defcustom org-startup-with-inline-images nil
1033 "Non-nil means show inline images when loading a new Org file.
1034 This can also be configured on a per-file basis by adding one of
1035 the following lines anywhere in the buffer:
1036 #+STARTUP: inlineimages
1037 #+STARTUP: noinlineimages"
1038 :group 'org-startup
1039 :version "24.1"
1040 :type 'boolean)
1042 (defcustom org-startup-with-latex-preview nil
1043 "Non-nil means preview LaTeX fragments when loading a new Org file.
1045 This can also be configured on a per-file basis by adding one of
1046 the following lines anywhere in the buffer:
1047 #+STARTUP: latexpreview
1048 #+STARTUP: nolatexpreview"
1049 :group 'org-startup
1050 :version "24.4"
1051 :package-version '(Org . "8.0")
1052 :type 'boolean)
1054 (defcustom org-insert-mode-line-in-empty-file nil
1055 "Non-nil means insert the first line setting Org mode in empty files.
1056 When the function `org-mode' is called interactively in an empty file, this
1057 normally means that the file name does not automatically trigger Org mode.
1058 To ensure that the file will always be in Org mode in the future, a
1059 line enforcing Org mode will be inserted into the buffer, if this option
1060 has been set."
1061 :group 'org-startup
1062 :type 'boolean)
1064 (defcustom org-replace-disputed-keys nil
1065 "Non-nil means use alternative key bindings for some keys.
1066 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1067 These keys are also used by other packages like shift-selection-mode'
1068 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1069 If you want to use Org mode together with one of these other modes,
1070 or more generally if you would like to move some Org mode commands to
1071 other keys, set this variable and configure the keys with the variable
1072 `org-disputed-keys'.
1074 This option is only relevant at load-time of Org mode, and must be set
1075 *before* org.el is loaded. Changing it requires a restart of Emacs to
1076 become effective."
1077 :group 'org-startup
1078 :type 'boolean)
1080 (defcustom org-use-extra-keys nil
1081 "Non-nil means use extra key sequence definitions for certain commands.
1082 This happens automatically if `window-system' is nil. This
1083 variable lets you do the same manually. You must set it before
1084 loading Org."
1085 :group 'org-startup
1086 :type 'boolean)
1088 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1090 (defcustom org-disputed-keys
1091 '(([(shift up)] . [(meta p)])
1092 ([(shift down)] . [(meta n)])
1093 ([(shift left)] . [(meta -)])
1094 ([(shift right)] . [(meta +)])
1095 ([(control shift right)] . [(meta shift +)])
1096 ([(control shift left)] . [(meta shift -)]))
1097 "Keys for which Org mode and other modes compete.
1098 This is an alist, cars are the default keys, second element specifies
1099 the alternative to use when `org-replace-disputed-keys' is t.
1101 Keys can be specified in any syntax supported by `define-key'.
1102 The value of this option takes effect only at Org mode startup,
1103 therefore you'll have to restart Emacs to apply it after changing."
1104 :group 'org-startup
1105 :type 'alist)
1107 (defun org-key (key)
1108 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1109 Or return the original if not disputed."
1110 (when org-replace-disputed-keys
1111 (let* ((nkey (key-description key))
1112 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1113 org-disputed-keys)))
1114 (setq key (if x (cdr x) key))))
1115 key)
1117 (defun org-defkey (keymap key def)
1118 "Define a key, possibly translated, as returned by `org-key'."
1119 (define-key keymap (org-key key) def))
1121 (defcustom org-ellipsis nil
1122 "The ellipsis to use in the Org mode outline.
1124 When nil, just use the standard three dots. When a non-empty string,
1125 use that string instead.
1127 The change affects only Org mode (which will then use its own display table).
1128 Changing this requires executing `\\[org-mode]' in a buffer to become
1129 effective."
1130 :group 'org-startup
1131 :type '(choice (const :tag "Default" nil)
1132 (string :tag "String" :value "...#"))
1133 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1135 (defvar org-display-table nil
1136 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1138 (defgroup org-keywords nil
1139 "Keywords in Org mode."
1140 :tag "Org Keywords"
1141 :group 'org)
1143 (defcustom org-closed-keep-when-no-todo nil
1144 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1145 :group 'org-todo
1146 :group 'org-keywords
1147 :version "24.4"
1148 :package-version '(Org . "8.0")
1149 :type 'boolean)
1151 (defgroup org-structure nil
1152 "Options concerning the general structure of Org files."
1153 :tag "Org Structure"
1154 :group 'org)
1156 (defgroup org-reveal-location nil
1157 "Options about how to make context of a location visible."
1158 :tag "Org Reveal Location"
1159 :group 'org-structure)
1161 (defcustom org-show-context-detail '((agenda . local)
1162 (bookmark-jump . lineage)
1163 (isearch . lineage)
1164 (default . ancestors))
1165 "Alist between context and visibility span when revealing a location.
1167 \\<org-mode-map>Some actions may move point into invisible
1168 locations. As a consequence, Org always expose a neighborhood
1169 around point. How much is shown depends on the initial action,
1170 or context. Valid contexts are
1172 agenda when exposing an entry from the agenda
1173 org-goto when using the command `org-goto' (`\\[org-goto]')
1174 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1175 tags-tree when constructing a sparse tree based on tags matches
1176 link-search when exposing search matches associated with a link
1177 mark-goto when exposing the jump goal of a mark
1178 bookmark-jump when exposing a bookmark location
1179 isearch when exiting from an incremental search
1180 default default for all contexts not set explicitly
1182 Allowed visibility spans are
1184 minimal show current headline; if point is not on headline,
1185 also show entry
1187 local show current headline, entry and next headline
1189 ancestors show current headline and its direct ancestors; if
1190 point is not on headline, also show entry
1192 lineage show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and first child
1196 tree show current headline, its direct ancestors and all
1197 their children; if point is not on headline, also show
1198 entry and all children
1200 canonical show current headline, its direct ancestors along with
1201 their entries and children; if point is not located on
1202 the headline, also show current entry and all children
1204 As special cases, a nil or t value means show all contexts in
1205 `minimal' or `canonical' view, respectively.
1207 Some views can make displayed information very compact, but also
1208 make it harder to edit the location of the match. In such
1209 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1210 more context."
1211 :group 'org-reveal-location
1212 :version "26.1"
1213 :package-version '(Org . "9.0")
1214 :type '(choice
1215 (const :tag "Canonical" t)
1216 (const :tag "Minimal" nil)
1217 (repeat :greedy t :tag "Individual contexts"
1218 (cons
1219 (choice :tag "Context"
1220 (const agenda)
1221 (const org-goto)
1222 (const occur-tree)
1223 (const tags-tree)
1224 (const link-search)
1225 (const mark-goto)
1226 (const bookmark-jump)
1227 (const isearch)
1228 (const default))
1229 (choice :tag "Detail level"
1230 (const minimal)
1231 (const local)
1232 (const ancestors)
1233 (const lineage)
1234 (const tree)
1235 (const canonical))))))
1237 (defcustom org-indirect-buffer-display 'other-window
1238 "How should indirect tree buffers be displayed?
1240 This applies to indirect buffers created with the commands
1241 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1243 Valid values are:
1244 current-window Display in the current window
1245 other-window Just display in another window.
1246 dedicated-frame Create one new frame, and re-use it each time.
1247 new-frame Make a new frame each time. Note that in this case
1248 previously-made indirect buffers are kept, and you need to
1249 kill these buffers yourself."
1250 :group 'org-structure
1251 :group 'org-agenda-windows
1252 :type '(choice
1253 (const :tag "In current window" current-window)
1254 (const :tag "In current frame, other window" other-window)
1255 (const :tag "Each time a new frame" new-frame)
1256 (const :tag "One dedicated frame" dedicated-frame)))
1258 (defcustom org-use-speed-commands nil
1259 "Non-nil means activate single letter commands at beginning of a headline.
1260 This may also be a function to test for appropriate locations where speed
1261 commands should be active.
1263 For example, to activate speed commands when the point is on any
1264 star at the beginning of the headline, you can do this:
1266 (setq org-use-speed-commands
1267 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1268 :group 'org-structure
1269 :type '(choice
1270 (const :tag "Never" nil)
1271 (const :tag "At beginning of headline stars" t)
1272 (function)))
1274 (defcustom org-speed-commands-user nil
1275 "Alist of additional speed commands.
1276 This list will be checked before `org-speed-commands-default'
1277 when the variable `org-use-speed-commands' is non-nil
1278 and when the cursor is at the beginning of a headline.
1279 The car of each entry is a string with a single letter, which must
1280 be assigned to `self-insert-command' in the global map.
1281 The cdr is either a command to be called interactively, a function
1282 to be called, or a form to be evaluated.
1283 An entry that is just a list with a single string will be interpreted
1284 as a descriptive headline that will be added when listing the speed
1285 commands in the Help buffer using the `?' speed command."
1286 :group 'org-structure
1287 :type '(repeat :value ("k" . ignore)
1288 (choice :value ("k" . ignore)
1289 (list :tag "Descriptive Headline" (string :tag "Headline"))
1290 (cons :tag "Letter and Command"
1291 (string :tag "Command letter")
1292 (choice
1293 (function)
1294 (sexp))))))
1296 (defcustom org-bookmark-names-plist
1297 '(:last-capture "org-capture-last-stored"
1298 :last-refile "org-refile-last-stored"
1299 :last-capture-marker "org-capture-last-stored-marker")
1300 "Names for bookmarks automatically set by some Org commands.
1301 This can provide strings as names for a number of bookmarks Org sets
1302 automatically. The following keys are currently implemented:
1303 :last-capture
1304 :last-capture-marker
1305 :last-refile
1306 When a key does not show up in the property list, the corresponding bookmark
1307 is not set."
1308 :group 'org-structure
1309 :type 'plist)
1311 (defgroup org-cycle nil
1312 "Options concerning visibility cycling in Org mode."
1313 :tag "Org Cycle"
1314 :group 'org-structure)
1316 (defcustom org-cycle-skip-children-state-if-no-children t
1317 "Non-nil means skip CHILDREN state in entries that don't have any."
1318 :group 'org-cycle
1319 :type 'boolean)
1321 (defcustom org-cycle-max-level nil
1322 "Maximum level which should still be subject to visibility cycling.
1323 Levels higher than this will, for cycling, be treated as text, not a headline.
1324 When `org-odd-levels-only' is set, a value of N in this variable actually
1325 means 2N-1 stars as the limiting headline.
1326 When nil, cycle all levels.
1327 Note that the limiting level of cycling is also influenced by
1328 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1329 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1330 than its value."
1331 :group 'org-cycle
1332 :type '(choice
1333 (const :tag "No limit" nil)
1334 (integer :tag "Maximum level")))
1336 (defcustom org-hide-block-startup nil
1337 "Non-nil means entering Org mode will fold all blocks.
1338 This can also be set in on a per-file basis with
1340 #+STARTUP: hideblocks
1341 #+STARTUP: showblocks"
1342 :group 'org-startup
1343 :group 'org-cycle
1344 :type 'boolean)
1346 (defcustom org-cycle-global-at-bob nil
1347 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1349 This makes it possible to do global cycling without having to use `S-TAB'
1350 or `\\[universal-argument] TAB'. For this special case to work, the first \
1351 line of the buffer
1352 must not be a headline -- it may be empty or some other text.
1354 When used in this way, `org-cycle-hook' is disabled temporarily to make
1355 sure the cursor stays at the beginning of the buffer.
1357 When this option is nil, don't do anything special at the beginning of
1358 the buffer."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-level-after-item/entry-creation t
1363 "Non-nil means cycle entry level or item indentation in new empty entries.
1365 When the cursor is at the end of an empty headline, i.e., with only stars
1366 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1367 and then all possible ancestor states, before returning to the original state.
1368 This makes data entry extremely fast: M-RET to create a new headline,
1369 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1371 When the cursor is at the end of an empty plain list item, one TAB will
1372 make it a subitem, two or more tabs will back up to make this an item
1373 higher up in the item hierarchy."
1374 :group 'org-cycle
1375 :type 'boolean)
1377 (defcustom org-cycle-emulate-tab t
1378 "Where should `org-cycle' emulate TAB.
1379 nil Never
1380 white Only in completely white lines
1381 whitestart Only at the beginning of lines, before the first non-white char
1382 t Everywhere except in headlines
1383 exc-hl-bol Everywhere except at the start of a headline
1384 If TAB is used in a place where it does not emulate TAB, the current subtree
1385 visibility is cycled."
1386 :group 'org-cycle
1387 :type '(choice (const :tag "Never" nil)
1388 (const :tag "Only in completely white lines" white)
1389 (const :tag "Before first char in a line" whitestart)
1390 (const :tag "Everywhere except in headlines" t)
1391 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1393 (defcustom org-cycle-separator-lines 2
1394 "Number of empty lines needed to keep an empty line between collapsed trees.
1395 If you leave an empty line between the end of a subtree and the following
1396 headline, this empty line is hidden when the subtree is folded.
1397 Org mode will leave (exactly) one empty line visible if the number of
1398 empty lines is equal or larger to the number given in this variable.
1399 So the default 2 means at least 2 empty lines after the end of a subtree
1400 are needed to produce free space between a collapsed subtree and the
1401 following headline.
1403 If the number is negative, and the number of empty lines is at least -N,
1404 all empty lines are shown.
1406 Special case: when 0, never leave empty lines in collapsed view."
1407 :group 'org-cycle
1408 :type 'integer)
1409 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1411 (defcustom org-pre-cycle-hook nil
1412 "Hook that is run before visibility cycling is happening.
1413 The function(s) in this hook must accept a single argument which indicates
1414 the new state that will be set right after running this hook. The
1415 argument is a symbol. Before a global state change, it can have the values
1416 `overview', `content', or `all'. Before a local state change, it can have
1417 the values `folded', `children', or `subtree'."
1418 :group 'org-cycle
1419 :type 'hook)
1421 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1422 org-cycle-hide-drawers
1423 org-cycle-show-empty-lines
1424 org-optimize-window-after-visibility-change)
1425 "Hook that is run after `org-cycle' has changed the buffer visibility.
1426 The function(s) in this hook must accept a single argument which indicates
1427 the new state that was set by the most recent `org-cycle' command. The
1428 argument is a symbol. After a global state change, it can have the values
1429 `overview', `contents', or `all'. After a local state change, it can have
1430 the values `folded', `children', or `subtree'."
1431 :group 'org-cycle
1432 :type 'hook
1433 :version "26.1"
1434 :package-version '(Org . "8.3"))
1436 (defgroup org-edit-structure nil
1437 "Options concerning structure editing in Org mode."
1438 :tag "Org Edit Structure"
1439 :group 'org-structure)
1441 (defcustom org-odd-levels-only nil
1442 "Non-nil means skip even levels and only use odd levels for the outline.
1443 This has the effect that two stars are being added/taken away in
1444 promotion/demotion commands. It also influences how levels are
1445 handled by the exporters.
1446 Changing it requires restart of `font-lock-mode' to become effective
1447 for fontification also in regions already fontified.
1448 You may also set this on a per-file basis by adding one of the following
1449 lines to the buffer:
1451 #+STARTUP: odd
1452 #+STARTUP: oddeven"
1453 :group 'org-edit-structure
1454 :group 'org-appearance
1455 :type 'boolean)
1457 (defcustom org-adapt-indentation t
1458 "Non-nil means adapt indentation to outline node level.
1460 When this variable is set, Org assumes that you write outlines by
1461 indenting text in each node to align with the headline (after the
1462 stars). The following issues are influenced by this variable:
1464 - The indentation is increased by one space in a demotion
1465 command, and decreased by one in a promotion command. However,
1466 in the latter case, if shifting some line in the entry body
1467 would alter document structure (e.g., insert a new headline),
1468 indentation is not changed at all.
1470 - Property drawers and planning information is inserted indented
1471 when this variable is set. When nil, they will not be indented.
1473 - TAB indents a line relative to current level. The lines below
1474 a headline will be indented when this variable is set.
1476 Note that this is all about true indentation, by adding and
1477 removing space characters. See also \"org-indent.el\" which does
1478 level-dependent indentation in a virtual way, i.e. at display
1479 time in Emacs."
1480 :group 'org-edit-structure
1481 :type 'boolean
1482 :safe #'booleanp)
1484 (defcustom org-special-ctrl-a/e nil
1485 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1487 When t, `C-a' will bring back the cursor to the beginning of the
1488 headline text, i.e. after the stars and after a possible TODO
1489 keyword. In an item, this will be the position after bullet and
1490 check-box, if any. When the cursor is already at that position,
1491 another `C-a' will bring it to the beginning of the line.
1493 `C-e' will jump to the end of the headline, ignoring the presence
1494 of tags in the headline. A second `C-e' will then jump to the
1495 true end of the line, after any tags. This also means that, when
1496 this variable is non-nil, `C-e' also will never jump beyond the
1497 end of the heading of a folded section, i.e. not after the
1498 ellipses.
1500 When set to the symbol `reversed', the first `C-a' or `C-e' works
1501 normally, going to the true line boundary first. Only a directly
1502 following, identical keypress will bring the cursor to the
1503 special positions.
1505 This may also be a cons cell where the behavior for `C-a' and
1506 `C-e' is set separately."
1507 :group 'org-edit-structure
1508 :type '(choice
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet and before tags first" t)
1511 (const :tag "reversed: true line boundary first" reversed)
1512 (cons :tag "Set C-a and C-e separately"
1513 (choice :tag "Special C-a"
1514 (const :tag "off" nil)
1515 (const :tag "on: after stars/bullet first" t)
1516 (const :tag "reversed: before stars/bullet first" reversed))
1517 (choice :tag "Special C-e"
1518 (const :tag "off" nil)
1519 (const :tag "on: before tags first" t)
1520 (const :tag "reversed: after tags first" reversed)))))
1521 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1523 (defcustom org-special-ctrl-k nil
1524 "Non-nil means `C-k' will behave specially in headlines.
1525 When nil, `C-k' will call the default `kill-line' command.
1526 When t, the following will happen while the cursor is in the headline:
1528 - When the cursor is at the beginning of a headline, kill the entire
1529 line and possible the folded subtree below the line.
1530 - When in the middle of the headline text, kill the headline up to the tags.
1531 - When after the headline text, kill the tags."
1532 :group 'org-edit-structure
1533 :type 'boolean)
1535 (defcustom org-ctrl-k-protect-subtree nil
1536 "Non-nil means, do not delete a hidden subtree with C-k.
1537 When set to the symbol `error', simply throw an error when C-k is
1538 used to kill (part-of) a headline that has hidden text behind it.
1539 Any other non-nil value will result in a query to the user, if it is
1540 OK to kill that hidden subtree. When nil, kill without remorse."
1541 :group 'org-edit-structure
1542 :version "24.1"
1543 :type '(choice
1544 (const :tag "Do not protect hidden subtrees" nil)
1545 (const :tag "Protect hidden subtrees with a security query" t)
1546 (const :tag "Never kill a hidden subtree with C-k" error)))
1548 (defcustom org-special-ctrl-o t
1549 "Non-nil means, make `C-o' insert a row in tables."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-catch-invisible-edits nil
1554 "Check if in invisible region before inserting or deleting a character.
1555 Valid values are:
1557 nil Do not check, so just do invisible edits.
1558 error Throw an error and do nothing.
1559 show Make point visible, and do the requested edit.
1560 show-and-error Make point visible, then throw an error and abort the edit.
1561 smart Make point visible, and do insertion/deletion if it is
1562 adjacent to visible text and the change feels predictable.
1563 Never delete a previously invisible character or add in the
1564 middle or right after an invisible region. Basically, this
1565 allows insertion and backward-delete right before ellipses.
1566 FIXME: maybe in this case we should not even show?"
1567 :group 'org-edit-structure
1568 :version "24.1"
1569 :type '(choice
1570 (const :tag "Do not check" nil)
1571 (const :tag "Throw error when trying to edit" error)
1572 (const :tag "Unhide, but do not do the edit" show-and-error)
1573 (const :tag "Show invisible part and do the edit" show)
1574 (const :tag "Be smart and do the right thing" smart)))
1576 (defcustom org-yank-folded-subtrees t
1577 "Non-nil means when yanking subtrees, fold them.
1578 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1579 it starts with a heading and all other headings in it are either children
1580 or siblings, then fold all the subtrees. However, do this only if no
1581 text after the yank would be swallowed into a folded tree by this action."
1582 :group 'org-edit-structure
1583 :type 'boolean)
1585 (defcustom org-yank-adjusted-subtrees nil
1586 "Non-nil means when yanking subtrees, adjust the level.
1587 With this setting, `org-paste-subtree' is used to insert the subtree, see
1588 this function for details."
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defcustom org-M-RET-may-split-line '((default . t))
1593 "Non-nil means M-RET will split the line at the cursor position.
1594 When nil, it will go to the end of the line before making a
1595 new line.
1596 You may also set this option in a different way for different
1597 contexts. Valid contexts are:
1599 headline when creating a new headline
1600 item when creating a new item
1601 table in a table field
1602 default the value to be used for all contexts not explicitly
1603 customized"
1604 :group 'org-structure
1605 :group 'org-table
1606 :type '(choice
1607 (const :tag "Always" t)
1608 (const :tag "Never" nil)
1609 (repeat :greedy t :tag "Individual contexts"
1610 (cons
1611 (choice :tag "Context"
1612 (const headline)
1613 (const item)
1614 (const table)
1615 (const default))
1616 (boolean)))))
1619 (defcustom org-insert-heading-respect-content nil
1620 "Non-nil means insert new headings after the current subtree.
1621 \\<org-mode-map>
1622 When nil, the new heading is created directly after the current line.
1623 The commands `\\[org-insert-heading-respect-content]' and \
1624 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1625 for the duration of the command."
1626 :group 'org-structure
1627 :type 'boolean)
1629 (defcustom org-blank-before-new-entry '((heading . auto)
1630 (plain-list-item . auto))
1631 "Should `org-insert-heading' leave a blank line before new heading/item?
1632 The value is an alist, with `heading' and `plain-list-item' as CAR,
1633 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1634 which case Org will look at the surrounding headings/items and try to
1635 make an intelligent decision whether to insert a blank line or not."
1636 :group 'org-edit-structure
1637 :type '(list
1638 (cons (const heading)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))
1642 (cons (const plain-list-item)
1643 (choice (const :tag "Never" nil)
1644 (const :tag "Always" t)
1645 (const :tag "Auto" auto)))))
1647 (defcustom org-insert-heading-hook nil
1648 "Hook being run after inserting a new heading."
1649 :group 'org-edit-structure
1650 :type 'hook)
1652 (defcustom org-enable-fixed-width-editor t
1653 "Non-nil means lines starting with \":\" are treated as fixed-width.
1654 This currently only means they are never auto-wrapped.
1655 When nil, such lines will be treated like ordinary lines."
1656 :group 'org-edit-structure
1657 :type 'boolean)
1659 (defgroup org-sparse-trees nil
1660 "Options concerning sparse trees in Org mode."
1661 :tag "Org Sparse Trees"
1662 :group 'org-structure)
1664 (defcustom org-highlight-sparse-tree-matches t
1665 "Non-nil means highlight all matches that define a sparse tree.
1666 The highlights will automatically disappear the next time the buffer is
1667 changed by an edit command."
1668 :group 'org-sparse-trees
1669 :type 'boolean)
1671 (defcustom org-remove-highlights-with-change t
1672 "Non-nil means any change to the buffer will remove temporary highlights.
1673 \\<org-mode-map>\
1674 Such highlights are created by `org-occur' and `org-clock-display'.
1675 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1676 to get rid of the highlights.
1677 The highlights created by `org-toggle-latex-fragment' always need
1678 `\\[org-toggle-latex-fragment]' to be removed."
1679 :group 'org-sparse-trees
1680 :group 'org-time
1681 :type 'boolean)
1683 (defcustom org-occur-case-fold-search t
1684 "Non-nil means `org-occur' should be case-insensitive.
1685 If set to `smart' the search will be case-insensitive only if it
1686 doesn't specify any upper case character."
1687 :group 'org-sparse-trees
1688 :version "26.1"
1689 :type '(choice
1690 (const :tag "Case-sensitive" nil)
1691 (const :tag "Case-insensitive" t)
1692 (const :tag "Case-insensitive for lower case searches only" smart)))
1694 (defcustom org-occur-hook '(org-first-headline-recenter)
1695 "Hook that is run after `org-occur' has constructed a sparse tree.
1696 This can be used to recenter the window to show as much of the structure
1697 as possible."
1698 :group 'org-sparse-trees
1699 :type 'hook)
1701 (defgroup org-table nil
1702 "Options concerning tables in Org mode."
1703 :tag "Org Table"
1704 :group 'org)
1706 (defcustom org-self-insert-cluster-for-undo nil
1707 "Non-nil means cluster self-insert commands for undo when possible.
1708 If this is set, then, like in the Emacs command loop, 20 consecutive
1709 characters will be undone together.
1710 This is configurable, because there is some impact on typing performance."
1711 :group 'org-table
1712 :type 'boolean)
1714 (defcustom org-table-tab-recognizes-table.el t
1715 "Non-nil means TAB will automatically notice a table.el table.
1716 When it sees such a table, it moves point into it and - if necessary -
1717 calls `table-recognize-table'."
1718 :group 'org-table-editing
1719 :type 'boolean)
1721 (defgroup org-link nil
1722 "Options concerning links in Org mode."
1723 :tag "Org Link"
1724 :group 'org)
1726 (defvar-local org-link-abbrev-alist-local nil
1727 "Buffer-local version of `org-link-abbrev-alist', which see.
1728 The value of this is taken from the #+LINK lines.")
1730 (defcustom org-link-parameters
1731 '(("doi" :follow org--open-doi-link)
1732 ("elisp" :follow org--open-elisp-link)
1733 ("file" :complete org-file-complete-link)
1734 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1735 ("help" :follow org--open-help-link)
1736 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1737 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1738 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1739 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1740 ("shell" :follow org--open-shell-link))
1741 "An alist of properties that defines all the links in Org mode.
1742 The key in each association is a string of the link type.
1743 Subsequent optional elements make up a p-list of link properties.
1745 :follow - A function that takes the link path as an argument.
1747 :export - A function that takes the link path, description and
1748 export-backend as arguments.
1750 :store - A function responsible for storing the link. See the
1751 function `org-store-link-functions'.
1753 :complete - A function that inserts a link with completion. The
1754 function takes one optional prefix arg.
1756 :face - A face for the link, or a function that returns a face.
1757 The function takes one argument which is the link path. The
1758 default face is `org-link'.
1760 :mouse-face - The mouse-face. The default is `highlight'.
1762 :display - `full' will not fold the link in descriptive
1763 display. Default is `org-link'.
1765 :help-echo - A string or function that takes (window object position)
1766 as arguments and returns a string.
1768 :keymap - A keymap that is active on the link. The default is
1769 `org-mouse-map'.
1771 :htmlize-link - A function for the htmlize-link. Defaults
1772 to (list :uri \"type:path\")
1774 :activate-func - A function to run at the end of font-lock
1775 activation. The function must accept (link-start link-end path bracketp)
1776 as arguments."
1777 :group 'org-link
1778 :type '(alist :tag "Link display parameters"
1779 :value-type plist)
1780 :version "26.1"
1781 :package-version '(Org . "9.1"))
1783 (defun org-link-get-parameter (type key)
1784 "Get TYPE link property for KEY.
1785 TYPE is a string and KEY is a plist keyword."
1786 (plist-get
1787 (cdr (assoc type org-link-parameters))
1788 key))
1790 (defun org-link-set-parameters (type &rest parameters)
1791 "Set link TYPE properties to PARAMETERS.
1792 PARAMETERS should be :key val pairs."
1793 (let ((data (assoc type org-link-parameters)))
1794 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1795 (push (cons type parameters) org-link-parameters)
1796 (org-make-link-regexps)
1797 (org-element-update-syntax))))
1799 (defun org-link-types ()
1800 "Return a list of known link types."
1801 (mapcar #'car org-link-parameters))
1803 (defcustom org-link-abbrev-alist nil
1804 "Alist of link abbreviations.
1805 The car of each element is a string, to be replaced at the start of a link.
1806 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1807 links in Org buffers can have an optional tag after a double colon, e.g.,
1809 [[linkkey:tag][description]]
1811 The `linkkey' must be a single word, starting with a letter, followed
1812 by letters, numbers, `-' or `_'.
1814 If REPLACE is a string, the tag will simply be appended to create the link.
1815 If the string contains \"%s\", the tag will be inserted there. If the string
1816 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1817 at that point (see the function `url-hexify-string'). If the string contains
1818 the specifier \"%(my-function)\", then the custom function `my-function' will
1819 be invoked: this function takes the tag as its only argument and must return
1820 a string.
1822 REPLACE may also be a function that will be called with the tag as the
1823 only argument to create the link, which should be returned as a string.
1825 See the manual for examples."
1826 :group 'org-link
1827 :type '(repeat
1828 (cons
1829 (string :tag "Protocol")
1830 (choice
1831 (string :tag "Format")
1832 (function)))))
1834 (defcustom org-descriptive-links t
1835 "Non-nil means Org will display descriptive links.
1836 E.g. [[http://orgmode.org][Org website]] will be displayed as
1837 \"Org Website\", hiding the link itself and just displaying its
1838 description. When set to nil, Org will display the full links
1839 literally.
1841 You can interactively set the value of this variable by calling
1842 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1843 :group 'org-link
1844 :type 'boolean)
1846 (defcustom org-link-file-path-type 'adaptive
1847 "How the path name in file links should be stored.
1848 Valid values are:
1850 relative Relative to the current directory, i.e. the directory of the file
1851 into which the link is being inserted.
1852 absolute Absolute path, if possible with ~ for home directory.
1853 noabbrev Absolute path, no abbreviation of home directory.
1854 adaptive Use relative path for files in the current directory and sub-
1855 directories of it. For other files, use an absolute path."
1856 :group 'org-link
1857 :type '(choice
1858 (const relative)
1859 (const absolute)
1860 (const noabbrev)
1861 (const adaptive)))
1863 (defvaralias 'org-activate-links 'org-highlight-links)
1864 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1865 "Types of links that should be highlighted in Org files.
1867 This is a list of symbols, each one of them leading to the
1868 highlighting of a certain link type.
1870 You can still open links that are not highlighted.
1872 In principle, it does not hurt to turn on highlighting for all
1873 link types. There may be a small gain when turning off unused
1874 link types. The types are:
1876 bracket The recommended [[link][description]] or [[link]] links with hiding.
1877 angle Links in angular brackets that may contain whitespace like
1878 <bbdb:Carsten Dominik>.
1879 plain Plain links in normal text, no whitespace, like http://google.com.
1880 radio Text that is matched by a radio target, see manual for details.
1881 tag Tag settings in a headline (link to tag search).
1882 date Time stamps (link to calendar).
1883 footnote Footnote labels.
1885 If you set this variable during an Emacs session, use `org-mode-restart'
1886 in the Org buffer so that the change takes effect."
1887 :group 'org-link
1888 :group 'org-appearance
1889 :type '(set :greedy t
1890 (const :tag "Double bracket links" bracket)
1891 (const :tag "Angular bracket links" angle)
1892 (const :tag "Plain text links" plain)
1893 (const :tag "Radio target matches" radio)
1894 (const :tag "Tags" tag)
1895 (const :tag "Timestamps" date)
1896 (const :tag "Footnotes" footnote)))
1898 (defcustom org-make-link-description-function nil
1899 "Function to use for generating link descriptions from links.
1900 This function must take two parameters: the first one is the
1901 link, the second one is the description generated by
1902 `org-insert-link'. The function should return the description to
1903 use."
1904 :group 'org-link
1905 :type '(choice (const nil) (function)))
1907 (defgroup org-link-store nil
1908 "Options concerning storing links in Org mode."
1909 :tag "Org Store Link"
1910 :group 'org-link)
1912 (defcustom org-url-hexify-p t
1913 "When non-nil, hexify URL when creating a link."
1914 :type 'boolean
1915 :version "24.3"
1916 :group 'org-link-store)
1918 (defcustom org-email-link-description-format "Email %c: %.30s"
1919 "Format of the description part of a link to an email or usenet message.
1920 The following %-escapes will be replaced by corresponding information:
1922 %F full \"From\" field
1923 %f name, taken from \"From\" field, address if no name
1924 %T full \"To\" field
1925 %t first name in \"To\" field, address if no name
1926 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1927 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1928 %s subject
1929 %d date
1930 %m message-id.
1932 You may use normal field width specification between the % and the letter.
1933 This is for example useful to limit the length of the subject.
1935 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1936 :group 'org-link-store
1937 :type 'string)
1939 (defcustom org-from-is-user-regexp
1940 (let (r1 r2)
1941 (when (and user-mail-address (not (string= user-mail-address "")))
1942 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1943 (when (and user-full-name (not (string= user-full-name "")))
1944 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1945 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1946 "Regexp matched against the \"From:\" header of an email or usenet message.
1947 It should match if the message is from the user him/herself."
1948 :group 'org-link-store
1949 :type 'regexp)
1951 (defcustom org-context-in-file-links t
1952 "Non-nil means file links from `org-store-link' contain context.
1953 \\<org-mode-map>
1954 A search string will be added to the file name with :: as separator
1955 and used to find the context when the link is activated by the command
1956 `org-open-at-point'. When this option is t, the entire active region
1957 will be placed in the search string of the file link. If set to a
1958 positive integer, only the first n lines of context will be stored.
1960 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1961 \\[org-store-link]')
1962 negates this setting for the duration of the command."
1963 :group 'org-link-store
1964 :type '(choice boolean integer))
1966 (defcustom org-keep-stored-link-after-insertion nil
1967 "Non-nil means keep link in list for entire session.
1968 \\<org-mode-map>
1969 The command `org-store-link' adds a link pointing to the current
1970 location to an internal list. These links accumulate during a session.
1971 The command `org-insert-link' can be used to insert links into any
1972 Org file (offering completion for all stored links).
1974 When this option is nil, every link which has been inserted once using
1975 `\\[org-insert-link]' will be removed from the list, to make completing the \
1976 unused
1977 links more efficient."
1978 :group 'org-link-store
1979 :type 'boolean)
1981 (defgroup org-link-follow nil
1982 "Options concerning following links in Org mode."
1983 :tag "Org Follow Link"
1984 :group 'org-link)
1986 (defcustom org-link-translation-function nil
1987 "Function to translate links with different syntax to Org syntax.
1988 This can be used to translate links created for example by the Planner
1989 or emacs-wiki packages to Org syntax.
1990 The function must accept two parameters, a TYPE containing the link
1991 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1992 which is everything after the link protocol. It should return a cons
1993 with possibly modified values of type and path.
1994 Org contains a function for this, so if you set this variable to
1995 `org-translate-link-from-planner', you should be able follow many
1996 links created by planner."
1997 :group 'org-link-follow
1998 :type '(choice (const nil) (function)))
2000 (defcustom org-follow-link-hook nil
2001 "Hook that is run after a link has been followed."
2002 :group 'org-link-follow
2003 :type 'hook)
2005 (defcustom org-tab-follows-link nil
2006 "Non-nil means on links TAB will follow the link.
2007 Needs to be set before org.el is loaded.
2008 This really should not be used, it does not make sense, and the
2009 implementation is bad."
2010 :group 'org-link-follow
2011 :type 'boolean)
2013 (defcustom org-return-follows-link nil
2014 "Non-nil means on links RET will follow the link.
2015 In tables, the special behavior of RET has precedence."
2016 :group 'org-link-follow
2017 :type 'boolean)
2019 (defcustom org-mouse-1-follows-link
2020 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2021 "Non-nil means mouse-1 on a link will follow the link.
2022 A longer mouse click will still set point. Needs to be set
2023 before org.el is loaded."
2024 :group 'org-link-follow
2025 :version "26.1"
2026 :package-version '(Org . "8.3")
2027 :type '(choice
2028 (const :tag "A double click follows the link" double)
2029 (const :tag "Unconditionally follow the link with mouse-1" t)
2030 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2032 (defcustom org-mark-ring-length 4
2033 "Number of different positions to be recorded in the ring.
2034 Changing this requires a restart of Emacs to work correctly."
2035 :group 'org-link-follow
2036 :type 'integer)
2038 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2039 "Non-nil means internal fuzzy links can only match headlines.
2041 When nil, the a fuzzy link may point to a target or a named
2042 construct in the document. When set to the special value
2043 `query-to-create', offer to create a new headline when none
2044 matched.
2046 Spaces and statistics cookies are ignored during heading searches."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type '(choice
2050 (const :tag "Use fuzzy text search" nil)
2051 (const :tag "Match only exact headline" t)
2052 (const :tag "Match exact headline or query to create it"
2053 query-to-create))
2054 :safe #'symbolp)
2056 (defcustom org-link-frame-setup
2057 '((vm . vm-visit-folder-other-frame)
2058 (vm-imap . vm-visit-imap-folder-other-frame)
2059 (gnus . org-gnus-no-new-news)
2060 (file . find-file-other-window)
2061 (wl . wl-other-frame))
2062 "Setup the frame configuration for following links.
2063 When following a link with Emacs, it may often be useful to display
2064 this link in another window or frame. This variable can be used to
2065 set this up for the different types of links.
2066 For VM, use any of
2067 `vm-visit-folder'
2068 `vm-visit-folder-other-window'
2069 `vm-visit-folder-other-frame'
2070 For Gnus, use any of
2071 `gnus'
2072 `gnus-other-frame'
2073 `org-gnus-no-new-news'
2074 For FILE, use any of
2075 `find-file'
2076 `find-file-other-window'
2077 `find-file-other-frame'
2078 For Wanderlust use any of
2079 `wl'
2080 `wl-other-frame'
2081 For the calendar, use the variable `calendar-setup'.
2082 For BBDB, it is currently only possible to display the matches in
2083 another window."
2084 :group 'org-link-follow
2085 :type '(list
2086 (cons (const vm)
2087 (choice
2088 (const vm-visit-folder)
2089 (const vm-visit-folder-other-window)
2090 (const vm-visit-folder-other-frame)))
2091 (cons (const vm-imap)
2092 (choice
2093 (const vm-visit-imap-folder)
2094 (const vm-visit-imap-folder-other-window)
2095 (const vm-visit-imap-folder-other-frame)))
2096 (cons (const gnus)
2097 (choice
2098 (const gnus)
2099 (const gnus-other-frame)
2100 (const org-gnus-no-new-news)))
2101 (cons (const file)
2102 (choice
2103 (const find-file)
2104 (const find-file-other-window)
2105 (const find-file-other-frame)))
2106 (cons (const wl)
2107 (choice
2108 (const wl)
2109 (const wl-other-frame)))))
2111 (defcustom org-display-internal-link-with-indirect-buffer nil
2112 "Non-nil means use indirect buffer to display infile links.
2113 Activating internal links (from one location in a file to another location
2114 in the same file) normally just jumps to the location. When the link is
2115 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2116 is displayed in
2117 another window. When this option is set, the other window actually displays
2118 an indirect buffer clone of the current buffer, to avoid any visibility
2119 changes to the current buffer."
2120 :group 'org-link-follow
2121 :type 'boolean)
2123 (defcustom org-open-non-existing-files nil
2124 "Non-nil means `org-open-file' will open non-existing files.
2125 When nil, an error will be generated.
2126 This variable applies only to external applications because they
2127 might choke on non-existing files. If the link is to a file that
2128 will be opened in Emacs, the variable is ignored."
2129 :group 'org-link-follow
2130 :type 'boolean)
2132 (defcustom org-open-directory-means-index-dot-org nil
2133 "Non-nil means a link to a directory really means to index.org.
2134 When nil, following a directory link will run dired or open a finder/explorer
2135 window on that directory."
2136 :group 'org-link-follow
2137 :type 'boolean)
2139 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2140 "Non-nil means ask for confirmation before executing shell links.
2141 Shell links can be dangerous: just think about a link
2143 [[shell:rm -rf ~/*][Google Search]]
2145 This link would show up in your Org document as \"Google Search\",
2146 but really it would remove your entire home directory.
2147 Therefore we advise against setting this variable to nil.
2148 Just change it to `y-or-n-p' if you want to confirm with a
2149 single keystroke rather than having to type \"yes\"."
2150 :group 'org-link-follow
2151 :type '(choice
2152 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2153 (const :tag "with y-or-n (faster)" y-or-n-p)
2154 (const :tag "no confirmation (dangerous)" nil)))
2155 (put 'org-confirm-shell-link-function
2156 'safe-local-variable
2157 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2159 (defcustom org-confirm-shell-link-not-regexp ""
2160 "A regexp to skip confirmation for shell links."
2161 :group 'org-link-follow
2162 :version "24.1"
2163 :type 'regexp)
2165 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2166 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2167 Elisp links can be dangerous: just think about a link
2169 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2171 This link would show up in your Org document as \"Google Search\",
2172 but really it would remove your entire home directory.
2173 Therefore we advise against setting this variable to nil.
2174 Just change it to `y-or-n-p' if you want to confirm with a
2175 single keystroke rather than having to type \"yes\"."
2176 :group 'org-link-follow
2177 :type '(choice
2178 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2179 (const :tag "with y-or-n (faster)" y-or-n-p)
2180 (const :tag "no confirmation (dangerous)" nil)))
2181 (put 'org-confirm-shell-link-function
2182 'safe-local-variable
2183 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2185 (defcustom org-confirm-elisp-link-not-regexp ""
2186 "A regexp to skip confirmation for Elisp links."
2187 :group 'org-link-follow
2188 :version "24.1"
2189 :type 'regexp)
2191 (defconst org-file-apps-defaults-gnu
2192 '((remote . emacs)
2193 (system . mailcap)
2194 (t . mailcap))
2195 "Default file applications on a UNIX or GNU/Linux system.
2196 See `org-file-apps'.")
2198 (defconst org-file-apps-defaults-macosx
2199 '((remote . emacs)
2200 (system . "open %s")
2201 ("ps.gz" . "gv %s")
2202 ("eps.gz" . "gv %s")
2203 ("dvi" . "xdvi %s")
2204 ("fig" . "xfig %s")
2205 (t . "open %s"))
2206 "Default file applications on a macOS system.
2207 The system \"open\" is known as a default, but we use X11 applications
2208 for some files for which the OS does not have a good default.
2209 See `org-file-apps'.")
2211 (defconst org-file-apps-defaults-windowsnt
2212 (list '(remote . emacs)
2213 (cons 'system (lambda (file _path)
2214 (with-no-warnings (w32-shell-execute "open" file))))
2215 (cons t (lambda (file _path)
2216 (with-no-warnings (w32-shell-execute "open" file)))))
2217 "Default file applications on a Windows NT system.
2218 The system \"open\" is used for most files.
2219 See `org-file-apps'.")
2221 (defcustom org-file-apps
2222 '((auto-mode . emacs)
2223 ("\\.mm\\'" . default)
2224 ("\\.x?html?\\'" . default)
2225 ("\\.pdf\\'" . default))
2226 "External applications for opening `file:path' items in a document.
2227 \\<org-mode-map>\
2229 Org mode uses system defaults for different file types, but
2230 you can use this variable to set the application for a given file
2231 extension. The entries in this list are cons cells where the car identifies
2232 files and the cdr the corresponding command.
2234 Possible values for the file identifier are:
2236 \"string\" A string as a file identifier can be interpreted in different
2237 ways, depending on its contents:
2239 - Alphanumeric characters only:
2240 Match links with this file extension.
2241 Example: (\"pdf\" . \"evince %s\")
2242 to open PDFs with evince.
2244 - Regular expression: Match links where the
2245 filename matches the regexp. If you want to
2246 use groups here, use shy groups.
2248 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2249 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2250 to open *.html and *.xhtml with firefox.
2252 - Regular expression which contains (non-shy) groups:
2253 Match links where the whole link, including \"::\", and
2254 anything after that, matches the regexp.
2255 In a custom command string, %1, %2, etc. are replaced with
2256 the parts of the link that were matched by the groups.
2257 For backwards compatibility, if a command string is given
2258 that does not use any of the group matches, this case is
2259 handled identically to the second one (i.e. match against
2260 file name only).
2261 In a custom function, you can access the group matches with
2262 (match-string n link).
2264 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2265 \"evince -p %1 %s\")
2266 to open [[file:document.pdf::5]] with evince at page 5.
2268 `directory' Matches a directory
2269 `remote' Matches a remote file, accessible through tramp or efs.
2270 Remote files most likely should be visited through Emacs
2271 because external applications cannot handle such paths.
2272 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2273 so all files Emacs knows how to handle. Using this with
2274 command `emacs' will open most files in Emacs. Beware that this
2275 will also open html files inside Emacs, unless you add
2276 (\"html\" . default) to the list as well.
2277 `system' The system command to open files, like `open' on Windows
2278 and macOS, and mailcap under GNU/Linux. This is the command
2279 that will be selected if you call `org-open-at-point' with a
2280 double prefix argument (`\\[universal-argument] \
2281 \\[universal-argument] \\[org-open-at-point]').
2282 t Default for files not matched by any of the other options.
2284 Possible values for the command are:
2286 `emacs' The file will be visited by the current Emacs process.
2287 `default' Use the default application for this file type, which is the
2288 association for t in the list, most likely in the system-specific
2289 part. This can be used to overrule an unwanted setting in the
2290 system-specific variable.
2291 `system' Use the system command for opening files, like \"open\".
2292 This command is specified by the entry whose car is `system'.
2293 Most likely, the system-specific version of this variable
2294 does define this command, but you can overrule/replace it
2295 here.
2296 `mailcap' Use command specified in the mailcaps.
2297 string A command to be executed by a shell; %s will be replaced
2298 by the path to the file.
2299 function A Lisp function, which will be called with two arguments:
2300 the file path and the original link string, without the
2301 \"file:\" prefix.
2303 For more examples, see the system specific constants
2304 `org-file-apps-defaults-macosx'
2305 `org-file-apps-defaults-windowsnt'
2306 `org-file-apps-defaults-gnu'."
2307 :group 'org-link-follow
2308 :type '(repeat
2309 (cons (choice :value ""
2310 (string :tag "Extension")
2311 (const :tag "System command to open files" system)
2312 (const :tag "Default for unrecognized files" t)
2313 (const :tag "Remote file" remote)
2314 (const :tag "Links to a directory" directory)
2315 (const :tag "Any files that have Emacs modes"
2316 auto-mode))
2317 (choice :value ""
2318 (const :tag "Visit with Emacs" emacs)
2319 (const :tag "Use default" default)
2320 (const :tag "Use the system command" system)
2321 (string :tag "Command")
2322 (function :tag "Function")))))
2324 (defcustom org-doi-server-url "http://dx.doi.org/"
2325 "The URL of the DOI server."
2326 :type 'string
2327 :version "24.3"
2328 :group 'org-link-follow)
2330 (defgroup org-refile nil
2331 "Options concerning refiling entries in Org mode."
2332 :tag "Org Refile"
2333 :group 'org)
2335 (defcustom org-directory "~/org"
2336 "Directory with Org files.
2337 This is just a default location to look for Org files. There is no need
2338 at all to put your files into this directory. It is used in the
2339 following situations:
2341 1. When a capture template specifies a target file that is not an
2342 absolute path. The path will then be interpreted relative to
2343 `org-directory'
2344 2. When the value of variable `org-agenda-files' is a single file, any
2345 relative paths in this file will be taken as relative to
2346 `org-directory'."
2347 :group 'org-refile
2348 :group 'org-capture
2349 :type 'directory)
2351 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2352 "Default target for storing notes.
2353 Used as a fall back file for org-capture.el, for templates that
2354 do not specify a target file."
2355 :group 'org-refile
2356 :group 'org-capture
2357 :type 'file)
2359 (defcustom org-reverse-note-order nil
2360 "Non-nil means store new notes at the beginning of a file or entry.
2361 When nil, new notes will be filed to the end of a file or entry.
2362 This can also be a list with cons cells of regular expressions that
2363 are matched against file names, and values."
2364 :group 'org-capture
2365 :group 'org-refile
2366 :type '(choice
2367 (const :tag "Reverse always" t)
2368 (const :tag "Reverse never" nil)
2369 (repeat :tag "By file name regexp"
2370 (cons regexp boolean))))
2372 (defcustom org-log-refile nil
2373 "Information to record when a task is refiled.
2375 Possible values are:
2377 nil Don't add anything
2378 time Add a time stamp to the task
2379 note Prompt for a note and add it with template `org-log-note-headings'
2381 This option can also be set with on a per-file-basis with
2383 #+STARTUP: nologrefile
2384 #+STARTUP: logrefile
2385 #+STARTUP: lognoterefile
2387 You can have local logging settings for a subtree by setting the LOGGING
2388 property to one or more of these keywords.
2390 When bulk-refiling from the agenda, the value `note' is forbidden and
2391 will temporarily be changed to `time'."
2392 :group 'org-refile
2393 :group 'org-progress
2394 :version "24.1"
2395 :type '(choice
2396 (const :tag "No logging" nil)
2397 (const :tag "Record timestamp" time)
2398 (const :tag "Record timestamp with note." note)))
2400 (defcustom org-refile-targets nil
2401 "Targets for refiling entries with `\\[org-refile]'.
2402 This is a list of cons cells. Each cell contains:
2403 - a specification of the files to be considered, either a list of files,
2404 or a symbol whose function or variable value will be used to retrieve
2405 a file name or a list of file names. If you use `org-agenda-files' for
2406 that, all agenda files will be scanned for targets. Nil means consider
2407 headings in the current buffer.
2408 - A specification of how to find candidate refile targets. This may be
2409 any of:
2410 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2411 This tag has to be present in all target headlines, inheritance will
2412 not be considered.
2413 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2414 todo keyword.
2415 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2416 headlines that are refiling targets.
2417 - a cons cell (:level . N). Any headline of level N is considered a target.
2418 Note that, when `org-odd-levels-only' is set, level corresponds to
2419 order in hierarchy, not to the number of stars.
2420 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2421 Note that, when `org-odd-levels-only' is set, level corresponds to
2422 order in hierarchy, not to the number of stars.
2424 Each element of this list generates a set of possible targets.
2425 The union of these sets is presented (with completion) to
2426 the user by `org-refile'.
2428 You can set the variable `org-refile-target-verify-function' to a function
2429 to verify each headline found by the simple criteria above.
2431 When this variable is nil, all top-level headlines in the current buffer
2432 are used, equivalent to the value `((nil . (:level . 1))'."
2433 :group 'org-refile
2434 :type '(repeat
2435 (cons
2436 (choice :value org-agenda-files
2437 (const :tag "All agenda files" org-agenda-files)
2438 (const :tag "Current buffer" nil)
2439 (function) (variable) (file))
2440 (choice :tag "Identify target headline by"
2441 (cons :tag "Specific tag" (const :value :tag) (string))
2442 (cons :tag "TODO keyword" (const :value :todo) (string))
2443 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2444 (cons :tag "Level number" (const :value :level) (integer))
2445 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2447 (defcustom org-refile-target-verify-function nil
2448 "Function to verify if the headline at point should be a refile target.
2449 The function will be called without arguments, with point at the
2450 beginning of the headline. It should return t and leave point
2451 where it is if the headline is a valid target for refiling.
2453 If the target should not be selected, the function must return nil.
2454 In addition to this, it may move point to a place from where the search
2455 should be continued. For example, the function may decide that the entire
2456 subtree of the current entry should be excluded and move point to the end
2457 of the subtree."
2458 :group 'org-refile
2459 :type '(choice
2460 (const nil)
2461 (function)))
2463 (defcustom org-refile-use-cache nil
2464 "Non-nil means cache refile targets to speed up the process.
2465 \\<org-mode-map>\
2466 The cache for a particular file will be updated automatically when
2467 the buffer has been killed, or when any of the marker used for flagging
2468 refile targets no longer points at a live buffer.
2469 If you have added new entries to a buffer that might themselves be targets,
2470 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2471 if you find that easier, \
2472 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2473 \\[org-refile]'."
2474 :group 'org-refile
2475 :version "24.1"
2476 :type 'boolean)
2478 (defcustom org-refile-use-outline-path nil
2479 "Non-nil means provide refile targets as paths.
2480 So a level 3 headline will be available as level1/level2/level3.
2482 When the value is `file', also include the file name (without directory)
2483 into the path. In this case, you can also stop the completion after
2484 the file name, to get entries inserted as top level in the file.
2486 When `full-file-path', include the full file path.
2488 When `buffer-name', use the buffer name."
2489 :group 'org-refile
2490 :type '(choice
2491 (const :tag "Not" nil)
2492 (const :tag "Yes" t)
2493 (const :tag "Start with file name" file)
2494 (const :tag "Start with full file path" full-file-path)
2495 (const :tag "Start with buffer name" buffer-name)))
2497 (defcustom org-outline-path-complete-in-steps t
2498 "Non-nil means complete the outline path in hierarchical steps.
2499 When Org uses the refile interface to select an outline path (see
2500 `org-refile-use-outline-path'), the completion of the path can be
2501 done in a single go, or it can be done in steps down the headline
2502 hierarchy. Going in steps is probably the best if you do not use
2503 a special completion package like `ido' or `icicles'. However,
2504 when using these packages, going in one step can be very fast,
2505 while still showing the whole path to the entry."
2506 :group 'org-refile
2507 :type 'boolean)
2509 (defcustom org-refile-allow-creating-parent-nodes nil
2510 "Non-nil means allow the creation of new nodes as refile targets.
2511 New nodes are then created by adding \"/new node name\" to the completion
2512 of an existing node. When the value of this variable is `confirm',
2513 new node creation must be confirmed by the user (recommended).
2514 When nil, the completion must match an existing entry.
2516 Note that, if the new heading is not seen by the criteria
2517 listed in `org-refile-targets', multiple instances of the same
2518 heading would be created by trying again to file under the new
2519 heading."
2520 :group 'org-refile
2521 :type '(choice
2522 (const :tag "Never" nil)
2523 (const :tag "Always" t)
2524 (const :tag "Prompt for confirmation" confirm)))
2526 (defcustom org-refile-active-region-within-subtree nil
2527 "Non-nil means also refile active region within a subtree.
2529 By default `org-refile' doesn't allow refiling regions if they
2530 don't contain a set of subtrees, but it might be convenient to
2531 do so sometimes: in that case, the first line of the region is
2532 converted to a headline before refiling."
2533 :group 'org-refile
2534 :version "24.1"
2535 :type 'boolean)
2537 (defgroup org-todo nil
2538 "Options concerning TODO items in Org mode."
2539 :tag "Org TODO"
2540 :group 'org)
2542 (defgroup org-progress nil
2543 "Options concerning Progress logging in Org mode."
2544 :tag "Org Progress"
2545 :group 'org-time)
2547 (defvar org-todo-interpretation-widgets
2548 '((:tag "Sequence (cycling hits every state)" sequence)
2549 (:tag "Type (cycling directly to DONE)" type))
2550 "The available interpretation symbols for customizing `org-todo-keywords'.
2551 Interested libraries should add to this list.")
2553 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2554 "List of TODO entry keyword sequences and their interpretation.
2555 \\<org-mode-map>This is a list of sequences.
2557 Each sequence starts with a symbol, either `sequence' or `type',
2558 indicating if the keywords should be interpreted as a sequence of
2559 action steps, or as different types of TODO items. The first
2560 keywords are states requiring action - these states will select a headline
2561 for inclusion into the global TODO list Org produces. If one of the
2562 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2563 signify that no further action is necessary. If \"|\" is not found,
2564 the last keyword is treated as the only DONE state of the sequence.
2566 The command `\\[org-todo]' cycles an entry through these states, and one
2567 additional state where no keyword is present. For details about this
2568 cycling, see the manual.
2570 TODO keywords and interpretation can also be set on a per-file basis with
2571 the special #+SEQ_TODO and #+TYP_TODO lines.
2573 Each keyword can optionally specify a character for fast state selection
2574 \(in combination with the variable `org-use-fast-todo-selection')
2575 and specifiers for state change logging, using the same syntax that
2576 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2577 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2578 indicates to record a time stamp each time this state is selected.
2580 Each keyword may also specify if a timestamp or a note should be
2581 recorded when entering or leaving the state, by adding additional
2582 characters in the parenthesis after the keyword. This looks like this:
2583 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2584 record only the time of the state change. With X and Y being either
2585 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2586 Y when leaving the state if and only if the *target* state does not
2587 define X. You may omit any of the fast-selection key or X or /Y,
2588 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2590 For backward compatibility, this variable may also be just a list
2591 of keywords. In this case the interpretation (sequence or type) will be
2592 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2593 :group 'org-todo
2594 :group 'org-keywords
2595 :type '(choice
2596 (repeat :tag "Old syntax, just keywords"
2597 (string :tag "Keyword"))
2598 (repeat :tag "New syntax"
2599 (cons
2600 (choice
2601 :tag "Interpretation"
2602 ;;Quick and dirty way to see
2603 ;;`org-todo-interpretations'. This takes the
2604 ;;place of item arguments
2605 :convert-widget
2606 (lambda (widget)
2607 (widget-put widget
2608 :args (mapcar
2609 (lambda (x)
2610 (widget-convert
2611 (cons 'const x)))
2612 org-todo-interpretation-widgets))
2613 widget))
2614 (repeat
2615 (string :tag "Keyword"))))))
2617 (defvar-local org-todo-keywords-1 nil
2618 "All TODO and DONE keywords active in a buffer.")
2619 (defvar org-todo-keywords-for-agenda nil)
2620 (defvar org-done-keywords-for-agenda nil)
2621 (defvar org-todo-keyword-alist-for-agenda nil)
2622 (defvar org-tag-alist-for-agenda nil
2623 "Alist of all tags from all agenda files.")
2624 (defvar org-tag-groups-alist-for-agenda nil
2625 "Alist of all groups tags from all current agenda files.")
2626 (defvar-local org-tag-groups-alist nil)
2627 (defvar org-agenda-contributing-files nil)
2628 (defvar-local org-current-tag-alist nil
2629 "Alist of all tag groups in current buffer.
2630 This variable takes into consideration `org-tag-alist',
2631 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2632 (defvar-local org-not-done-keywords nil)
2633 (defvar-local org-done-keywords nil)
2634 (defvar-local org-todo-heads nil)
2635 (defvar-local org-todo-sets nil)
2636 (defvar-local org-todo-log-states nil)
2637 (defvar-local org-todo-kwd-alist nil)
2638 (defvar-local org-todo-key-alist nil)
2639 (defvar-local org-todo-key-trigger nil)
2641 (defcustom org-todo-interpretation 'sequence
2642 "Controls how TODO keywords are interpreted.
2643 This variable is in principle obsolete and is only used for
2644 backward compatibility, if the interpretation of todo keywords is
2645 not given already in `org-todo-keywords'. See that variable for
2646 more information."
2647 :group 'org-todo
2648 :group 'org-keywords
2649 :type '(choice (const sequence)
2650 (const type)))
2652 (defcustom org-use-fast-todo-selection t
2653 "\\<org-mode-map>\
2654 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2655 This variable describes if and under what circumstances the cycling
2656 mechanism for TODO keywords will be replaced by a single-key, direct
2657 selection scheme.
2659 When nil, fast selection is never used.
2661 When the symbol `prefix', it will be used when `org-todo' is called
2662 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2663 in an Org buffer, and
2664 `\\[universal-argument] t' in an agenda buffer.
2666 When t, fast selection is used by default. In this case, the prefix
2667 argument forces cycling instead.
2669 In all cases, the special interface is only used if access keys have
2670 actually been assigned by the user, i.e. if keywords in the configuration
2671 are followed by a letter in parenthesis, like TODO(t)."
2672 :group 'org-todo
2673 :type '(choice
2674 (const :tag "Never" nil)
2675 (const :tag "By default" t)
2676 (const :tag "Only with C-u C-c C-t" prefix)))
2678 (defcustom org-provide-todo-statistics t
2679 "Non-nil means update todo statistics after insert and toggle.
2680 ALL-HEADLINES means update todo statistics by including headlines
2681 with no TODO keyword as well, counting them as not done.
2682 A list of TODO keywords means the same, but skip keywords that are
2683 not in this list.
2684 When set to a list of two lists, the first list contains keywords
2685 to consider as TODO keywords, the second list contains keywords
2686 to consider as DONE keywords.
2688 When this is set, todo statistics is updated in the parent of the
2689 current entry each time a todo state is changed."
2690 :group 'org-todo
2691 :type '(choice
2692 (const :tag "Yes, only for TODO entries" t)
2693 (const :tag "Yes, including all entries" all-headlines)
2694 (repeat :tag "Yes, for TODOs in this list"
2695 (string :tag "TODO keyword"))
2696 (list :tag "Yes, for TODOs and DONEs in these lists"
2697 (repeat (string :tag "TODO keyword"))
2698 (repeat (string :tag "DONE keyword")))
2699 (other :tag "No TODO statistics" nil)))
2701 (defcustom org-hierarchical-todo-statistics t
2702 "Non-nil means TODO statistics covers just direct children.
2703 When nil, all entries in the subtree are considered.
2704 This has only an effect if `org-provide-todo-statistics' is set.
2705 To set this to nil for only a single subtree, use a COOKIE_DATA
2706 property and include the word \"recursive\" into the value."
2707 :group 'org-todo
2708 :type 'boolean)
2710 (defcustom org-after-todo-state-change-hook nil
2711 "Hook which is run after the state of a TODO item was changed.
2712 The new state (a string with a TODO keyword, or nil) is available in the
2713 Lisp variable `org-state'."
2714 :group 'org-todo
2715 :type 'hook)
2717 (defvar org-blocker-hook nil
2718 "Hook for functions that are allowed to block a state change.
2720 Functions in this hook should not modify the buffer.
2721 Each function gets as its single argument a property list,
2722 see `org-trigger-hook' for more information about this list.
2724 If any of the functions in this hook returns nil, the state change
2725 is blocked.")
2727 (defvar org-trigger-hook nil
2728 "Hook for functions that are triggered by a state change.
2730 Each function gets as its single argument a property list with at
2731 least the following elements:
2733 (:type type-of-change :position pos-at-entry-start
2734 :from old-state :to new-state)
2736 Depending on the type, more properties may be present.
2738 This mechanism is currently implemented for:
2740 TODO state changes
2741 ------------------
2742 :type todo-state-change
2743 :from previous state (keyword as a string), or nil, or a symbol
2744 `todo' or `done', to indicate the general type of state.
2745 :to new state, like in :from")
2747 (defcustom org-enforce-todo-dependencies nil
2748 "Non-nil means undone TODO entries will block switching the parent to DONE.
2749 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2750 be blocked if any prior sibling is not yet done.
2751 Finally, if the parent is blocked because of ordered siblings of its own,
2752 the child will also be blocked."
2753 :set (lambda (var val)
2754 (set var val)
2755 (if val
2756 (add-hook 'org-blocker-hook
2757 'org-block-todo-from-children-or-siblings-or-parent)
2758 (remove-hook 'org-blocker-hook
2759 'org-block-todo-from-children-or-siblings-or-parent)))
2760 :group 'org-todo
2761 :type 'boolean)
2763 (defcustom org-enforce-todo-checkbox-dependencies nil
2764 "Non-nil means unchecked boxes will block switching the parent to DONE.
2765 When this is nil, checkboxes have no influence on switching TODO states.
2766 When non-nil, you first need to check off all check boxes before the TODO
2767 entry can be switched to DONE.
2768 This variable needs to be set before org.el is loaded, and you need to
2769 restart Emacs after a change to make the change effective. The only way
2770 to change is while Emacs is running is through the customize interface."
2771 :set (lambda (var val)
2772 (set var val)
2773 (if val
2774 (add-hook 'org-blocker-hook
2775 'org-block-todo-from-checkboxes)
2776 (remove-hook 'org-blocker-hook
2777 'org-block-todo-from-checkboxes)))
2778 :group 'org-todo
2779 :type 'boolean)
2781 (defcustom org-treat-insert-todo-heading-as-state-change nil
2782 "Non-nil means inserting a TODO heading is treated as state change.
2783 So when the command `\\[org-insert-todo-heading]' is used, state change
2784 logging will apply if appropriate. When nil, the new TODO item will
2785 be inserted directly, and no logging will take place."
2786 :group 'org-todo
2787 :type 'boolean)
2789 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2790 "Non-nil means switching TODO states with S-cursor counts as state change.
2791 This is the default behavior. However, setting this to nil allows a
2792 convenient way to select a TODO state and bypass any logging associated
2793 with that."
2794 :group 'org-todo
2795 :type 'boolean)
2797 (defcustom org-todo-state-tags-triggers nil
2798 "Tag changes that should be triggered by TODO state changes.
2799 This is a list. Each entry is
2801 (state-change (tag . flag) .......)
2803 State-change can be a string with a state, and empty string to indicate the
2804 state that has no TODO keyword, or it can be one of the symbols `todo'
2805 or `done', meaning any not-done or done state, respectively."
2806 :group 'org-todo
2807 :group 'org-tags
2808 :type '(repeat
2809 (cons (choice :tag "When changing to"
2810 (const :tag "Not-done state" todo)
2811 (const :tag "Done state" done)
2812 (string :tag "State"))
2813 (repeat
2814 (cons :tag "Tag action"
2815 (string :tag "Tag")
2816 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2818 (defcustom org-log-done nil
2819 "Information to record when a task moves to the DONE state.
2821 Possible values are:
2823 nil Don't add anything, just change the keyword
2824 time Add a time stamp to the task
2825 note Prompt for a note and add it with template `org-log-note-headings'
2827 This option can also be set with on a per-file-basis with
2829 #+STARTUP: nologdone
2830 #+STARTUP: logdone
2831 #+STARTUP: lognotedone
2833 You can have local logging settings for a subtree by setting the LOGGING
2834 property to one or more of these keywords."
2835 :group 'org-todo
2836 :group 'org-progress
2837 :type '(choice
2838 (const :tag "No logging" nil)
2839 (const :tag "Record CLOSED timestamp" time)
2840 (const :tag "Record CLOSED timestamp with note." note)))
2842 ;; Normalize old uses of org-log-done.
2843 (cond
2844 ((eq org-log-done t) (setq org-log-done 'time))
2845 ((and (listp org-log-done) (memq 'done org-log-done))
2846 (setq org-log-done 'note)))
2848 (defcustom org-log-reschedule nil
2849 "Information to record when the scheduling date of a tasks is modified.
2851 Possible values are:
2853 nil Don't add anything, just change the date
2854 time Add a time stamp to the task
2855 note Prompt for a note and add it with template `org-log-note-headings'
2857 This option can also be set with on a per-file-basis with
2859 #+STARTUP: nologreschedule
2860 #+STARTUP: logreschedule
2861 #+STARTUP: lognotereschedule"
2862 :group 'org-todo
2863 :group 'org-progress
2864 :type '(choice
2865 (const :tag "No logging" nil)
2866 (const :tag "Record timestamp" time)
2867 (const :tag "Record timestamp with note." note)))
2869 (defcustom org-log-redeadline nil
2870 "Information to record when the deadline date of a tasks is modified.
2872 Possible values are:
2874 nil Don't add anything, just change the date
2875 time Add a time stamp to the task
2876 note Prompt for a note and add it with template `org-log-note-headings'
2878 This option can also be set with on a per-file-basis with
2880 #+STARTUP: nologredeadline
2881 #+STARTUP: logredeadline
2882 #+STARTUP: lognoteredeadline
2884 You can have local logging settings for a subtree by setting the LOGGING
2885 property to one or more of these keywords."
2886 :group 'org-todo
2887 :group 'org-progress
2888 :type '(choice
2889 (const :tag "No logging" nil)
2890 (const :tag "Record timestamp" time)
2891 (const :tag "Record timestamp with note." note)))
2893 (defcustom org-log-note-clock-out nil
2894 "Non-nil means record a note when clocking out of an item.
2895 This can also be configured on a per-file basis by adding one of
2896 the following lines anywhere in the buffer:
2898 #+STARTUP: lognoteclock-out
2899 #+STARTUP: nolognoteclock-out"
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type 'boolean)
2904 (defcustom org-log-done-with-time t
2905 "Non-nil means the CLOSED time stamp will contain date and time.
2906 When nil, only the date will be recorded."
2907 :group 'org-progress
2908 :type 'boolean)
2910 (defcustom org-log-note-headings
2911 '((done . "CLOSING NOTE %t")
2912 (state . "State %-12s from %-12S %t")
2913 (note . "Note taken on %t")
2914 (reschedule . "Rescheduled from %S on %t")
2915 (delschedule . "Not scheduled, was %S on %t")
2916 (redeadline . "New deadline from %S on %t")
2917 (deldeadline . "Removed deadline, was %S on %t")
2918 (refile . "Refiled on %t")
2919 (clock-out . ""))
2920 "Headings for notes added to entries.
2922 The value is an alist, with the car being a symbol indicating the
2923 note context, and the cdr is the heading to be used. The heading
2924 may also be the empty string. The following placeholders can be
2925 used:
2927 %t a time stamp.
2928 %T an active time stamp instead the default inactive one
2929 %d a short-format time stamp.
2930 %D an active short-format time stamp.
2931 %s the new TODO state or time stamp (inactive), in double quotes.
2932 %S the old TODO state or time stamp (inactive), in double quotes.
2933 %u the user name.
2934 %U full user name.
2936 In fact, it is not a good idea to change the `state' entry,
2937 because Agenda Log mode depends on the format of these entries."
2938 :group 'org-todo
2939 :group 'org-progress
2940 :type '(list :greedy t
2941 (cons (const :tag "Heading when closing an item" done) string)
2942 (cons (const :tag
2943 "Heading when changing todo state (todo sequence only)"
2944 state) string)
2945 (cons (const :tag "Heading when just taking a note" note) string)
2946 (cons (const :tag "Heading when rescheduling" reschedule) string)
2947 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2948 (cons (const :tag "Heading when changing deadline" redeadline) string)
2949 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2950 (cons (const :tag "Heading when refiling" refile) string)
2951 (cons (const :tag "Heading when clocking out" clock-out) string)))
2953 (unless (assq 'note org-log-note-headings)
2954 (push '(note . "%t") org-log-note-headings))
2956 (defcustom org-log-into-drawer nil
2957 "Non-nil means insert state change notes and time stamps into a drawer.
2958 When nil, state changes notes will be inserted after the headline and
2959 any scheduling and clock lines, but not inside a drawer.
2961 The value of this variable should be the name of the drawer to use.
2962 LOGBOOK is proposed as the default drawer for this purpose, you can
2963 also set this to a string to define the drawer of your choice.
2965 A value of t is also allowed, representing \"LOGBOOK\".
2967 A value of t or nil can also be set with on a per-file-basis with
2969 #+STARTUP: logdrawer
2970 #+STARTUP: nologdrawer
2972 If this variable is set, `org-log-state-notes-insert-after-drawers'
2973 will be ignored.
2975 You can set the property LOG_INTO_DRAWER to overrule this setting for
2976 a subtree.
2978 Do not check directly this variable in a Lisp program. Call
2979 function `org-log-into-drawer' instead."
2980 :group 'org-todo
2981 :group 'org-progress
2982 :type '(choice
2983 (const :tag "Not into a drawer" nil)
2984 (const :tag "LOGBOOK" t)
2985 (string :tag "Other")))
2987 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2989 (defun org-log-into-drawer ()
2990 "Name of the log drawer, as a string, or nil.
2991 This is the value of `org-log-into-drawer'. However, if the
2992 current entry has or inherits a LOG_INTO_DRAWER property, it will
2993 be used instead of the default value."
2994 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2995 (cond ((equal p "nil") nil)
2996 ((equal p "t") "LOGBOOK")
2997 ((stringp p) p)
2998 (p "LOGBOOK")
2999 ((stringp org-log-into-drawer) org-log-into-drawer)
3000 (org-log-into-drawer "LOGBOOK"))))
3002 (defcustom org-log-state-notes-insert-after-drawers nil
3003 "Non-nil means insert state change notes after any drawers in entry.
3004 Only the drawers that *immediately* follow the headline and the
3005 deadline/scheduled line are skipped.
3006 When nil, insert notes right after the heading and perhaps the line
3007 with deadline/scheduling if present.
3009 This variable will have no effect if `org-log-into-drawer' is
3010 set."
3011 :group 'org-todo
3012 :group 'org-progress
3013 :type 'boolean)
3015 (defcustom org-log-states-order-reversed t
3016 "Non-nil means the latest state note will be directly after heading.
3017 When nil, the state change notes will be ordered according to time.
3019 This option can also be set with on a per-file-basis with
3021 #+STARTUP: logstatesreversed
3022 #+STARTUP: nologstatesreversed"
3023 :group 'org-todo
3024 :group 'org-progress
3025 :type 'boolean)
3027 (defcustom org-todo-repeat-to-state nil
3028 "The TODO state to which a repeater should return the repeating task.
3029 By default this is the first task in a TODO sequence, or the previous state
3030 in a TODO_TYP set. But you can specify another task here.
3031 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3032 :group 'org-todo
3033 :version "24.1"
3034 :type '(choice (const :tag "Head of sequence" nil)
3035 (string :tag "Specific 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-calendar-to-agenda-key [?c]
3776 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3777 The command `org-calendar-goto-agenda' will be bound to this key. The
3778 default is the character `c' because then `c' can be used to switch back and
3779 forth between agenda and calendar."
3780 :group 'org-agenda
3781 :type 'sexp)
3783 (defcustom org-calendar-insert-diary-entry-key [?i]
3784 "The key to be installed in `calendar-mode-map' for adding diary entries.
3785 This option is irrelevant until `org-agenda-diary-file' has been configured
3786 to point to an Org file. When that is the case, the command
3787 `org-agenda-diary-entry' will be bound to the key given here, by default
3788 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3789 if you want to continue doing this, you need to change this to a different
3790 key."
3791 :group 'org-agenda
3792 :type 'sexp)
3794 (defcustom org-agenda-diary-file 'diary-file
3795 "File to which to add new entries with the `i' key in agenda and calendar.
3796 When this is the symbol `diary-file', the functionality in the Emacs
3797 calendar will be used to add entries to the `diary-file'. But when this
3798 points to a file, `org-agenda-diary-entry' will be used instead."
3799 :group 'org-agenda
3800 :type '(choice
3801 (const :tag "The standard Emacs diary file" diary-file)
3802 (file :tag "Special Org file diary entries")))
3804 (eval-after-load "calendar"
3805 '(progn
3806 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3807 'org-calendar-goto-agenda)
3808 (add-hook 'calendar-mode-hook
3809 (lambda ()
3810 (unless (eq org-agenda-diary-file 'diary-file)
3811 (define-key calendar-mode-map
3812 org-calendar-insert-diary-entry-key
3813 'org-agenda-diary-entry))))))
3815 (defgroup org-latex nil
3816 "Options for embedding LaTeX code into Org mode."
3817 :tag "Org LaTeX"
3818 :group 'org)
3820 (defcustom org-format-latex-options
3821 '(:foreground default :background default :scale 1.0
3822 :html-foreground "Black" :html-background "Transparent"
3823 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3824 "Options for creating images from LaTeX fragments.
3825 This is a property list with the following properties:
3826 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3827 `default' means use the foreground of the default face.
3828 `auto' means use the foreground from the text face.
3829 :background the background color, or \"Transparent\".
3830 `default' means use the background of the default face.
3831 `auto' means use the background from the text face.
3832 :scale a scaling factor for the size of the images, to get more pixels
3833 :html-foreground, :html-background, :html-scale
3834 the same numbers for HTML export.
3835 :matchers a list indicating which matchers should be used to
3836 find LaTeX fragments. Valid members of this list are:
3837 \"begin\" find environments
3838 \"$1\" find single characters surrounded by $.$
3839 \"$\" find math expressions surrounded by $...$
3840 \"$$\" find math expressions surrounded by $$....$$
3841 \"\\(\" find math expressions surrounded by \\(...\\)
3842 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3843 :group 'org-latex
3844 :type 'plist)
3846 (defcustom org-format-latex-signal-error t
3847 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3848 When nil, just push out a message."
3849 :group 'org-latex
3850 :version "24.1"
3851 :type 'boolean)
3853 (defcustom org-latex-to-mathml-jar-file nil
3854 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3855 Use this to specify additional executable file say a jar file.
3857 When using MathToWeb as the converter, specify the full-path to
3858 your mathtoweb.jar file."
3859 :group 'org-latex
3860 :version "24.1"
3861 :type '(choice
3862 (const :tag "None" nil)
3863 (file :tag "JAR file" :must-match t)))
3865 (defcustom org-latex-to-mathml-convert-command nil
3866 "Command to convert LaTeX fragments to MathML.
3867 Replace format-specifiers in the command as noted below and use
3868 `shell-command' to convert LaTeX to MathML.
3869 %j: Executable file in fully expanded form as specified by
3870 `org-latex-to-mathml-jar-file'.
3871 %I: Input LaTeX file in fully expanded form.
3872 %i: The latex fragment to be converted.
3873 %o: Output MathML file.
3875 This command is used by `org-create-math-formula'.
3877 When using MathToWeb as the converter, set this option to
3878 \"java -jar %j -unicode -force -df %o %I\".
3880 When using LaTeXML set this option to
3881 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3882 :group 'org-latex
3883 :version "24.1"
3884 :type '(choice
3885 (const :tag "None" nil)
3886 (string :tag "\nShell command")))
3888 (defcustom org-preview-latex-default-process 'dvipng
3889 "The default process to convert LaTeX fragments to image files.
3890 All available processes and theirs documents can be found in
3891 `org-preview-latex-process-alist', which see."
3892 :group 'org-latex
3893 :version "26.1"
3894 :package-version '(Org . "9.0")
3895 :type 'symbol)
3897 (defcustom org-preview-latex-process-alist
3898 '((dvipng
3899 :programs ("latex" "dvipng")
3900 :description "dvi > png"
3901 :message "you need to install the programs: latex and dvipng."
3902 :image-input-type "dvi"
3903 :image-output-type "png"
3904 :image-size-adjust (1.0 . 1.0)
3905 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3906 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3907 (dvisvgm
3908 :programs ("latex" "dvisvgm")
3909 :description "dvi > svg"
3910 :message "you need to install the programs: latex and dvisvgm."
3911 :use-xcolor t
3912 :image-input-type "dvi"
3913 :image-output-type "svg"
3914 :image-size-adjust (1.7 . 1.5)
3915 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3916 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3917 (imagemagick
3918 :programs ("latex" "convert")
3919 :description "pdf > png"
3920 :message "you need to install the programs: latex and imagemagick."
3921 :use-xcolor t
3922 :image-input-type "pdf"
3923 :image-output-type "png"
3924 :image-size-adjust (1.0 . 1.0)
3925 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3926 :image-converter
3927 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3928 "Definitions of external processes for LaTeX previewing.
3929 Org mode can use some external commands to generate TeX snippet's images for
3930 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3931 `org-create-formula-image' how to call them.
3933 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3934 PROPERTIES accepts the following attributes:
3936 :programs list of strings, required programs.
3937 :description string, describe the process.
3938 :message string, message it when required programs cannot be found.
3939 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3940 :image-output-type string, output file type of image converter (e.g., \"png\").
3941 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3942 deal with background and foreground color of image.
3943 Otherwise, dvipng style background and foreground color
3944 format are generated. You may then refer to them in
3945 command options with \"%F\" and \"%B\".
3946 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3947 image size showed in buffer and the cdr element is for
3948 HTML file. This option is only useful for process
3949 developers, users should use variable
3950 `org-format-latex-options' instead.
3951 :post-clean list of strings, files matched are to be cleaned up once
3952 the image is generated. When nil, the files with \".dvi\",
3953 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3954 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3955 be cleaned up.
3956 :latex-header list of strings, the LaTeX header of the snippet file.
3957 When nil, the fallback value is used instead, which is
3958 controlled by `org-format-latex-header',
3959 `org-latex-default-packages-alist' and
3960 `org-latex-packages-alist', which see.
3961 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3962 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3963 replaced with values defined below.
3964 :image-converter list of image converter commands strings. Each of them is
3965 given to the shell and supports any of the following
3966 place-holders defined below.
3968 Place-holders used by `:image-converter' and `:latex-compiler':
3970 %f input file name
3971 %b base name of input file
3972 %o base directory of input file
3973 %O absolute output file name
3975 Place-holders only used by `:image-converter':
3977 %F foreground of image
3978 %B background of image
3979 %D dpi, which is used to adjust image size by some processing commands.
3980 %S the image size scale ratio, which is used to adjust image size by some
3981 processing commands."
3982 :group 'org-latex
3983 :version "26.1"
3984 :package-version '(Org . "9.0")
3985 :type '(alist :tag "LaTeX to image backends"
3986 :value-type (plist)))
3988 (defcustom org-preview-latex-image-directory "ltximg/"
3989 "Path to store latex preview images.
3990 A relative path here creates many directories relative to the
3991 processed org files paths. An absolute path puts all preview
3992 images at the same place."
3993 :group 'org-latex
3994 :version "26.1"
3995 :package-version '(Org . "9.0")
3996 :type 'string)
3998 (defun org-format-latex-mathml-available-p ()
3999 "Return t if `org-latex-to-mathml-convert-command' is usable."
4000 (save-match-data
4001 (when (and (boundp 'org-latex-to-mathml-convert-command)
4002 org-latex-to-mathml-convert-command)
4003 (let ((executable (car (split-string
4004 org-latex-to-mathml-convert-command))))
4005 (when (executable-find executable)
4006 (if (string-match
4007 "%j" org-latex-to-mathml-convert-command)
4008 (file-readable-p org-latex-to-mathml-jar-file)
4009 t))))))
4011 (defcustom org-format-latex-header "\\documentclass{article}
4012 \\usepackage[usenames]{color}
4013 \[PACKAGES]
4014 \[DEFAULT-PACKAGES]
4015 \\pagestyle{empty} % do not remove
4016 % The settings below are copied from fullpage.sty
4017 \\setlength{\\textwidth}{\\paperwidth}
4018 \\addtolength{\\textwidth}{-3cm}
4019 \\setlength{\\oddsidemargin}{1.5cm}
4020 \\addtolength{\\oddsidemargin}{-2.54cm}
4021 \\setlength{\\evensidemargin}{\\oddsidemargin}
4022 \\setlength{\\textheight}{\\paperheight}
4023 \\addtolength{\\textheight}{-\\headheight}
4024 \\addtolength{\\textheight}{-\\headsep}
4025 \\addtolength{\\textheight}{-\\footskip}
4026 \\addtolength{\\textheight}{-3cm}
4027 \\setlength{\\topmargin}{1.5cm}
4028 \\addtolength{\\topmargin}{-2.54cm}"
4029 "The document header used for processing LaTeX fragments.
4030 It is imperative that this header make sure that no page number
4031 appears on the page. The package defined in the variables
4032 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4033 will either replace the placeholder \"[PACKAGES]\" in this
4034 header, or they will be appended."
4035 :group 'org-latex
4036 :type 'string)
4038 (defun org-set-packages-alist (var val)
4039 "Set the packages alist and make sure it has 3 elements per entry."
4040 (set var (mapcar (lambda (x)
4041 (if (and (consp x) (= (length x) 2))
4042 (list (car x) (nth 1 x) t)
4044 val)))
4046 (defun org-get-packages-alist (var)
4047 "Get the packages alist and make sure it has 3 elements per entry."
4048 (mapcar (lambda (x)
4049 (if (and (consp x) (= (length x) 2))
4050 (list (car x) (nth 1 x) t)
4052 (default-value var)))
4054 (defcustom org-latex-default-packages-alist
4055 '(("AUTO" "inputenc" t ("pdflatex"))
4056 ("T1" "fontenc" t ("pdflatex"))
4057 ("" "graphicx" t)
4058 ("" "grffile" t)
4059 ("" "longtable" nil)
4060 ("" "wrapfig" nil)
4061 ("" "rotating" nil)
4062 ("normalem" "ulem" t)
4063 ("" "amsmath" t)
4064 ("" "textcomp" t)
4065 ("" "amssymb" t)
4066 ("" "capt-of" nil)
4067 ("" "hyperref" nil))
4068 "Alist of default packages to be inserted in the header.
4070 Change this only if one of the packages here causes an
4071 incompatibility with another package you are using.
4073 The packages in this list are needed by one part or another of
4074 Org mode to function properly:
4076 - inputenc, fontenc: for basic font and character selection
4077 - graphicx: for including images
4078 - grffile: allow periods and spaces in graphics file names
4079 - longtable: For multipage tables
4080 - wrapfig: for figure placement
4081 - rotating: for sideways figures and tables
4082 - ulem: for underline and strike-through
4083 - amsmath: for subscript and superscript and math environments
4084 - textcomp, amssymb: for various symbols used
4085 for interpreting the entities in `org-entities'. You can skip
4086 some of these packages if you don't use any of their symbols.
4087 - capt-of: for captions outside of floats
4088 - hyperref: for cross references
4090 Therefore you should not modify this variable unless you know
4091 what you are doing. The one reason to change it anyway is that
4092 you might be loading some other package that conflicts with one
4093 of the default packages. Each element is either a cell or
4094 a string.
4096 A cell is of the format
4098 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4100 If SNIPPET-FLAG is non-nil, the package also needs to be included
4101 when compiling LaTeX snippets into images for inclusion into
4102 non-LaTeX output. COMPILERS is a list of compilers that should
4103 include the package, see `org-latex-compiler'. If the document
4104 compiler is not in the list, and the list is non-nil, the package
4105 will not be inserted in the final document.
4107 A string will be inserted as-is in the header of the document."
4108 :group 'org-latex
4109 :group 'org-export-latex
4110 :set 'org-set-packages-alist
4111 :get 'org-get-packages-alist
4112 :version "26.1"
4113 :package-version '(Org . "8.3")
4114 :type '(repeat
4115 (choice
4116 (list :tag "options/package pair"
4117 (string :tag "options")
4118 (string :tag "package")
4119 (boolean :tag "Snippet")
4120 (choice
4121 (const :tag "For all compilers" nil)
4122 (repeat :tag "Allowed compiler" string)))
4123 (string :tag "A line of LaTeX"))))
4125 (defcustom org-latex-packages-alist nil
4126 "Alist of packages to be inserted in every LaTeX header.
4128 These will be inserted after `org-latex-default-packages-alist'.
4129 Each element is either a cell or a string.
4131 A cell is of the format:
4133 (\"options\" \"package\" SNIPPET-FLAG)
4135 SNIPPET-FLAG, when non-nil, indicates that this package is also
4136 needed when turning LaTeX snippets into images for inclusion into
4137 non-LaTeX output.
4139 A string will be inserted as-is in the header of the document.
4141 Make sure that you only list packages here which:
4143 - you want in every file;
4144 - do not conflict with the setup in `org-format-latex-header';
4145 - do not conflict with the default packages in
4146 `org-latex-default-packages-alist'."
4147 :group 'org-latex
4148 :group 'org-export-latex
4149 :set 'org-set-packages-alist
4150 :get 'org-get-packages-alist
4151 :type '(repeat
4152 (choice
4153 (list :tag "options/package pair"
4154 (string :tag "options")
4155 (string :tag "package")
4156 (boolean :tag "Snippet"))
4157 (string :tag "A line of LaTeX"))))
4159 (defgroup org-appearance nil
4160 "Settings for Org mode appearance."
4161 :tag "Org Appearance"
4162 :group 'org)
4164 (defcustom org-level-color-stars-only nil
4165 "Non-nil means fontify only the stars in each headline.
4166 When nil, the entire headline is fontified.
4167 Changing it requires restart of `font-lock-mode' to become effective
4168 also in regions already fontified."
4169 :group 'org-appearance
4170 :type 'boolean)
4172 (defcustom org-hide-leading-stars nil
4173 "Non-nil means hide the first N-1 stars in a headline.
4174 This works by using the face `org-hide' for these stars. This
4175 face is white for a light background, and black for a dark
4176 background. You may have to customize the face `org-hide' to
4177 make this work.
4178 Changing it requires restart of `font-lock-mode' to become effective
4179 also in regions already fontified.
4180 You may also set this on a per-file basis by adding one of the following
4181 lines to the buffer:
4183 #+STARTUP: hidestars
4184 #+STARTUP: showstars"
4185 :group 'org-appearance
4186 :type 'boolean)
4188 (defcustom org-hidden-keywords nil
4189 "List of symbols corresponding to keywords to be hidden the org buffer.
4190 For example, a value \\='(title) for this list will make the document's title
4191 appear in the buffer without the initial #+TITLE: keyword."
4192 :group 'org-appearance
4193 :version "24.1"
4194 :type '(set (const :tag "#+AUTHOR" author)
4195 (const :tag "#+DATE" date)
4196 (const :tag "#+EMAIL" email)
4197 (const :tag "#+TITLE" title)))
4199 (defcustom org-custom-properties nil
4200 "List of properties (as strings) with a special meaning.
4201 The default use of these custom properties is to let the user
4202 hide them with `org-toggle-custom-properties-visibility'."
4203 :group 'org-properties
4204 :group 'org-appearance
4205 :version "24.3"
4206 :type '(repeat (string :tag "Property Name")))
4208 (defcustom org-fontify-done-headline nil
4209 "Non-nil means change the face of a headline if it is marked DONE.
4210 Normally, only the TODO/DONE keyword indicates the state of a headline.
4211 When this is non-nil, the headline after the keyword is set to the
4212 `org-headline-done' as an additional indication."
4213 :group 'org-appearance
4214 :type 'boolean)
4216 (defcustom org-fontify-emphasized-text t
4217 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4218 Changing this variable requires a restart of Emacs to take effect."
4219 :group 'org-appearance
4220 :type 'boolean)
4222 (defcustom org-fontify-whole-heading-line nil
4223 "Non-nil means fontify the whole line for headings.
4224 This is useful when setting a background color for the
4225 org-level-* faces."
4226 :group 'org-appearance
4227 :type 'boolean)
4229 (defcustom org-highlight-latex-and-related nil
4230 "Non-nil means highlight LaTeX related syntax in the buffer.
4231 When non nil, the value should be a list containing any of the
4232 following symbols:
4233 `latex' Highlight LaTeX snippets and environments.
4234 `script' Highlight subscript and superscript.
4235 `entities' Highlight entities."
4236 :group 'org-appearance
4237 :version "24.4"
4238 :package-version '(Org . "8.0")
4239 :type '(choice
4240 (const :tag "No highlighting" nil)
4241 (set :greedy t :tag "Highlight"
4242 (const :tag "LaTeX snippets and environments" latex)
4243 (const :tag "Subscript and superscript" script)
4244 (const :tag "Entities" entities))))
4246 (defcustom org-hide-emphasis-markers nil
4247 "Non-nil mean font-lock should hide the emphasis marker characters."
4248 :group 'org-appearance
4249 :type 'boolean)
4251 (defcustom org-hide-macro-markers nil
4252 "Non-nil mean font-lock should hide the brackets marking macro calls."
4253 :group 'org-appearance
4254 :type 'boolean)
4256 (defcustom org-pretty-entities nil
4257 "Non-nil means show entities as UTF8 characters.
4258 When nil, the \\name form remains in the buffer."
4259 :group 'org-appearance
4260 :version "24.1"
4261 :type 'boolean)
4263 (defcustom org-pretty-entities-include-sub-superscripts t
4264 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4265 :group 'org-appearance
4266 :version "24.1"
4267 :type 'boolean)
4269 (defvar org-emph-re nil
4270 "Regular expression for matching emphasis.
4271 After a match, the match groups contain these elements:
4272 0 The match of the full regular expression, including the characters
4273 before and after the proper match
4274 1 The character before the proper match, or empty at beginning of line
4275 2 The proper match, including the leading and trailing markers
4276 3 The leading marker like * or /, indicating the type of highlighting
4277 4 The text between the emphasis markers, not including the markers
4278 5 The character after the match, empty at the end of a line")
4280 (defvar org-verbatim-re nil
4281 "Regular expression for matching verbatim text.")
4283 (defvar org-emphasis-regexp-components) ; defined just below
4284 (defvar org-emphasis-alist) ; defined just below
4285 (defun org-set-emph-re (var val)
4286 "Set variable and compute the emphasis regular expression."
4287 (set var val)
4288 (when (and (boundp 'org-emphasis-alist)
4289 (boundp 'org-emphasis-regexp-components)
4290 org-emphasis-alist org-emphasis-regexp-components)
4291 (pcase-let*
4292 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4293 (body (if (<= nl 0) body
4294 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4295 (template
4296 (format (concat "\\([%s]\\|^\\)" ;before markers
4297 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4298 "\\([%s]\\|$\\)") ;after markers
4299 pre border border body border post)))
4300 (setq org-emph-re (format template "*/_+"))
4301 (setq org-verbatim-re (format template "=~")))))
4303 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4304 ;; set this option proved cumbersome. See this message/thread:
4305 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4306 (defvar org-emphasis-regexp-components
4307 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4308 "Components used to build the regular expression for emphasis.
4309 This is a list with five entries. Terminology: In an emphasis string
4310 like \" *strong word* \", we call the initial space PREMATCH, the final
4311 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4312 and \"trong wor\" is the body. The different components in this variable
4313 specify what is allowed/forbidden in each part:
4315 pre Chars allowed as prematch. Beginning of line will be allowed too.
4316 post Chars allowed as postmatch. End of line will be allowed too.
4317 border The chars *forbidden* as border characters.
4318 body-regexp A regexp like \".\" to match a body character. Don't use
4319 non-shy groups here, and don't allow newline here.
4320 newline The maximum number of newlines allowed in an emphasis exp.
4322 You need to reload Org or to restart Emacs after setting this.")
4324 (defcustom org-emphasis-alist
4325 '(("*" bold)
4326 ("/" italic)
4327 ("_" underline)
4328 ("=" org-verbatim verbatim)
4329 ("~" org-code verbatim)
4330 ("+" (:strike-through t)))
4331 "Alist of characters and faces to emphasize text.
4332 Text starting and ending with a special character will be emphasized,
4333 for example *bold*, _underlined_ and /italic/. This variable sets the
4334 marker characters and the face to be used by font-lock for highlighting
4335 in Org buffers.
4337 You need to reload Org or to restart Emacs after customizing this."
4338 :group 'org-appearance
4339 :set 'org-set-emph-re
4340 :version "24.4"
4341 :package-version '(Org . "8.0")
4342 :type '(repeat
4343 (list
4344 (string :tag "Marker character")
4345 (choice
4346 (face :tag "Font-lock-face")
4347 (plist :tag "Face property list"))
4348 (option (const verbatim)))))
4350 (defvar org-protecting-blocks '("src" "example" "export")
4351 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4352 This is needed for font-lock setup.")
4354 ;;; Functions and variables from their packages
4355 ;; Declared here to avoid compiler warnings
4356 (defvar mark-active)
4358 ;; Various packages
4359 (declare-function calc-eval "calc" (str &optional separator &rest args))
4360 (declare-function calendar-forward-day "cal-move" (arg))
4361 (declare-function calendar-goto-date "cal-move" (date))
4362 (declare-function calendar-goto-today "cal-move" ())
4363 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4364 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4365 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4366 (declare-function cdlatex-tab "ext:cdlatex" ())
4367 (declare-function dired-get-filename
4368 "dired"
4369 (&optional localp no-error-if-not-filep))
4370 (declare-function iswitchb-read-buffer
4371 "iswitchb"
4372 (prompt &optional
4373 default require-match _predicate start matches-set))
4374 (declare-function org-agenda-change-all-lines
4375 "org-agenda"
4376 (newhead hdmarker &optional fixface just-this))
4377 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4378 "org-agenda"
4379 (&optional end))
4380 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4381 (declare-function org-agenda-format-item
4382 "org-agenda"
4383 (extra txt &optional level category tags dotime
4384 remove-re habitp))
4385 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4386 (declare-function org-agenda-save-markers-for-cut-and-paste
4387 "org-agenda"
4388 (beg end))
4389 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4390 (declare-function org-agenda-skip "org-agenda" ())
4391 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4392 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4393 (declare-function org-indent-mode "org-indent" (&optional arg))
4394 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4395 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4396 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4397 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4398 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4399 (declare-function parse-time-string "parse-time" (string))
4401 (defvar align-mode-rules-list)
4402 (defvar calc-embedded-close-formula)
4403 (defvar calc-embedded-open-formula)
4404 (defvar calc-embedded-open-mode)
4405 (defvar font-lock-unfontify-region-function)
4406 (defvar iswitchb-temp-buflist)
4407 (defvar org-agenda-tags-todo-honor-ignore-options)
4408 (defvar remember-data-file)
4409 (defvar texmathp-why)
4411 ;;;###autoload
4412 (defun turn-on-orgtbl ()
4413 "Unconditionally turn on `orgtbl-mode'."
4414 (require 'org-table)
4415 (orgtbl-mode 1))
4417 (defun org-at-table-p (&optional table-type)
4418 "Non-nil if the cursor is inside an Org table.
4419 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4420 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4421 (or (not (derived-mode-p 'org-mode))
4422 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4423 (and e (or table-type
4424 (eq 'org (org-element-property :type e))))))))
4426 (defun org-at-table.el-p ()
4427 "Non-nil when point is at a table.el table."
4428 (and (org-match-line "[ \t]*[|+]")
4429 (let ((element (org-element-at-point)))
4430 (and (eq (org-element-type element) 'table)
4431 (eq (org-element-property :type element) 'table.el)))))
4433 (defun org-at-table-hline-p ()
4434 "Non-nil when point is inside a hline in a table.
4435 Assume point is already in a table."
4436 (org-match-line org-table-hline-regexp))
4438 (defun org-table-map-tables (function &optional quietly)
4439 "Apply FUNCTION to the start of all tables in the buffer."
4440 (org-with-wide-buffer
4441 (goto-char (point-min))
4442 (while (re-search-forward org-table-any-line-regexp nil t)
4443 (unless quietly
4444 (message "Mapping tables: %d%%"
4445 (floor (* 100.0 (point)) (buffer-size))))
4446 (beginning-of-line 1)
4447 (when (and (looking-at org-table-line-regexp)
4448 ;; Exclude tables in src/example/verbatim/clocktable blocks
4449 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4450 (save-excursion (funcall function))
4451 (or (looking-at org-table-line-regexp)
4452 (forward-char 1)))
4453 (re-search-forward org-table-any-border-regexp nil 1)))
4454 (unless quietly (message "Mapping tables: done")))
4456 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4457 (declare-function org-clock-update-mode-line "org-clock" ())
4458 (declare-function org-resolve-clocks "org-clock"
4459 (&optional also-non-dangling-p prompt last-valid))
4461 (defun org-at-TBLFM-p (&optional pos)
4462 "Non-nil when point (or POS) is in #+TBLFM line."
4463 (save-excursion
4464 (goto-char (or pos (point)))
4465 (beginning-of-line)
4466 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4467 (eq (org-element-type (org-element-at-point)) 'table))))
4469 (defvar org-clock-start-time)
4470 (defvar org-clock-marker (make-marker)
4471 "Marker recording the last clock-in.")
4472 (defvar org-clock-hd-marker (make-marker)
4473 "Marker recording the last clock-in, but the headline position.")
4474 (defvar org-clock-heading ""
4475 "The heading of the current clock entry.")
4476 (defun org-clock-is-active ()
4477 "Return the buffer where the clock is currently running.
4478 Return nil if no clock is running."
4479 (marker-buffer org-clock-marker))
4481 (defun org-check-running-clock ()
4482 "Check if the current buffer contains the running clock.
4483 If yes, offer to stop it and to save the buffer with the changes."
4484 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4485 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4486 (buffer-name))))
4487 (org-clock-out)
4488 (when (y-or-n-p "Save changed buffer?")
4489 (save-buffer))))
4491 (defun org-clocktable-try-shift (dir n)
4492 "Check if this line starts a clock table, if yes, shift the time block."
4493 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4494 (org-clocktable-shift dir n)))
4496 ;;;###autoload
4497 (defun org-clock-persistence-insinuate ()
4498 "Set up hooks for clock persistence."
4499 (require 'org-clock)
4500 (add-hook 'org-mode-hook 'org-clock-load)
4501 (add-hook 'kill-emacs-hook 'org-clock-save))
4503 (defgroup org-archive nil
4504 "Options concerning archiving in Org mode."
4505 :tag "Org Archive"
4506 :group 'org-structure)
4508 (defcustom org-archive-location "%s_archive::"
4509 "The location where subtrees should be archived.
4511 The value of this variable is a string, consisting of two parts,
4512 separated by a double-colon. The first part is a filename and
4513 the second part is a headline.
4515 When the filename is omitted, archiving happens in the same file.
4516 %s in the filename will be replaced by the current file
4517 name (without the directory part). Archiving to a different file
4518 is useful to keep archived entries from contributing to the
4519 Org Agenda.
4521 The archived entries will be filed as subtrees of the specified
4522 headline. When the headline is omitted, the subtrees are simply
4523 filed away at the end of the file, as top-level entries. Also in
4524 the heading you can use %s to represent the file name, this can be
4525 useful when using the same archive for a number of different files.
4527 Here are a few examples:
4528 \"%s_archive::\"
4529 If the current file is Projects.org, archive in file
4530 Projects.org_archive, as top-level trees. This is the default.
4532 \"::* Archived Tasks\"
4533 Archive in the current file, under the top-level headline
4534 \"* Archived Tasks\".
4536 \"~/org/archive.org::\"
4537 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4539 \"~/org/archive.org::* From %s\"
4540 Archive in file ~/org/archive.org (absolute path), under headlines
4541 \"From FILENAME\" where file name is the current file name.
4543 \"~/org/datetree.org::datetree/* Finished Tasks\"
4544 The \"datetree/\" string is special, signifying to archive
4545 items to the datetree. Items are placed in either the CLOSED
4546 date of the item, or the current date if there is no CLOSED date.
4547 The heading will be a subentry to the current date. There doesn't
4548 need to be a heading, but there always needs to be a slash after
4549 datetree. For example, to store archived items directly in the
4550 datetree, use \"~/org/datetree.org::datetree/\".
4552 \"basement::** Finished Tasks\"
4553 Archive in file ./basement (relative path), as level 3 trees
4554 below the level 2 heading \"** Finished Tasks\".
4556 You may set this option on a per-file basis by adding to the buffer a
4557 line like
4559 #+ARCHIVE: basement::** Finished Tasks
4561 You may also define it locally for a subtree by setting an ARCHIVE property
4562 in the entry. If such a property is found in an entry, or anywhere up
4563 the hierarchy, it will be used."
4564 :group 'org-archive
4565 :type 'string)
4567 (defcustom org-agenda-skip-archived-trees t
4568 "Non-nil means the agenda will skip any items located in archived trees.
4569 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4570 variable is no longer recommended, you should leave it at the value t.
4571 Instead, use the key `v' to cycle the archives-mode in the agenda."
4572 :group 'org-archive
4573 :group 'org-agenda-skip
4574 :type 'boolean)
4576 (defcustom org-columns-skip-archived-trees t
4577 "Non-nil means ignore archived trees when creating column view."
4578 :group 'org-archive
4579 :group 'org-properties
4580 :type 'boolean)
4582 (defcustom org-cycle-open-archived-trees nil
4583 "Non-nil means `org-cycle' will open archived trees.
4584 An archived tree is a tree marked with the tag ARCHIVE.
4585 When nil, archived trees will stay folded. You can still open them with
4586 normal outline commands like `show-all', but not with the cycling commands."
4587 :group 'org-archive
4588 :group 'org-cycle
4589 :type 'boolean)
4591 (defcustom org-sparse-tree-open-archived-trees nil
4592 "Non-nil means sparse tree construction shows matches in archived trees.
4593 When nil, matches in these trees are highlighted, but the trees are kept in
4594 collapsed state."
4595 :group 'org-archive
4596 :group 'org-sparse-trees
4597 :type 'boolean)
4599 (defcustom org-sparse-tree-default-date-type nil
4600 "The default date type when building a sparse tree.
4601 When this is nil, a date is a scheduled or a deadline timestamp.
4602 Otherwise, these types are allowed:
4604 all: all timestamps
4605 active: only active timestamps (<...>)
4606 inactive: only inactive timestamps ([...])
4607 scheduled: only scheduled timestamps
4608 deadline: only deadline timestamps"
4609 :type '(choice (const :tag "Scheduled or deadline" nil)
4610 (const :tag "All timestamps" all)
4611 (const :tag "Only active timestamps" active)
4612 (const :tag "Only inactive timestamps" inactive)
4613 (const :tag "Only scheduled timestamps" scheduled)
4614 (const :tag "Only deadline timestamps" deadline)
4615 (const :tag "Only closed timestamps" closed))
4616 :version "26.1"
4617 :package-version '(Org . "8.3")
4618 :group 'org-sparse-trees)
4620 (defun org-cycle-hide-archived-subtrees (state)
4621 "Re-hide all archived subtrees after a visibility state change.
4622 STATE should be one of the symbols listed in the docstring of
4623 `org-cycle-hook'."
4624 (when (and (not org-cycle-open-archived-trees)
4625 (not (memq state '(overview folded))))
4626 (save-excursion
4627 (let* ((globalp (memq state '(contents all)))
4628 (beg (if globalp (point-min) (point)))
4629 (end (if globalp (point-max) (org-end-of-subtree t))))
4630 (org-hide-archived-subtrees beg end)
4631 (goto-char beg)
4632 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4633 (message "%s" (substitute-command-keys
4634 "Subtree is archived and stays closed. Use \
4635 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4637 (defun org-force-cycle-archived ()
4638 "Cycle subtree even if it is archived."
4639 (interactive)
4640 (setq this-command 'org-cycle)
4641 (let ((org-cycle-open-archived-trees t))
4642 (call-interactively 'org-cycle)))
4644 (defun org-hide-archived-subtrees (beg end)
4645 "Re-hide all archived subtrees after a visibility state change."
4646 (org-with-wide-buffer
4647 (let ((case-fold-search nil)
4648 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4649 (goto-char beg)
4650 ;; Include headline point is currently on.
4651 (beginning-of-line)
4652 (while (and (< (point) end) (re-search-forward re end t))
4653 (when (member org-archive-tag (org-get-tags))
4654 (org-flag-subtree t)
4655 (org-end-of-subtree t))))))
4657 (declare-function outline-end-of-heading "outline" ())
4658 (declare-function outline-flag-region "outline" (from to flag))
4659 (defun org-flag-subtree (flag)
4660 (save-excursion
4661 (org-back-to-heading t)
4662 (outline-end-of-heading)
4663 (outline-flag-region (point)
4664 (progn (org-end-of-subtree t) (point))
4665 flag)))
4667 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4669 ;; Declare Column View Code
4671 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4672 (declare-function org-columns-compute "org-colview" (property))
4674 ;; Declare ID code
4676 (declare-function org-id-store-link "org-id")
4677 (declare-function org-id-locations-load "org-id")
4678 (declare-function org-id-locations-save "org-id")
4679 (defvar org-id-track-globally)
4681 ;;; Variables for pre-computed regular expressions, all buffer local
4683 (defvar-local org-todo-regexp nil
4684 "Matches any of the TODO state keywords.
4685 Since TODO keywords are case-sensitive, `case-fold-search' is
4686 expected to be bound to nil when matching against this regexp.")
4688 (defvar-local org-not-done-regexp nil
4689 "Matches any of the TODO state keywords except the last one.
4690 Since TODO keywords are case-sensitive, `case-fold-search' is
4691 expected to be bound to nil when matching against this regexp.")
4693 (defvar-local org-not-done-heading-regexp nil
4694 "Matches a TODO headline that is not done.
4695 Since TODO keywords are case-sensitive, `case-fold-search' is
4696 expected to be bound to nil when matching against this regexp.")
4698 (defvar-local org-todo-line-regexp nil
4699 "Matches a headline and puts TODO state into group 2 if present.
4700 Since TODO keywords are case-sensitive, `case-fold-search' is
4701 expected to be bound to nil when matching against this regexp.")
4703 (defvar-local org-complex-heading-regexp nil
4704 "Matches a headline and puts everything into groups:
4706 group 1: Stars
4707 group 2: The TODO keyword, maybe
4708 group 3: Priority cookie
4709 group 4: True headline
4710 group 5: Tags
4712 Since TODO keywords are case-sensitive, `case-fold-search' is
4713 expected to be bound to nil when matching against this regexp.")
4715 (defvar-local org-complex-heading-regexp-format nil
4716 "Printf format to make regexp to match an exact headline.
4717 This regexp will match the headline of any node which has the
4718 exact headline text that is put into the format, but may have any
4719 TODO state, priority and tags.")
4721 (defvar-local org-todo-line-tags-regexp nil
4722 "Matches a headline and puts TODO state into group 2 if present.
4723 Also put tags into group 4 if tags are present.")
4725 (defconst org-plain-time-of-day-regexp
4726 (concat
4727 "\\(\\<[012]?[0-9]"
4728 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4729 "\\(--?"
4730 "\\(\\<[012]?[0-9]"
4731 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4732 "\\)?")
4733 "Regular expression to match a plain time or time range.
4734 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4735 groups carry important information:
4736 0 the full match
4737 1 the first time, range or not
4738 8 the second time, if it is a range.")
4740 (defconst org-plain-time-extension-regexp
4741 (concat
4742 "\\(\\<[012]?[0-9]"
4743 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4744 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4745 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4746 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4747 groups carry important information:
4748 0 the full match
4749 7 hours of duration
4750 9 minutes of duration")
4752 (defconst org-stamp-time-of-day-regexp
4753 (concat
4754 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4755 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4756 "\\(--?"
4757 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4758 "Regular expression to match a timestamp time or time range.
4759 After a match, the following groups carry important information:
4760 0 the full match
4761 1 date plus weekday, for back referencing to make sure both times are on the same day
4762 2 the first time, range or not
4763 4 the second time, if it is a range.")
4765 (defconst org-startup-options
4766 '(("fold" org-startup-folded t)
4767 ("overview" org-startup-folded t)
4768 ("nofold" org-startup-folded nil)
4769 ("showall" org-startup-folded nil)
4770 ("showeverything" org-startup-folded showeverything)
4771 ("content" org-startup-folded content)
4772 ("indent" org-startup-indented t)
4773 ("noindent" org-startup-indented nil)
4774 ("hidestars" org-hide-leading-stars t)
4775 ("showstars" org-hide-leading-stars nil)
4776 ("odd" org-odd-levels-only t)
4777 ("oddeven" org-odd-levels-only nil)
4778 ("align" org-startup-align-all-tables t)
4779 ("noalign" org-startup-align-all-tables nil)
4780 ("shrink" org-startup-shrink-all-tables t)
4781 ("inlineimages" org-startup-with-inline-images t)
4782 ("noinlineimages" org-startup-with-inline-images nil)
4783 ("latexpreview" org-startup-with-latex-preview t)
4784 ("nolatexpreview" org-startup-with-latex-preview nil)
4785 ("customtime" org-display-custom-times t)
4786 ("logdone" org-log-done time)
4787 ("lognotedone" org-log-done note)
4788 ("nologdone" org-log-done nil)
4789 ("lognoteclock-out" org-log-note-clock-out t)
4790 ("nolognoteclock-out" org-log-note-clock-out nil)
4791 ("logrepeat" org-log-repeat state)
4792 ("lognoterepeat" org-log-repeat note)
4793 ("logdrawer" org-log-into-drawer t)
4794 ("nologdrawer" org-log-into-drawer nil)
4795 ("logstatesreversed" org-log-states-order-reversed t)
4796 ("nologstatesreversed" org-log-states-order-reversed nil)
4797 ("nologrepeat" org-log-repeat nil)
4798 ("logreschedule" org-log-reschedule time)
4799 ("lognotereschedule" org-log-reschedule note)
4800 ("nologreschedule" org-log-reschedule nil)
4801 ("logredeadline" org-log-redeadline time)
4802 ("lognoteredeadline" org-log-redeadline note)
4803 ("nologredeadline" org-log-redeadline nil)
4804 ("logrefile" org-log-refile time)
4805 ("lognoterefile" org-log-refile note)
4806 ("nologrefile" org-log-refile nil)
4807 ("fninline" org-footnote-define-inline t)
4808 ("nofninline" org-footnote-define-inline nil)
4809 ("fnlocal" org-footnote-section nil)
4810 ("fnauto" org-footnote-auto-label t)
4811 ("fnprompt" org-footnote-auto-label nil)
4812 ("fnconfirm" org-footnote-auto-label confirm)
4813 ("fnplain" org-footnote-auto-label plain)
4814 ("fnadjust" org-footnote-auto-adjust t)
4815 ("nofnadjust" org-footnote-auto-adjust nil)
4816 ("constcgs" constants-unit-system cgs)
4817 ("constSI" constants-unit-system SI)
4818 ("noptag" org-tag-persistent-alist nil)
4819 ("hideblocks" org-hide-block-startup t)
4820 ("nohideblocks" org-hide-block-startup nil)
4821 ("beamer" org-startup-with-beamer-mode t)
4822 ("entitiespretty" org-pretty-entities t)
4823 ("entitiesplain" org-pretty-entities nil))
4824 "Variable associated with STARTUP options for org-mode.
4825 Each element is a list of three items: the startup options (as written
4826 in the #+STARTUP line), the corresponding variable, and the value to set
4827 this variable to if the option is found. An optional forth element PUSH
4828 means to push this value onto the list in the variable.")
4830 (defcustom org-group-tags t
4831 "When non-nil (the default), use group tags.
4832 This can be turned on/off through `org-toggle-tags-groups'."
4833 :group 'org-tags
4834 :group 'org-startup
4835 :type 'boolean)
4837 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4839 (defun org-toggle-tags-groups ()
4840 "Toggle support for group tags.
4841 Support for group tags is controlled by the option
4842 `org-group-tags', which is non-nil by default."
4843 (interactive)
4844 (setq org-group-tags (not org-group-tags))
4845 (cond ((and (derived-mode-p 'org-agenda-mode)
4846 org-group-tags)
4847 (org-agenda-redo))
4848 ((derived-mode-p 'org-mode)
4849 (let ((org-inhibit-startup t)) (org-mode))))
4850 (message "Groups tags support has been turned %s"
4851 (if org-group-tags "on" "off")))
4853 (defun org-set-regexps-and-options (&optional tags-only)
4854 "Precompute regular expressions used in the current buffer.
4855 When optional argument TAGS-ONLY is non-nil, only compute tags
4856 related expressions."
4857 (when (derived-mode-p 'org-mode)
4858 (let ((alist (org--setup-collect-keywords
4859 (org-make-options-regexp
4860 (append '("FILETAGS" "TAGS" "SETUPFILE")
4861 (and (not tags-only)
4862 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4863 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4864 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4865 ;; Startup options. Get this early since it does change
4866 ;; behavior for other options (e.g., tags).
4867 (let ((startup (cdr (assq 'startup alist))))
4868 (dolist (option startup)
4869 (let ((entry (assoc-string option org-startup-options t)))
4870 (when entry
4871 (let ((var (nth 1 entry))
4872 (val (nth 2 entry)))
4873 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4874 (unless (listp (symbol-value var))
4875 (set (make-local-variable var) nil))
4876 (add-to-list var val)))))))
4877 (setq-local org-file-tags
4878 (mapcar #'org-add-prop-inherited
4879 (cdr (assq 'filetags alist))))
4880 (setq org-current-tag-alist
4881 (append org-tag-persistent-alist
4882 (let ((tags (cdr (assq 'tags alist))))
4883 (if tags (org-tag-string-to-alist tags)
4884 org-tag-alist))))
4885 (setq org-tag-groups-alist
4886 (org-tag-alist-to-groups org-current-tag-alist))
4887 (unless tags-only
4888 ;; File properties.
4889 (setq-local org-file-properties (cdr (assq 'property alist)))
4890 ;; Archive location.
4891 (let ((archive (cdr (assq 'archive alist))))
4892 (when archive (setq-local org-archive-location archive)))
4893 ;; Category.
4894 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4895 (when cat
4896 (setq-local org-category (intern cat))
4897 (setq-local org-file-properties
4898 (org--update-property-plist
4899 "CATEGORY" cat org-file-properties))))
4900 ;; Columns.
4901 (let ((column (cdr (assq 'columns alist))))
4902 (when column (setq-local org-columns-default-format column)))
4903 ;; Constants.
4904 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4905 ;; Link abbreviations.
4906 (let ((links (cdr (assq 'link alist))))
4907 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4908 ;; Priorities.
4909 (let ((priorities (cdr (assq 'priorities alist))))
4910 (when priorities
4911 (setq-local org-highest-priority (nth 0 priorities))
4912 (setq-local org-lowest-priority (nth 1 priorities))
4913 (setq-local org-default-priority (nth 2 priorities))))
4914 ;; Scripts.
4915 (let ((scripts (assq 'scripts alist)))
4916 (when scripts
4917 (setq-local org-use-sub-superscripts (cdr scripts))))
4918 ;; TODO keywords.
4919 (setq-local org-todo-kwd-alist nil)
4920 (setq-local org-todo-key-alist nil)
4921 (setq-local org-todo-key-trigger nil)
4922 (setq-local org-todo-keywords-1 nil)
4923 (setq-local org-done-keywords nil)
4924 (setq-local org-todo-heads nil)
4925 (setq-local org-todo-sets nil)
4926 (setq-local org-todo-log-states nil)
4927 (let ((todo-sequences
4928 (or (nreverse (cdr (assq 'todo alist)))
4929 (let ((d (default-value 'org-todo-keywords)))
4930 (if (not (stringp (car d))) d
4931 ;; XXX: Backward compatibility code.
4932 (list (cons org-todo-interpretation d)))))))
4933 (dolist (sequence todo-sequences)
4934 (let* ((sequence (or (run-hook-with-args-until-success
4935 'org-todo-setup-filter-hook sequence)
4936 sequence))
4937 (sequence-type (car sequence))
4938 (keywords (cdr sequence))
4939 (sep (member "|" keywords))
4940 names alist)
4941 (dolist (k (remove "|" keywords))
4942 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4944 (error "Invalid TODO keyword %s" k))
4945 (let ((name (match-string 1 k))
4946 (key (match-string 2 k))
4947 (log (org-extract-log-state-settings k)))
4948 (push name names)
4949 (push (cons name (and key (string-to-char key))) alist)
4950 (when log (push log org-todo-log-states))))
4951 (let* ((names (nreverse names))
4952 (done (if sep (org-remove-keyword-keys (cdr sep))
4953 (last names)))
4954 (head (car names))
4955 (tail (list sequence-type head (car done) (org-last done))))
4956 (add-to-list 'org-todo-heads head 'append)
4957 (push names org-todo-sets)
4958 (setq org-done-keywords (append org-done-keywords done nil))
4959 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4960 (setq org-todo-key-alist
4961 (append org-todo-key-alist
4962 (and alist
4963 (append '((:startgroup))
4964 (nreverse alist)
4965 '((:endgroup))))))
4966 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4967 (setq org-todo-sets (nreverse org-todo-sets)
4968 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4969 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4970 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4971 ;; Compute the regular expressions and other local variables.
4972 ;; Using `org-outline-regexp-bol' would complicate them much,
4973 ;; because of the fixed white space at the end of that string.
4974 (unless org-done-keywords
4975 (setq org-done-keywords
4976 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4977 (setq org-not-done-keywords
4978 (org-delete-all org-done-keywords
4979 (copy-sequence org-todo-keywords-1))
4980 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4981 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4982 org-not-done-heading-regexp
4983 (format org-heading-keyword-regexp-format org-not-done-regexp)
4984 org-todo-line-regexp
4985 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4986 org-complex-heading-regexp
4987 (concat "^\\(\\*+\\)"
4988 "\\(?: +" org-todo-regexp "\\)?"
4989 "\\(?: +\\(\\[#.\\]\\)\\)?"
4990 "\\(?: +\\(.*?\\)\\)??"
4991 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4992 "[ \t]*$")
4993 org-complex-heading-regexp-format
4994 (concat "^\\(\\*+\\)"
4995 "\\(?: +" org-todo-regexp "\\)?"
4996 "\\(?: +\\(\\[#.\\]\\)\\)?"
4997 "\\(?: +"
4998 ;; Stats cookies can be stuck to body.
4999 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5000 "\\(%s\\)"
5001 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5002 "\\)"
5003 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5004 "[ \t]*$")
5005 org-todo-line-tags-regexp
5006 (concat "^\\(\\*+\\)"
5007 "\\(?: +" org-todo-regexp "\\)?"
5008 "\\(?: +\\(.*?\\)\\)??"
5009 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5010 "[ \t]*$"))
5011 (org-compute-latex-and-related-regexp)))))
5013 (defun org--setup-collect-keywords (regexp &optional files alist)
5014 "Return setup keywords values as an alist.
5016 REGEXP matches a subset of setup keywords. FILES is a list of
5017 file names already visited. It is used to avoid circular setup
5018 files. ALIST, when non-nil, is the alist computed so far.
5020 Return value contains the following keys: `archive', `category',
5021 `columns', `constants', `filetags', `link', `priorities',
5022 `property', `scripts', `startup', `tags' and `todo'."
5023 (org-with-wide-buffer
5024 (goto-char (point-min))
5025 (let ((case-fold-search t))
5026 (while (re-search-forward regexp nil t)
5027 (let ((element (org-element-at-point)))
5028 (when (eq (org-element-type element) 'keyword)
5029 (let ((key (org-element-property :key element))
5030 (value (org-element-property :value element)))
5031 (cond
5032 ((equal key "ARCHIVE")
5033 (when (org-string-nw-p value)
5034 (push (cons 'archive value) alist)))
5035 ((equal key "CATEGORY") (push (cons 'category value) alist))
5036 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5037 ((equal key "CONSTANTS")
5038 (let* ((constants (assq 'constants alist))
5039 (store (cdr constants)))
5040 (dolist (pair (split-string value))
5041 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5042 pair)
5043 (let* ((name (match-string 1 pair))
5044 (value (match-string 2 pair))
5045 (old (assoc name store)))
5046 (if old (setcdr old value)
5047 (push (cons name value) store)))))
5048 (if constants (setcdr constants store)
5049 (push (cons 'constants store) alist))))
5050 ((equal key "FILETAGS")
5051 (when (org-string-nw-p value)
5052 (let ((old (assq 'filetags alist))
5053 (new (apply #'nconc
5054 (mapcar (lambda (x) (org-split-string x ":"))
5055 (split-string value)))))
5056 (if old (setcdr old (append new (cdr old)))
5057 (push (cons 'filetags new) alist)))))
5058 ((equal key "LINK")
5059 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5060 (let ((links (assq 'link alist))
5061 (pair (cons (match-string-no-properties 1 value)
5062 (match-string-no-properties 2 value))))
5063 (if links (push pair (cdr links))
5064 (push (list 'link pair) alist)))))
5065 ((equal key "OPTIONS")
5066 (when (and (org-string-nw-p value)
5067 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5068 (push (cons 'scripts (read (match-string 1 value))) alist)))
5069 ((equal key "PRIORITIES")
5070 (push (cons 'priorities
5071 (let ((prio (split-string value)))
5072 (if (< (length prio) 3) '(?A ?C ?B)
5073 (mapcar #'string-to-char prio))))
5074 alist))
5075 ((equal key "PROPERTY")
5076 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5077 (let* ((property (assq 'property alist))
5078 (value (org--update-property-plist
5079 (match-string-no-properties 1 value)
5080 (match-string-no-properties 2 value)
5081 (cdr property))))
5082 (if property (setcdr property value)
5083 (push (cons 'property value) alist)))))
5084 ((equal key "STARTUP")
5085 (let ((startup (assq 'startup alist)))
5086 (if startup
5087 (setcdr startup
5088 (append (cdr startup) (split-string value)))
5089 (push (cons 'startup (split-string value)) alist))))
5090 ((equal key "TAGS")
5091 (let ((tag-cell (assq 'tags alist)))
5092 (if tag-cell
5093 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5094 (push (cons 'tags value) alist))))
5095 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5096 (let ((todo (assq 'todo alist))
5097 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5098 (split-string value))))
5099 (if todo (push value (cdr todo))
5100 (push (list 'todo value) alist))))
5101 ((equal key "SETUPFILE")
5102 (unless buffer-read-only ; Do not check in Gnus messages.
5103 (let ((f (and (org-string-nw-p value)
5104 (expand-file-name
5105 (org-unbracket-string "\"" "\"" value)))))
5106 (when (and f (file-readable-p f) (not (member f files)))
5107 (with-temp-buffer
5108 (setq default-directory (file-name-directory f))
5109 (insert-file-contents f)
5110 (setq alist
5111 ;; Fake Org mode to benefit from cache
5112 ;; without recurring needlessly.
5113 (let ((major-mode 'org-mode))
5114 (org--setup-collect-keywords
5115 regexp (cons f files) alist)))))))))))))))
5116 alist)
5118 (defun org-tag-string-to-alist (s)
5119 "Return tag alist associated to string S.
5120 S is a value for TAGS keyword or produced with
5121 `org-tag-alist-to-string'. Return value is an alist suitable for
5122 `org-tag-alist' or `org-tag-persistent-alist'."
5123 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5124 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5125 "\\|{.+?}\\)" ; regular expression
5126 "\\(?:(\\(.\\))\\)?\\'"))
5127 alist group-flag)
5128 (dolist (tokens lines (cdr (nreverse alist)))
5129 (push '(:newline) alist)
5130 (while tokens
5131 (let ((token (pop tokens)))
5132 (pcase token
5133 ("{"
5134 (push '(:startgroup) alist)
5135 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5136 ("}"
5137 (push '(:endgroup) alist)
5138 (setq group-flag nil))
5139 ("["
5140 (push '(:startgrouptag) alist)
5141 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5142 ("]"
5143 (push '(:endgrouptag) alist)
5144 (setq group-flag nil))
5145 (":"
5146 (push '(:grouptags) alist))
5147 ((guard (string-match tag-re token))
5148 (let ((tag (match-string 1 token))
5149 (key (and (match-beginning 2)
5150 (string-to-char (match-string 2 token)))))
5151 ;; Push all tags in groups, no matter if they already
5152 ;; appear somewhere else in the list.
5153 (when (or group-flag (not (assoc tag alist)))
5154 (push (cons tag key) alist))))))))))
5156 (defun org-tag-alist-to-string (alist &optional skip-key)
5157 "Return tag string associated to ALIST.
5159 ALIST is an alist, as defined in `org-tag-alist' or
5160 `org-tag-persistent-alist', or produced with
5161 `org-tag-string-to-alist'.
5163 Return value is a string suitable as a value for \"TAGS\"
5164 keyword.
5166 When optional argument SKIP-KEY is non-nil, skip selection keys
5167 next to tags."
5168 (mapconcat (lambda (token)
5169 (pcase token
5170 (`(:startgroup) "{")
5171 (`(:endgroup) "}")
5172 (`(:startgrouptag) "[")
5173 (`(:endgrouptag) "]")
5174 (`(:grouptags) ":")
5175 (`(:newline) "\\n")
5176 ((and
5177 (guard (not skip-key))
5178 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5179 (format "%s(%c)" tag key))
5180 (`(,(and tag (pred stringp)) . ,_) tag)
5181 (_ (user-error "Invalid tag token: %S" token))))
5182 alist
5183 " "))
5185 (defun org-tag-alist-to-groups (alist)
5186 "Return group alist from tag ALIST.
5187 ALIST is an alist, as defined in `org-tag-alist' or
5188 `org-tag-persistent-alist', or produced with
5189 `org-tag-string-to-alist'. Return value is an alist following
5190 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5191 a string, summarizing TAGS, as a list of strings."
5192 (let (groups group-status current-group)
5193 (dolist (token alist (nreverse groups))
5194 (pcase token
5195 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5196 (`(,(or :endgroup :endgrouptag))
5197 (when (eq group-status 'append)
5198 (push (nreverse current-group) groups))
5199 (setq group-status nil))
5200 (`(:grouptags) (setq group-status 'append))
5201 ((and `(,tag . ,_) (guard group-status))
5202 (if (eq group-status 'append) (push tag current-group)
5203 (setq current-group (list tag))))
5204 (_ nil)))))
5206 (defvar org--file-cache (make-hash-table :test #'equal)
5207 "Hash table to store contents of files referenced via a URL.
5208 This is the cache of file URLs read using `org-file-contents'.")
5210 (defun org-reset-file-cache ()
5211 "Reset the cache of files downloaded by `org-file-contents'."
5212 (clrhash org--file-cache))
5214 (defun org-file-url-p (file)
5215 "Non-nil if FILE is a URL."
5216 (require 'ffap)
5217 (string-match-p ffap-url-regexp file))
5219 (defun org-file-contents (file &optional noerror nocache)
5220 "Return the contents of FILE, as a string.
5222 FILE can be a file name or URL.
5224 If FILE is a URL, download the contents. If the URL contents are
5225 already cached in the `org--file-cache' hash table, the download step
5226 is skipped.
5228 If NOERROR is non-nil, ignore the error when unable to read the FILE
5229 from file or URL.
5231 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5232 is available. This option applies only if FILE is a URL."
5233 (let* ((is-url (org-file-url-p file))
5234 (cache (and is-url
5235 (not nocache)
5236 (gethash file org--file-cache))))
5237 (cond
5238 (cache)
5239 (is-url
5240 (with-current-buffer (url-retrieve-synchronously file)
5241 (goto-char (point-min))
5242 ;; Move point to after the url-retrieve header.
5243 (search-forward "\n\n" nil :move)
5244 ;; Search for the success code only in the url-retrieve header.
5245 (if (save-excursion
5246 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5247 ;; Update the cache `org--file-cache' and return contents.
5248 (puthash file
5249 (buffer-substring-no-properties (point) (point-max))
5250 org--file-cache)
5251 (funcall (if noerror #'message #'user-error)
5252 "Unable to fetch file from %S"
5253 file))))
5255 (with-temp-buffer
5256 (condition-case nil
5257 (progn
5258 (insert-file-contents file)
5259 (buffer-string))
5260 (file-error
5261 (funcall (if noerror #'message #'user-error)
5262 "Unable to read file %S"
5263 file))))))))
5265 (defun org-extract-log-state-settings (x)
5266 "Extract the log state setting from a TODO keyword string.
5267 This will extract info from a string like \"WAIT(w@/!)\"."
5268 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5269 (let ((kw (match-string 1 x))
5270 (log1 (and (match-end 3) (match-string 3 x)))
5271 (log2 (and (match-end 4) (match-string 4 x))))
5272 (and (or log1 log2)
5273 (list kw
5274 (and log1 (if (equal log1 "!") 'time 'note))
5275 (and log2 (if (equal log2 "!") 'time 'note)))))))
5277 (defun org-remove-keyword-keys (list)
5278 "Remove a pair of parenthesis at the end of each string in LIST."
5279 (mapcar (lambda (x)
5280 (if (string-match "(.*)$" x)
5281 (substring x 0 (match-beginning 0))
5283 list))
5285 (defun org-assign-fast-keys (alist)
5286 "Assign fast keys to a keyword-key alist.
5287 Respect keys that are already there."
5288 (let (new e (alt ?0))
5289 (while (setq e (pop alist))
5290 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5291 (cdr e)) ;; Key already assigned.
5292 (push e new)
5293 (let ((clist (string-to-list (downcase (car e))))
5294 (used (append new alist)))
5295 (when (= (car clist) ?@)
5296 (pop clist))
5297 (while (and clist (rassoc (car clist) used))
5298 (pop clist))
5299 (unless clist
5300 (while (rassoc alt used)
5301 (cl-incf alt)))
5302 (push (cons (car e) (or (car clist) alt)) new))))
5303 (nreverse new)))
5305 ;;; Some variables used in various places
5307 (defvar org-window-configuration nil
5308 "Used in various places to store a window configuration.")
5309 (defvar org-selected-window nil
5310 "Used in various places to store a window configuration.")
5311 (defvar org-finish-function nil
5312 "Function to be called when `C-c C-c' is used.
5313 This is for getting out of special buffers like capture.")
5314 (defvar org-last-state)
5316 ;; Defined somewhere in this file, but used before definition.
5317 (defvar org-entities) ;; defined in org-entities.el
5318 (defvar org-struct-menu)
5319 (defvar org-org-menu)
5320 (defvar org-tbl-menu)
5322 ;;;; Define the Org mode
5324 ;; We use a before-change function to check if a table might need
5325 ;; an update.
5326 (defvar org-table-may-need-update t
5327 "Indicates that a table might need an update.
5328 This variable is set by `org-before-change-function'.
5329 `org-table-align' sets it back to nil.")
5330 (defun org-before-change-function (_beg _end)
5331 "Every change indicates that a table might need an update."
5332 (setq org-table-may-need-update t))
5333 (defvar org-mode-map)
5334 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5335 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5336 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5337 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5338 (defvar org-table-buffer-is-an nil)
5340 (defvar bidi-paragraph-direction)
5341 (defvar buffer-face-mode-face)
5343 (require 'outline)
5345 ;; Other stuff we need.
5346 (require 'time-date)
5347 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5348 (require 'easymenu)
5349 (autoload 'easy-menu-add "easymenu")
5350 (require 'overlay)
5352 ;; (require 'org-macs) moved higher up in the file before it is first used
5353 (require 'org-entities)
5354 ;; (require 'org-compat) moved higher up in the file before it is first used
5355 (require 'org-faces)
5356 (require 'org-list)
5357 (require 'org-pcomplete)
5358 (require 'org-src)
5359 (require 'org-footnote)
5360 (require 'org-macro)
5362 ;; babel
5363 (require 'ob)
5365 ;;;###autoload
5366 (define-derived-mode org-mode outline-mode "Org"
5367 "Outline-based notes management and organizer, alias
5368 \"Carsten's outline-mode for keeping track of everything.\"
5370 Org mode develops organizational tasks around a NOTES file which
5371 contains information about projects as plain text. Org mode is
5372 implemented on top of Outline mode, which is ideal to keep the content
5373 of large files well structured. It supports ToDo items, deadlines and
5374 time stamps, which magically appear in the diary listing of the Emacs
5375 calendar. Tables are easily created with a built-in table editor.
5376 Plain text URL-like links connect to websites, emails (VM), Usenet
5377 messages (Gnus), BBDB entries, and any files related to the project.
5378 For printing and sharing of notes, an Org file (or a part of it)
5379 can be exported as a structured ASCII or HTML file.
5381 The following commands are available:
5383 \\{org-mode-map}"
5385 ;; Get rid of Outline menus, they are not needed
5386 ;; Need to do this here because define-derived-mode sets up
5387 ;; the keymap so late. Still, it is a waste to call this each time
5388 ;; we switch another buffer into Org mode.
5389 (define-key org-mode-map [menu-bar headings] 'undefined)
5390 (define-key org-mode-map [menu-bar hide] 'undefined)
5391 (define-key org-mode-map [menu-bar show] 'undefined)
5393 (org-load-modules-maybe)
5394 (org-install-agenda-files-menu)
5395 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5396 (add-to-invisibility-spec '(org-hide-block . t))
5397 (setq-local outline-regexp org-outline-regexp)
5398 (setq-local outline-level 'org-outline-level)
5399 (setq bidi-paragraph-direction 'left-to-right)
5400 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5401 (unless org-display-table
5402 (setq org-display-table (make-display-table)))
5403 (set-display-table-slot
5404 org-display-table 4
5405 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5406 org-ellipsis)))
5407 (setq buffer-display-table org-display-table))
5408 (org-set-regexps-and-options)
5409 (org-set-font-lock-defaults)
5410 (when (and org-tag-faces (not org-tags-special-faces-re))
5411 ;; tag faces set outside customize.... force initialization.
5412 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5413 ;; Calc embedded
5414 (setq-local calc-embedded-open-mode "# ")
5415 ;; Modify a few syntax entries
5416 (modify-syntax-entry ?@ "w")
5417 (modify-syntax-entry ?\" "\"")
5418 (modify-syntax-entry ?\\ "_")
5419 (modify-syntax-entry ?~ "_")
5420 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5421 ;; Activate before-change-function
5422 (setq-local org-table-may-need-update t)
5423 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5424 ;; Check for running clock before killing a buffer
5425 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5426 ;; Initialize macros templates.
5427 (org-macro-initialize-templates)
5428 ;; Initialize radio targets.
5429 (org-update-radio-target-regexp)
5430 ;; Indentation.
5431 (setq-local indent-line-function 'org-indent-line)
5432 (setq-local indent-region-function 'org-indent-region)
5433 ;; Filling and auto-filling.
5434 (org-setup-filling)
5435 ;; Comments.
5436 (org-setup-comments-handling)
5437 ;; Initialize cache.
5438 (org-element-cache-reset)
5439 ;; Beginning/end of defun
5440 (setq-local beginning-of-defun-function 'org-backward-element)
5441 (setq-local end-of-defun-function
5442 (lambda ()
5443 (if (not (org-at-heading-p))
5444 (org-forward-element)
5445 (org-forward-element)
5446 (forward-char -1))))
5447 ;; Next error for sparse trees
5448 (setq-local next-error-function 'org-occur-next-match)
5449 ;; Make sure dependence stuff works reliably, even for users who set it
5450 ;; too late :-(
5451 (if org-enforce-todo-dependencies
5452 (add-hook 'org-blocker-hook
5453 'org-block-todo-from-children-or-siblings-or-parent)
5454 (remove-hook 'org-blocker-hook
5455 'org-block-todo-from-children-or-siblings-or-parent))
5456 (if org-enforce-todo-checkbox-dependencies
5457 (add-hook 'org-blocker-hook
5458 'org-block-todo-from-checkboxes)
5459 (remove-hook 'org-blocker-hook
5460 'org-block-todo-from-checkboxes))
5462 ;; Align options lines
5463 (setq-local
5464 align-mode-rules-list
5465 '((org-in-buffer-settings
5466 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5467 (modes . '(org-mode)))))
5469 ;; Imenu
5470 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5472 ;; Make isearch reveal context
5473 (setq-local outline-isearch-open-invisible-function
5474 (lambda (&rest _) (org-show-context 'isearch)))
5476 ;; Setup the pcomplete hooks
5477 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5478 (setq-local pcomplete-command-name-function 'org-command-at-point)
5479 (setq-local pcomplete-default-completion-function 'ignore)
5480 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5481 (setq-local pcomplete-termination-string "")
5482 (setq-local buffer-face-mode-face 'org-default)
5484 ;; If empty file that did not turn on Org mode automatically, make
5485 ;; it to.
5486 (when (and org-insert-mode-line-in-empty-file
5487 (called-interactively-p 'any)
5488 (= (point-min) (point-max)))
5489 (insert "# -*- mode: org -*-\n\n"))
5490 (unless org-inhibit-startup
5491 (org-unmodified
5492 (when org-startup-with-beamer-mode (org-beamer-mode))
5493 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5494 (org-table-map-tables
5495 (cond ((and org-startup-align-all-tables
5496 org-startup-shrink-all-tables)
5497 (lambda () (org-table-align) (org-table-shrink)))
5498 (org-startup-align-all-tables #'org-table-align)
5499 (t #'org-table-shrink))
5501 (when org-startup-with-inline-images (org-display-inline-images))
5502 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5503 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5504 (when org-startup-truncated (setq truncate-lines t))
5505 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5506 (org-refresh-effort-properties)))
5507 ;; Try to set `org-hide' face correctly.
5508 (let ((foreground (org-find-invisible-foreground)))
5509 (when foreground
5510 (set-face-foreground 'org-hide foreground))))
5512 ;; Update `customize-package-emacs-version-alist'
5513 (add-to-list 'customize-package-emacs-version-alist
5514 '(Org ("8.0" . "24.4")
5515 ("8.1" . "24.4")
5516 ("8.2" . "24.4")
5517 ("8.2.7" . "24.4")
5518 ("8.3" . "26.1")
5519 ("9.0" . "26.1")
5520 ("9.1" . "26.1")
5521 ("9.2" . "27.1")))
5523 (defvar org-mode-transpose-word-syntax-table
5524 (let ((st (make-syntax-table text-mode-syntax-table)))
5525 (dolist (c org-emphasis-alist st)
5526 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5528 (when (fboundp 'abbrev-table-put)
5529 (abbrev-table-put org-mode-abbrev-table
5530 :parents (list text-mode-abbrev-table)))
5532 (defun org-find-invisible-foreground ()
5533 (let ((candidates (remove
5534 "unspecified-bg"
5535 (nconc
5536 (list (face-background 'default)
5537 (face-background 'org-default))
5538 (mapcar
5539 (lambda (alist)
5540 (when (boundp alist)
5541 (cdr (assq 'background-color (symbol-value alist)))))
5542 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5543 (list (face-foreground 'org-hide))))))
5544 (car (remove nil candidates))))
5546 (defun org-current-time (&optional rounding-minutes past)
5547 "Current time, possibly rounded to ROUNDING-MINUTES.
5548 When ROUNDING-MINUTES is not an integer, fall back on the car of
5549 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5550 the rounding returns a past time."
5551 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5552 (car org-time-stamp-rounding-minutes)))
5553 (time (decode-time)) res)
5554 (if (< r 1)
5555 (current-time)
5556 (setq res
5557 (apply 'encode-time
5558 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5559 (nthcdr 2 time))))
5560 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5561 (seconds-to-time (- (float-time res) (* r 60)))
5562 res))))
5564 (defun org-today ()
5565 "Return today date, considering `org-extend-today-until'."
5566 (time-to-days
5567 (time-subtract (current-time)
5568 (list 0 (* 3600 org-extend-today-until) 0))))
5570 ;;;; Font-Lock stuff, including the activators
5572 (defvar org-mouse-map (make-sparse-keymap))
5573 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5574 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5575 (when org-mouse-1-follows-link
5576 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5577 (when org-tab-follows-link
5578 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5579 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5581 (require 'font-lock)
5583 (defconst org-non-link-chars "]\t\n\r<>")
5584 (defvar org-link-types-re nil
5585 "Matches a link that has a url-like prefix like \"http:\"")
5586 (defvar org-link-re-with-space nil
5587 "Matches a link with spaces, optional angular brackets around it.")
5588 (defvar org-link-re-with-space2 nil
5589 "Matches a link with spaces, optional angular brackets around it.")
5590 (defvar org-link-re-with-space3 nil
5591 "Matches a link with spaces, only for internal part in bracket links.")
5592 (defvar org-angle-link-re nil
5593 "Matches link with angular brackets, spaces are allowed.")
5594 (defvar org-plain-link-re nil
5595 "Matches plain link, without spaces.")
5596 (defvar org-bracket-link-regexp nil
5597 "Matches a link in double brackets.")
5598 (defvar org-bracket-link-analytic-regexp nil
5599 "Regular expression used to analyze links.
5600 Here is what the match groups contain after a match:
5601 1: http:
5602 2: http
5603 3: path
5604 4: [desc]
5605 5: desc")
5606 (defvar org-bracket-link-analytic-regexp++ nil
5607 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5608 (defvar org-any-link-re nil
5609 "Regular expression matching any link.")
5611 (defconst org-match-sexp-depth 3
5612 "Number of stacked braces for sub/superscript matching.")
5614 (defun org-create-multibrace-regexp (left right n)
5615 "Create a regular expression which will match a balanced sexp.
5616 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5617 as single character strings.
5618 The regexp returned will match the entire expression including the
5619 delimiters. It will also define a single group which contains the
5620 match except for the outermost delimiters. The maximum depth of
5621 stacked delimiters is N. Escaping delimiters is not possible."
5622 (let* ((nothing (concat "[^" left right "]*?"))
5623 (or "\\|")
5624 (re nothing)
5625 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5626 (while (> n 1)
5627 (setq n (1- n)
5628 re (concat re or next)
5629 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5630 (concat left "\\(" re "\\)" right)))
5632 (defconst org-match-substring-regexp
5633 (concat
5634 "\\(\\S-\\)\\([_^]\\)\\("
5635 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5636 "\\|"
5637 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5638 "\\|"
5639 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5640 "The regular expression matching a sub- or superscript.")
5642 (defconst org-match-substring-with-braces-regexp
5643 (concat
5644 "\\(\\S-\\)\\([_^]\\)"
5645 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5646 "The regular expression matching a sub- or superscript, forcing braces.")
5648 (defun org-make-link-regexps ()
5649 "Update the link regular expressions.
5650 This should be called after the variable `org-link-parameters' has changed."
5651 (let ((types-re (regexp-opt (org-link-types) t)))
5652 (setq org-link-types-re
5653 (concat "\\`" types-re ":")
5654 org-link-re-with-space
5655 (concat "<?" types-re ":"
5656 "\\([^" org-non-link-chars " ]"
5657 "[^" org-non-link-chars "]*"
5658 "[^" org-non-link-chars " ]\\)>?")
5659 org-link-re-with-space2
5660 (concat "<?" types-re ":"
5661 "\\([^" org-non-link-chars " ]"
5662 "[^\t\n\r]*"
5663 "[^" org-non-link-chars " ]\\)>?")
5664 org-link-re-with-space3
5665 (concat "<?" types-re ":"
5666 "\\([^" org-non-link-chars " ]"
5667 "[^\t\n\r]*\\)")
5668 org-angle-link-re
5669 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5670 types-re)
5671 org-plain-link-re
5672 (concat
5673 "\\<" types-re ":"
5674 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5675 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5676 org-bracket-link-regexp
5677 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5678 org-bracket-link-analytic-regexp
5679 (concat
5680 "\\[\\["
5681 "\\(" types-re ":\\)?"
5682 "\\([^]]+\\)"
5683 "\\]"
5684 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5685 "\\]")
5686 org-bracket-link-analytic-regexp++
5687 (concat
5688 "\\[\\["
5689 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5690 "\\([^]]+\\)"
5691 "\\]"
5692 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5693 "\\]")
5694 org-any-link-re
5695 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5696 org-angle-link-re "\\)\\|\\("
5697 org-plain-link-re "\\)"))))
5699 (org-make-link-regexps)
5701 (defvar org-emph-face nil)
5703 (defun org-do-emphasis-faces (limit)
5704 "Run through the buffer and emphasize strings."
5705 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5706 (car org-emphasis-regexp-components))))
5707 (catch :exit
5708 (while (re-search-forward quick-re limit t)
5709 (let* ((marker (match-string 2))
5710 (verbatim? (member marker '("~" "="))))
5711 (when (save-excursion
5712 (goto-char (match-beginning 0))
5713 (and
5714 ;; Do not match table hlines.
5715 (not (and (equal marker "+")
5716 (org-match-line
5717 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5718 ;; Do not match headline stars. Do not consider
5719 ;; stars of a headline as closing marker for bold
5720 ;; markup either.
5721 (not (and (equal marker "*")
5722 (save-excursion
5723 (forward-char)
5724 (skip-chars-backward "*")
5725 (looking-at-p org-outline-regexp-bol))))
5726 ;; Match full emphasis markup regexp.
5727 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5728 ;; Do not span over paragraph boundaries.
5729 (not (string-match-p org-element-paragraph-separate
5730 (match-string 2)))
5731 ;; Do not span over cells in table rows.
5732 (not (and (save-match-data (org-match-line "[ \t]*|"))
5733 (string-match-p "|" (match-string 4))))))
5734 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5735 (font-lock-prepend-text-property
5736 (match-beginning 2) (match-end 2) 'face face)
5737 (when verbatim?
5738 (org-remove-flyspell-overlays-in
5739 (match-beginning 0) (match-end 0)))
5740 (add-text-properties (match-beginning 2) (match-end 2)
5741 '(font-lock-multiline t org-emphasis t))
5742 (when org-hide-emphasis-markers
5743 (add-text-properties (match-end 4) (match-beginning 5)
5744 '(invisible org-link))
5745 (add-text-properties (match-beginning 3) (match-end 3)
5746 '(invisible org-link)))
5747 (throw :exit t))))))))
5749 (defun org-emphasize (&optional char)
5750 "Insert or change an emphasis, i.e. a font like bold or italic.
5751 If there is an active region, change that region to a new emphasis.
5752 If there is no region, just insert the marker characters and position
5753 the cursor between them.
5754 CHAR should be the marker character. If it is a space, it means to
5755 remove the emphasis of the selected region.
5756 If CHAR is not given (for example in an interactive call) it will be
5757 prompted for."
5758 (interactive)
5759 (let ((erc org-emphasis-regexp-components)
5760 (string "") beg end move s)
5761 (if (org-region-active-p)
5762 (setq beg (region-beginning)
5763 end (region-end)
5764 string (buffer-substring beg end))
5765 (setq move t))
5767 (unless char
5768 (message "Emphasis marker or tag: [%s]"
5769 (mapconcat #'car org-emphasis-alist ""))
5770 (setq char (read-char-exclusive)))
5771 (if (equal char ?\s)
5772 (setq s ""
5773 move nil)
5774 (unless (assoc (char-to-string char) org-emphasis-alist)
5775 (user-error "No such emphasis marker: \"%c\"" char))
5776 (setq s (char-to-string char)))
5777 (while (and (> (length string) 1)
5778 (equal (substring string 0 1) (substring string -1))
5779 (assoc (substring string 0 1) org-emphasis-alist))
5780 (setq string (substring string 1 -1)))
5781 (setq string (concat s string s))
5782 (when beg (delete-region beg end))
5783 (unless (or (bolp)
5784 (string-match (concat "[" (nth 0 erc) "\n]")
5785 (char-to-string (char-before (point)))))
5786 (insert " "))
5787 (unless (or (eobp)
5788 (string-match (concat "[" (nth 1 erc) "\n]")
5789 (char-to-string (char-after (point)))))
5790 (insert " ") (backward-char 1))
5791 (insert string)
5792 (and move (backward-char 1))))
5794 (defconst org-nonsticky-props
5795 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5797 (defsubst org-rear-nonsticky-at (pos)
5798 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5800 (defun org-activate-links (limit)
5801 "Add link properties to links.
5802 This includes angle, plain, and bracket links."
5803 (catch :exit
5804 (while (re-search-forward org-any-link-re limit t)
5805 (let* ((start (match-beginning 0))
5806 (end (match-end 0))
5807 (style (cond ((eq ?< (char-after start)) 'angle)
5808 ((eq ?\[ (char-after (1+ start))) 'bracket)
5809 (t 'plain))))
5810 (when (and (memq style org-highlight-links)
5811 ;; Do not confuse plain links with tags.
5812 (not (and (eq style 'plain)
5813 (let ((face (get-text-property
5814 (max (1- start) (point-min)) 'face)))
5815 (if (consp face) (memq 'org-tag face)
5816 (eq 'org-tag face))))))
5817 (let* ((link-object (save-excursion
5818 (goto-char start)
5819 (save-match-data (org-element-link-parser))))
5820 (link (org-element-property :raw-link link-object))
5821 (type (org-element-property :type link-object))
5822 (path (org-element-property :path link-object))
5823 (properties ;for link's visible part
5824 (list
5825 'face (pcase (org-link-get-parameter type :face)
5826 ((and (pred functionp) face) (funcall face path))
5827 ((and (pred facep) face) face)
5828 ((and (pred consp) face) face) ;anonymous
5829 (_ 'org-link))
5830 'mouse-face (or (org-link-get-parameter type :mouse-face)
5831 'highlight)
5832 'keymap (or (org-link-get-parameter type :keymap)
5833 org-mouse-map)
5834 'help-echo (pcase (org-link-get-parameter type :help-echo)
5835 ((and (pred stringp) echo) echo)
5836 ((and (pred functionp) echo) echo)
5837 (_ (concat "LINK: " link)))
5838 'htmlize-link (pcase (org-link-get-parameter type
5839 :htmlize-link)
5840 ((and (pred functionp) f) (funcall f))
5841 (_ `(:uri ,link)))
5842 'font-lock-multiline t)))
5843 (org-remove-flyspell-overlays-in start end)
5844 (org-rear-nonsticky-at end)
5845 (if (not (eq 'bracket style))
5846 (add-text-properties start end properties)
5847 ;; Handle invisible parts in bracket links.
5848 (remove-text-properties start end '(invisible nil))
5849 (let ((hidden
5850 (append `(invisible
5851 ,(or (org-link-get-parameter type :display)
5852 'org-link))
5853 properties))
5854 (visible-start (or (match-beginning 4) (match-beginning 2)))
5855 (visible-end (or (match-end 4) (match-end 2))))
5856 (add-text-properties start visible-start hidden)
5857 (add-text-properties visible-start visible-end properties)
5858 (add-text-properties visible-end end hidden)
5859 (org-rear-nonsticky-at visible-start)
5860 (org-rear-nonsticky-at visible-end)))
5861 (let ((f (org-link-get-parameter type :activate-func)))
5862 (when (functionp f)
5863 (funcall f start end path (eq style 'bracket))))
5864 (throw :exit t))))) ;signal success
5865 nil))
5867 (defun org-activate-code (limit)
5868 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5869 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5870 (remove-text-properties (match-beginning 0) (match-end 0)
5871 '(display t invisible t intangible t))
5874 (defcustom org-src-fontify-natively t
5875 "When non-nil, fontify code in code blocks.
5876 See also the `org-block' face."
5877 :type 'boolean
5878 :version "26.1"
5879 :package-version '(Org . "8.3")
5880 :group 'org-appearance
5881 :group 'org-babel)
5883 (defcustom org-allow-promoting-top-level-subtree nil
5884 "When non-nil, allow promoting a top level subtree.
5885 The leading star of the top level headline will be replaced
5886 by a #."
5887 :type 'boolean
5888 :version "24.1"
5889 :group 'org-appearance)
5891 (defun org-fontify-meta-lines-and-blocks (limit)
5892 (condition-case nil
5893 (org-fontify-meta-lines-and-blocks-1 limit)
5894 (error (message "org-mode fontification error in %S at %d"
5895 (current-buffer)
5896 (line-number-at-pos)))))
5898 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5899 "Fontify #+ lines and blocks."
5900 (let ((case-fold-search t))
5901 (when (re-search-forward
5902 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5903 limit t)
5904 (let ((beg (match-beginning 0))
5905 (block-start (match-end 0))
5906 (block-end nil)
5907 (lang (match-string 7))
5908 (beg1 (line-beginning-position 2))
5909 (dc1 (downcase (match-string 2)))
5910 (dc3 (downcase (match-string 3)))
5911 end end1 quoting block-type)
5912 (cond
5913 ((and (match-end 4) (equal dc3 "+begin"))
5914 ;; Truly a block
5915 (setq block-type (downcase (match-string 5))
5916 quoting (member block-type org-protecting-blocks))
5917 (when (re-search-forward
5918 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5919 nil t) ;; on purpose, we look further than LIMIT
5920 (setq end (min (point-max) (match-end 0))
5921 end1 (min (point-max) (1- (match-beginning 0))))
5922 (setq block-end (match-beginning 0))
5923 (when quoting
5924 (org-remove-flyspell-overlays-in beg1 end1)
5925 (remove-text-properties beg end
5926 '(display t invisible t intangible t)))
5927 (add-text-properties
5928 beg end '(font-lock-fontified t font-lock-multiline t))
5929 (add-text-properties beg beg1 '(face org-meta-line))
5930 (org-remove-flyspell-overlays-in beg beg1)
5931 (add-text-properties ; For end_src
5932 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5933 (org-remove-flyspell-overlays-in end1 end)
5934 (cond
5935 ((and lang (not (string= lang "")) org-src-fontify-natively)
5936 (org-src-font-lock-fontify-block lang block-start block-end)
5937 (add-text-properties beg1 block-end '(src-block t)))
5938 (quoting
5939 (add-text-properties beg1 (min (point-max) (1+ end1))
5940 (list 'face
5941 (list :inherit
5942 (let ((face-name
5943 (intern (format "org-block-%s" lang))))
5944 (append (and (facep face-name) (list face-name))
5945 '(org-block))))))) ; end of source block
5946 ((not org-fontify-quote-and-verse-blocks))
5947 ((string= block-type "quote")
5948 (add-face-text-property
5949 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5950 ((string= block-type "verse")
5951 (add-face-text-property
5952 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5953 (add-text-properties beg beg1 '(face org-block-begin-line))
5954 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5955 '(face org-block-end-line))
5957 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5958 (org-remove-flyspell-overlays-in
5959 (match-beginning 0)
5960 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5961 (add-text-properties
5962 beg (match-end 3)
5963 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5964 '(font-lock-fontified t invisible t)
5965 '(font-lock-fontified t face org-document-info-keyword)))
5966 (add-text-properties
5967 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5968 (if (string-equal dc1 "+title:")
5969 '(font-lock-fontified t face org-document-title)
5970 '(font-lock-fontified t face org-document-info))))
5971 ((string-prefix-p "+caption" dc1)
5972 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5973 (remove-text-properties (match-beginning 0) (match-end 0)
5974 '(display t invisible t intangible t))
5975 ;; Handle short captions.
5976 (save-excursion
5977 (beginning-of-line)
5978 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5979 (add-text-properties (line-beginning-position) (match-end 1)
5980 '(font-lock-fontified t face org-meta-line))
5981 (add-text-properties (match-end 0) (line-end-position)
5982 '(font-lock-fontified t face org-block))
5984 ((member dc3 '(" " ""))
5985 (org-remove-flyspell-overlays-in beg (match-end 0))
5986 (add-text-properties
5987 beg (match-end 0)
5988 '(font-lock-fontified t face font-lock-comment-face)))
5989 (t ;; just any other in-buffer setting, but not indented
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5991 (remove-text-properties (match-beginning 0) (match-end 0)
5992 '(display t invisible t intangible t))
5993 (add-text-properties beg (match-end 0)
5994 '(font-lock-fontified t face org-meta-line))
5995 t))))))
5997 (defun org-fontify-drawers (limit)
5998 "Fontify drawers."
5999 (when (re-search-forward org-drawer-regexp limit t)
6000 (add-text-properties
6001 (match-beginning 0) (match-end 0)
6002 '(font-lock-fontified t face org-special-keyword))
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6006 (defun org-fontify-macros (limit)
6007 "Fontify macros."
6008 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6009 (add-text-properties
6010 (match-beginning 0) (match-end 0)
6011 '(font-lock-fontified t face org-macro))
6012 (when org-hide-macro-markers
6013 (add-text-properties (match-end 2) (match-beginning 2)
6014 '(invisible t))
6015 (add-text-properties (match-beginning 1) (match-end 1)
6016 '(invisible t)))
6017 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6020 (defun org-activate-footnote-links (limit)
6021 "Add text properties for footnotes."
6022 (let ((fn (org-footnote-next-reference-or-definition limit)))
6023 (when fn
6024 (let* ((beg (nth 1 fn))
6025 (end (nth 2 fn))
6026 (label (car fn))
6027 (referencep (/= (line-beginning-position) beg)))
6028 (when (and referencep (nth 3 fn))
6029 (save-excursion
6030 (goto-char beg)
6031 (search-forward (or label "fn:"))
6032 (org-remove-flyspell-overlays-in beg (match-end 0))))
6033 (add-text-properties beg end
6034 (list 'mouse-face 'highlight
6035 'keymap org-mouse-map
6036 'help-echo
6037 (if referencep "Footnote reference"
6038 "Footnote definition")
6039 'font-lock-fontified t
6040 'font-lock-multiline t
6041 'face 'org-footnote))))))
6043 (defun org-activate-dates (limit)
6044 "Add text properties for dates."
6045 (when (and (re-search-forward org-tsr-regexp-both limit t)
6046 (not (equal (char-before (match-beginning 0)) 91)))
6047 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6048 (add-text-properties (match-beginning 0) (match-end 0)
6049 (list 'mouse-face 'highlight
6050 'keymap org-mouse-map))
6051 (org-rear-nonsticky-at (match-end 0))
6052 (when org-display-custom-times
6053 ;; If it's a date range, activate custom time for second date.
6054 (when (match-end 3)
6055 (org-display-custom-time (match-beginning 3) (match-end 3)))
6056 (org-display-custom-time (match-beginning 1) (match-end 1)))
6059 (defvar-local org-target-link-regexp nil
6060 "Regular expression matching radio targets in plain text.")
6062 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6063 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6064 border border border))
6065 "Regular expression matching a link target.")
6067 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6068 "Regular expression matching a radio target.")
6070 (defconst org-any-target-regexp
6071 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6072 "Regular expression matching any target.")
6074 (defun org-activate-target-links (limit)
6075 "Add text properties for target matches."
6076 (when org-target-link-regexp
6077 (let ((case-fold-search t))
6078 (when (re-search-forward org-target-link-regexp limit t)
6079 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6080 (add-text-properties (match-beginning 1) (match-end 1)
6081 (list 'mouse-face 'highlight
6082 'keymap org-mouse-map
6083 'help-echo "Radio target link"
6084 'org-linked-text t))
6085 (org-rear-nonsticky-at (match-end 1))
6086 t))))
6088 (defun org-update-radio-target-regexp ()
6089 "Find all radio targets in this file and update the regular expression.
6090 Also refresh fontification if needed."
6091 (interactive)
6092 (let ((old-regexp org-target-link-regexp)
6093 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6094 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6095 (targets
6096 (org-with-wide-buffer
6097 (goto-char (point-min))
6098 (let (rtn)
6099 (while (re-search-forward org-radio-target-regexp nil t)
6100 ;; Make sure point is really within the object.
6101 (backward-char)
6102 (let ((obj (org-element-context)))
6103 (when (eq (org-element-type obj) 'radio-target)
6104 (cl-pushnew (org-element-property :value obj) rtn
6105 :test #'equal))))
6106 rtn))))
6107 (setq org-target-link-regexp
6108 (and targets
6109 (concat before-re
6110 (mapconcat
6111 (lambda (x)
6112 (replace-regexp-in-string
6113 " +" "\\s-+" (regexp-quote x) t t))
6114 targets
6115 "\\|")
6116 after-re)))
6117 (unless (equal old-regexp org-target-link-regexp)
6118 ;; Clean-up cache.
6119 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6120 ((not org-target-link-regexp) old-regexp)
6122 (concat before-re
6123 (mapconcat
6124 (lambda (re)
6125 (substring re (length before-re)
6126 (- (length after-re))))
6127 (list old-regexp org-target-link-regexp)
6128 "\\|")
6129 after-re)))))
6130 (org-with-wide-buffer
6131 (goto-char (point-min))
6132 (while (re-search-forward regexp nil t)
6133 (org-element-cache-refresh (match-beginning 1)))))
6134 ;; Re fontify buffer.
6135 (when (memq 'radio org-highlight-links)
6136 (org-restart-font-lock)))))
6138 (defvar org-latex-and-related-regexp nil
6139 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6141 (defun org-compute-latex-and-related-regexp ()
6142 "Compute regular expression for LaTeX, entities and sub/superscript.
6143 Result depends on variable `org-highlight-latex-and-related'."
6144 (setq-local
6145 org-latex-and-related-regexp
6146 (let* ((re-sub
6147 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6148 ((eq org-use-sub-superscripts '{})
6149 (list org-match-substring-with-braces-regexp))
6150 (org-use-sub-superscripts (list org-match-substring-regexp))))
6151 (re-latex
6152 (when (memq 'latex org-highlight-latex-and-related)
6153 (let ((matchers (plist-get org-format-latex-options :matchers)))
6154 (delq nil
6155 (mapcar (lambda (x)
6156 (and (member (car x) matchers) (nth 1 x)))
6157 org-latex-regexps)))))
6158 (re-entities
6159 (when (memq 'entities org-highlight-latex-and-related)
6160 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6161 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6163 (defun org-do-latex-and-related (limit)
6164 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6165 LIMIT bounds the search for syntax to highlight. Stop at first
6166 highlighted object, if any. Return t if some highlighting was
6167 done, nil otherwise."
6168 (when (org-string-nw-p org-latex-and-related-regexp)
6169 (catch 'found
6170 (while (re-search-forward org-latex-and-related-regexp limit t)
6171 (unless
6172 (cl-some
6173 (lambda (f)
6174 (memq f '(org-code org-verbatim underline org-special-keyword)))
6175 (save-excursion
6176 (goto-char (1+ (match-beginning 0)))
6177 (face-at-point nil t)))
6178 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6179 '(?_ ?^))
6181 0)))
6182 (font-lock-prepend-text-property
6183 (+ offset (match-beginning 0)) (match-end 0)
6184 'face 'org-latex-and-related)
6185 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6186 '(font-lock-multiline t)))
6187 (throw 'found t)))
6188 nil)))
6190 (defun org-restart-font-lock ()
6191 "Restart `font-lock-mode', to force refontification."
6192 (when (and (boundp 'font-lock-mode) font-lock-mode)
6193 (font-lock-mode -1)
6194 (font-lock-mode 1)))
6196 (defun org-activate-tags (limit)
6197 (when (re-search-forward
6198 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6199 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6200 (add-text-properties (match-beginning 1) (match-end 1)
6201 (list 'mouse-face 'highlight
6202 'keymap org-mouse-map))
6203 (org-rear-nonsticky-at (match-end 1))
6206 (defun org-outline-level ()
6207 "Compute the outline level of the heading at point.
6209 If this is called at a normal headline, the level is the number
6210 of stars. Use `org-reduced-level' to remove the effect of
6211 `org-odd-levels'. Unlike to `org-current-level', this function
6212 takes into consideration inlinetasks."
6213 (org-with-wide-buffer
6214 (end-of-line)
6215 (if (re-search-backward org-outline-regexp-bol nil t)
6216 (1- (- (match-end 0) (match-beginning 0)))
6217 0)))
6219 (defvar org-font-lock-keywords nil)
6221 (defsubst org-re-property (property &optional literal allow-null value)
6222 "Return a regexp matching a PROPERTY line.
6224 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6225 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6226 non-nil, match properties even without a value.
6228 Match group 3 is set to the value when it exists. If there is no
6229 value and ALLOW-NULL is non-nil, it is set to the empty string.
6231 With optional argument VALUE, match only property lines with
6232 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6233 unless LITERAL is non-nil."
6234 (concat
6235 "^\\(?4:[ \t]*\\)"
6236 (format "\\(?1::\\(?2:%s\\):\\)"
6237 (if literal property (regexp-quote property)))
6238 (cond (value
6239 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6240 (if literal value (regexp-quote value))))
6241 (allow-null
6242 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6244 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6246 (defconst org-property-re
6247 (org-re-property "\\S-+" 'literal t)
6248 "Regular expression matching a property line.
6249 There are four matching groups:
6250 1: :PROPKEY: including the leading and trailing colon,
6251 2: PROPKEY without the leading and trailing colon,
6252 3: PROPVAL without leading or trailing spaces,
6253 4: the indentation of the current line,
6254 5: trailing whitespace.")
6256 (defvar org-font-lock-hook nil
6257 "Functions to be called for special font lock stuff.")
6259 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6261 (defvar org-font-lock-set-keywords-hook nil
6262 "Functions that can manipulate `org-font-lock-extra-keywords'.
6263 This is called after `org-font-lock-extra-keywords' is defined, but before
6264 it is installed to be used by font lock. This can be useful if something
6265 needs to be inserted at a specific position in the font-lock sequence.")
6267 (defun org-font-lock-hook (limit)
6268 "Run `org-font-lock-hook' within LIMIT."
6269 (run-hook-with-args 'org-font-lock-hook limit))
6271 (defun org-set-font-lock-defaults ()
6272 "Set font lock defaults for the current buffer."
6273 (let* ((em org-fontify-emphasized-text)
6274 (lk org-highlight-links)
6275 (org-font-lock-extra-keywords
6276 (list
6277 ;; Call the hook
6278 '(org-font-lock-hook)
6279 ;; Headlines
6280 `(,(if org-fontify-whole-heading-line
6281 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6282 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6283 (1 (org-get-level-face 1))
6284 (2 (org-get-level-face 2))
6285 (3 (org-get-level-face 3)))
6286 ;; Table lines
6287 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6288 (1 'org-table t))
6289 ;; Table internals
6290 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6291 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6292 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6293 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6294 ;; Drawers
6295 '(org-fontify-drawers)
6296 ;; Properties
6297 (list org-property-re
6298 '(1 'org-special-keyword t)
6299 '(3 'org-property-value t))
6300 ;; Link related fontification.
6301 '(org-activate-links)
6302 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6303 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6304 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6305 (when (memq 'footnote lk) '(org-activate-footnote-links))
6306 ;; Targets.
6307 (list org-any-target-regexp '(0 'org-target t))
6308 ;; Diary sexps.
6309 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6310 ;; Macro
6311 '(org-fontify-macros)
6312 ;; TODO keyword
6313 (list (format org-heading-keyword-regexp-format
6314 org-todo-regexp)
6315 '(2 (org-get-todo-face 2) t))
6316 ;; DONE
6317 (if org-fontify-done-headline
6318 (list (format org-heading-keyword-regexp-format
6319 (concat
6320 "\\(?:"
6321 (mapconcat 'regexp-quote org-done-keywords "\\|")
6322 "\\)"))
6323 '(2 'org-headline-done t))
6324 nil)
6325 ;; Priorities
6326 '(org-font-lock-add-priority-faces)
6327 ;; Tags
6328 '(org-font-lock-add-tag-faces)
6329 ;; Tags groups
6330 (when (and org-group-tags org-tag-groups-alist)
6331 (list (concat org-outline-regexp-bol ".+\\(:"
6332 (regexp-opt (mapcar 'car org-tag-groups-alist))
6333 ":\\).*$")
6334 '(1 'org-tag-group prepend)))
6335 ;; Special keywords
6336 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6337 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6338 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6339 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6340 ;; Emphasis
6341 (when em '(org-do-emphasis-faces))
6342 ;; Checkboxes
6343 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6344 1 'org-checkbox prepend)
6345 (when (cdr (assq 'checkbox org-list-automatic-rules))
6346 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6347 (0 (org-get-checkbox-statistics-face) t)))
6348 ;; Description list items
6349 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6350 1 'org-list-dt prepend)
6351 ;; ARCHIVEd headings
6352 (list (concat
6353 org-outline-regexp-bol
6354 "\\(.*:" org-archive-tag ":.*\\)")
6355 '(1 'org-archived prepend))
6356 ;; Specials
6357 '(org-do-latex-and-related)
6358 '(org-fontify-entities)
6359 '(org-raise-scripts)
6360 ;; Code
6361 '(org-activate-code (1 'org-code t))
6362 ;; COMMENT
6363 (list (format
6364 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6365 org-todo-regexp
6366 org-comment-string)
6367 '(9 'org-special-keyword t))
6368 ;; Blocks and meta lines
6369 '(org-fontify-meta-lines-and-blocks))))
6370 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6371 (run-hooks 'org-font-lock-set-keywords-hook)
6372 ;; Now set the full font-lock-keywords
6373 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6374 (setq-local font-lock-defaults
6375 '(org-font-lock-keywords t nil nil backward-paragraph))
6376 (kill-local-variable 'font-lock-keywords)
6377 nil))
6379 (defun org-toggle-pretty-entities ()
6380 "Toggle the composition display of entities as UTF8 characters."
6381 (interactive)
6382 (setq-local org-pretty-entities (not org-pretty-entities))
6383 (org-restart-font-lock)
6384 (if org-pretty-entities
6385 (message "Entities are now displayed as UTF8 characters")
6386 (save-restriction
6387 (widen)
6388 (decompose-region (point-min) (point-max))
6389 (message "Entities are now displayed as plain text"))))
6391 (defvar-local org-custom-properties-overlays nil
6392 "List of overlays used for custom properties.")
6394 (defun org-toggle-custom-properties-visibility ()
6395 "Display or hide properties in `org-custom-properties'."
6396 (interactive)
6397 (if org-custom-properties-overlays
6398 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6399 (setq org-custom-properties-overlays nil))
6400 (when org-custom-properties
6401 (org-with-wide-buffer
6402 (goto-char (point-min))
6403 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6404 (while (re-search-forward regexp nil t)
6405 (let ((end (cdr (save-match-data (org-get-property-block)))))
6406 (when (and end (< (point) end))
6407 ;; Hide first custom property in current drawer.
6408 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6409 (overlay-put o 'invisible t)
6410 (overlay-put o 'org-custom-property t)
6411 (push o org-custom-properties-overlays))
6412 ;; Hide additional custom properties in the same drawer.
6413 (while (re-search-forward regexp end t)
6414 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6415 (overlay-put o 'invisible t)
6416 (overlay-put o 'org-custom-property t)
6417 (push o org-custom-properties-overlays)))))
6418 ;; Each entry is limited to a single property drawer.
6419 (outline-next-heading)))))))
6421 (defun org-fontify-entities (limit)
6422 "Find an entity to fontify."
6423 (let (ee)
6424 (when org-pretty-entities
6425 (catch 'match
6426 ;; "\_ "-family is left out on purpose. Only the first one,
6427 ;; i.e., "\_ ", could be fontified anyway, and it would be
6428 ;; confusing when adding a second white space character.
6429 (while (re-search-forward
6430 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6431 limit t)
6432 (when (and (not (org-at-comment-p))
6433 (setq ee (org-entity-get (match-string 1)))
6434 (= (length (nth 6 ee)) 1))
6435 (let* ((end (if (equal (match-string 2) "{}")
6436 (match-end 2)
6437 (match-end 1))))
6438 (add-text-properties
6439 (match-beginning 0) end
6440 (list 'font-lock-fontified t))
6441 (compose-region (match-beginning 0) end
6442 (nth 6 ee) nil)
6443 (backward-char 1)
6444 (throw 'match t))))
6445 nil))))
6447 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6448 "Fontify string S like in Org mode."
6449 (with-temp-buffer
6450 (insert s)
6451 (let ((org-odd-levels-only odd-levels))
6452 (org-mode)
6453 (org-font-lock-ensure)
6454 (buffer-string))))
6456 (defvar org-m nil)
6457 (defvar org-l nil)
6458 (defvar org-f nil)
6459 (defun org-get-level-face (n)
6460 "Get the right face for match N in font-lock matching of headlines."
6461 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6462 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6463 (if org-cycle-level-faces
6464 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6465 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6466 (cond
6467 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6468 ((eq n 2) org-f)
6469 (t (unless org-level-color-stars-only org-f))))
6471 (defun org-face-from-face-or-color (context inherit face-or-color)
6472 "Create a face list that inherits INHERIT, but sets the foreground color.
6473 When FACE-OR-COLOR is not a string, just return it."
6474 (if (stringp face-or-color)
6475 (list :inherit inherit
6476 (cdr (assoc context org-faces-easy-properties))
6477 face-or-color)
6478 face-or-color))
6480 (defun org-get-todo-face (kwd)
6481 "Get the right face for a TODO keyword KWD.
6482 If KWD is a number, get the corresponding match group."
6483 (when (numberp kwd) (setq kwd (match-string kwd)))
6484 (or (org-face-from-face-or-color
6485 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6486 (and (member kwd org-done-keywords) 'org-done)
6487 'org-todo))
6489 (defun org-get-priority-face (priority)
6490 "Get the right face for PRIORITY.
6491 PRIORITY is a character."
6492 (or (org-face-from-face-or-color
6493 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6494 'org-priority))
6496 (defun org-get-tag-face (tag)
6497 "Get the right face for TAG.
6498 If TAG is a number, get the corresponding match group."
6499 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6500 (or (org-face-from-face-or-color
6501 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6502 'org-tag)))
6504 (defun org-font-lock-add-priority-faces (limit)
6505 "Add the special priority faces."
6506 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6507 (add-text-properties
6508 (match-beginning 1) (match-end 1)
6509 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6510 'font-lock-fontified t))))
6512 (defun org-font-lock-add-tag-faces (limit)
6513 "Add the special tag faces."
6514 (when (and org-tag-faces org-tags-special-faces-re)
6515 (while (re-search-forward org-tags-special-faces-re limit t)
6516 (add-text-properties (match-beginning 1) (match-end 1)
6517 (list 'face (org-get-tag-face 1)
6518 'font-lock-fontified t))
6519 (backward-char 1))))
6521 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6522 "Remove fontification and activation overlays from links."
6523 (font-lock-default-unfontify-region beg end)
6524 (let* ((buffer-undo-list t)
6525 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6526 (inhibit-modification-hooks t)
6527 deactivate-mark buffer-file-name buffer-file-truename)
6528 (decompose-region beg end)
6529 (remove-text-properties beg end
6530 '(mouse-face t keymap t org-linked-text t
6531 invisible t intangible t
6532 org-emphasis t))
6533 (org-remove-font-lock-display-properties beg end)))
6535 (defconst org-script-display '(((raise -0.3) (height 0.7))
6536 ((raise 0.3) (height 0.7))
6537 ((raise -0.5))
6538 ((raise 0.5)))
6539 "Display properties for showing superscripts and subscripts.")
6541 (defun org-remove-font-lock-display-properties (beg end)
6542 "Remove specific display properties that have been added by font lock.
6543 The will remove the raise properties that are used to show superscripts
6544 and subscripts."
6545 (let (next prop)
6546 (while (< beg end)
6547 (setq next (next-single-property-change beg 'display nil end)
6548 prop (get-text-property beg 'display))
6549 (when (member prop org-script-display)
6550 (put-text-property beg next 'display nil))
6551 (setq beg next))))
6553 (defun org-raise-scripts (limit)
6554 "Add raise properties to sub/superscripts."
6555 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6556 (re-search-forward
6557 (if (eq org-use-sub-superscripts t)
6558 org-match-substring-regexp
6559 org-match-substring-with-braces-regexp)
6560 limit t))
6561 (let* ((pos (point)) table-p comment-p
6562 (mpos (match-beginning 3))
6563 (emph-p (get-text-property mpos 'org-emphasis))
6564 (link-p (get-text-property mpos 'mouse-face))
6565 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6566 (goto-char (point-at-bol))
6567 (setq table-p (looking-at-p org-table-dataline-regexp)
6568 comment-p (looking-at-p "^[ \t]*#[ +]"))
6569 (goto-char pos)
6570 ;; Handle a_b^c
6571 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6572 (unless (or comment-p emph-p link-p keyw-p)
6573 (put-text-property (match-beginning 3) (match-end 0)
6574 'display
6575 (if (equal (char-after (match-beginning 2)) ?^)
6576 (nth (if table-p 3 1) org-script-display)
6577 (nth (if table-p 2 0) org-script-display)))
6578 (add-text-properties (match-beginning 2) (match-end 2)
6579 (list 'invisible t))
6580 (when (and (eq (char-after (match-beginning 3)) ?{)
6581 (eq (char-before (match-end 3)) ?}))
6582 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6583 (list 'invisible t))
6584 (add-text-properties (1- (match-end 3)) (match-end 3)
6585 (list 'invisible t))))
6586 t)))
6588 ;;;; Visibility cycling, including org-goto and indirect buffer
6590 ;;; Cycling
6592 (defvar-local org-cycle-global-status nil)
6593 (put 'org-cycle-global-status 'org-state t)
6594 (defvar-local org-cycle-subtree-status nil)
6595 (put 'org-cycle-subtree-status 'org-state t)
6597 (defvar org-inlinetask-min-level)
6599 ;;;###autoload
6600 (defun org-cycle (&optional arg)
6601 "TAB-action and visibility cycling for Org mode.
6603 This is the command invoked in Org mode by the `TAB' key. Its main
6604 purpose is outline visibility cycling, but it also invokes other actions
6605 in special contexts.
6607 When this function is called with a `\\[universal-argument]' prefix, rotate \
6608 the entire
6609 buffer through 3 states (global cycling)
6610 1. OVERVIEW: Show only top-level headlines.
6611 2. CONTENTS: Show all headlines of all levels, but no body text.
6612 3. SHOW ALL: Show everything.
6614 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6615 switch to the startup visibility,
6616 determined by the variable `org-startup-folded', and by any VISIBILITY
6617 properties in the buffer.
6619 With a `\\[universal-argument] \\[universal-argument] \
6620 \\[universal-argument]' prefix argument, show the entire buffer, including
6621 any drawers.
6623 When inside a table, re-align the table and move to the next field.
6625 When point is at the beginning of a headline, rotate the subtree started
6626 by this line through 3 different states (local cycling)
6627 1. FOLDED: Only the main headline is shown.
6628 2. CHILDREN: The main headline and the direct children are shown.
6629 From this state, you can move to one of the children
6630 and zoom in further.
6631 3. SUBTREE: Show the entire subtree, including body text.
6632 If there is no subtree, switch directly from CHILDREN to FOLDED.
6634 When point is at the beginning of an empty headline and the variable
6635 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6636 of the headline by demoting and promoting it to likely levels. This
6637 speeds up creation document structure by pressing `TAB' once or several
6638 times right after creating a new headline.
6640 When there is a numeric prefix, go up to a heading with level ARG, do
6641 a `show-subtree' and return to the previous cursor position. If ARG
6642 is negative, go up that many levels.
6644 When point is not at the beginning of a headline, execute the global
6645 binding for `TAB', which is re-indenting the line. See the option
6646 `org-cycle-emulate-tab' for details.
6648 As a special case, if point is at the beginning of the buffer and there is
6649 no headline in line 1, this function will act as if called with prefix arg
6650 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6651 prefix arg, but only
6652 if the variable `org-cycle-global-at-bob' is t."
6653 (interactive "P")
6654 (org-load-modules-maybe)
6655 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6656 (and org-cycle-level-after-item/entry-creation
6657 (or (org-cycle-level)
6658 (org-cycle-item-indentation))))
6659 (let* ((limit-level
6660 (or org-cycle-max-level
6661 (and (boundp 'org-inlinetask-min-level)
6662 org-inlinetask-min-level
6663 (1- org-inlinetask-min-level))))
6664 (nstars (and limit-level
6665 (if org-odd-levels-only
6666 (and limit-level (1- (* limit-level 2)))
6667 limit-level)))
6668 (org-outline-regexp
6669 (if (not (derived-mode-p 'org-mode))
6670 outline-regexp
6671 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6672 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6673 (not (looking-at org-outline-regexp))))
6674 (org-cycle-hook
6675 (if bob-special
6676 (delq 'org-optimize-window-after-visibility-change
6677 (copy-sequence org-cycle-hook))
6678 org-cycle-hook))
6679 (pos (point)))
6681 (cond
6683 ((equal arg '(16))
6684 (setq last-command 'dummy)
6685 (org-set-startup-visibility)
6686 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6688 ((equal arg '(64))
6689 (outline-show-all)
6690 (org-unlogged-message "Entire buffer visible, including drawers"))
6692 ((equal arg '(4)) (org-cycle-internal-global))
6694 ;; Try hiding block at point.
6695 ((org-hide-block-toggle-maybe))
6697 ;; Try cdlatex TAB completion
6698 ((org-try-cdlatex-tab))
6700 ;; Table: enter it or move to the next field.
6701 ((org-at-table-p 'any)
6702 (if (org-at-table.el-p)
6703 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6704 Use `\\[org-edit-special]' to edit table.el tables"))
6705 (if arg (org-table-edit-field t)
6706 (org-table-justify-field-maybe)
6707 (call-interactively 'org-table-next-field))))
6709 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6711 ;; Global cycling: delegate to `org-cycle-internal-global'.
6712 (bob-special (org-cycle-internal-global))
6714 ;; Drawers: delegate to `org-flag-drawer'.
6715 ((save-excursion
6716 (beginning-of-line 1)
6717 (looking-at org-drawer-regexp))
6718 (org-flag-drawer ; toggle block visibility
6719 (not (get-char-property (match-end 0) 'invisible))))
6721 ;; Show-subtree, ARG levels up from here.
6722 ((integerp arg)
6723 (save-excursion
6724 (org-back-to-heading)
6725 (outline-up-heading (if (< arg 0) (- arg)
6726 (- (funcall outline-level) arg)))
6727 (org-show-subtree)))
6729 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6730 ((and (featurep 'org-inlinetask)
6731 (org-inlinetask-at-task-p)
6732 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6733 (org-inlinetask-toggle-visibility))
6735 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6736 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6737 (save-excursion (move-beginning-of-line 1)
6738 (looking-at org-outline-regexp)))
6739 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6740 (org-cycle-internal-local))
6742 ;; From there: TAB emulation and template completion.
6743 (buffer-read-only (org-back-to-heading))
6745 ((run-hook-with-args-until-success
6746 'org-tab-after-check-for-cycling-hook))
6748 ((run-hook-with-args-until-success
6749 'org-tab-before-tab-emulation-hook))
6751 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6752 (or (not (bolp))
6753 (not (looking-at org-outline-regexp))))
6754 (call-interactively (global-key-binding "\t")))
6756 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6757 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6758 (or (and (eq org-cycle-emulate-tab 'white)
6759 (= (match-end 0) (point-at-eol)))
6760 (and (eq org-cycle-emulate-tab 'whitestart)
6761 (>= (match-end 0) pos))))
6763 (eq org-cycle-emulate-tab t))
6764 (call-interactively (global-key-binding "\t")))
6766 (t (save-excursion
6767 (org-back-to-heading)
6768 (org-cycle)))))))
6770 (defun org-cycle-internal-global ()
6771 "Do the global cycling action."
6772 ;; Hack to avoid display of messages for .org attachments in Gnus
6773 (let ((ga (string-match "\\*fontification" (buffer-name))))
6774 (cond
6775 ((and (eq last-command this-command)
6776 (eq org-cycle-global-status 'overview))
6777 ;; We just created the overview - now do table of contents
6778 ;; This can be slow in very large buffers, so indicate action
6779 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6780 (unless ga (org-unlogged-message "CONTENTS..."))
6781 (org-content)
6782 (unless ga (org-unlogged-message "CONTENTS...done"))
6783 (setq org-cycle-global-status 'contents)
6784 (run-hook-with-args 'org-cycle-hook 'contents))
6786 ((and (eq last-command this-command)
6787 (eq org-cycle-global-status 'contents))
6788 ;; We just showed the table of contents - now show everything
6789 (run-hook-with-args 'org-pre-cycle-hook 'all)
6790 (outline-show-all)
6791 (unless ga (org-unlogged-message "SHOW ALL"))
6792 (setq org-cycle-global-status 'all)
6793 (run-hook-with-args 'org-cycle-hook 'all))
6796 ;; Default action: go to overview
6797 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6798 (org-overview)
6799 (unless ga (org-unlogged-message "OVERVIEW"))
6800 (setq org-cycle-global-status 'overview)
6801 (run-hook-with-args 'org-cycle-hook 'overview)))))
6803 (defvar org-called-with-limited-levels nil
6804 "Non-nil when `org-with-limited-levels' is currently active.")
6806 (defun org-cycle-internal-local ()
6807 "Do the local cycling action."
6808 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6809 ;; First, determine end of headline (EOH), end of subtree or item
6810 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6811 (save-excursion
6812 (if (org-at-item-p)
6813 (progn
6814 (beginning-of-line)
6815 (setq struct (org-list-struct))
6816 (setq eoh (point-at-eol))
6817 (setq eos (org-list-get-item-end-before-blank (point) struct))
6818 (setq has-children (org-list-has-child-p (point) struct)))
6819 (org-back-to-heading)
6820 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6821 (setq eos (save-excursion (org-end-of-subtree t t)
6822 (when (bolp) (backward-char)) (point)))
6823 (setq has-children
6824 (or (save-excursion
6825 (let ((level (funcall outline-level)))
6826 (outline-next-heading)
6827 (and (org-at-heading-p t)
6828 (> (funcall outline-level) level))))
6829 (save-excursion
6830 (org-list-search-forward (org-item-beginning-re) eos t)))))
6831 ;; Determine end invisible part of buffer (EOL)
6832 (beginning-of-line 2)
6833 (while (and (not (eobp)) ;This is like `next-line'.
6834 (get-char-property (1- (point)) 'invisible))
6835 (goto-char (next-single-char-property-change (point) 'invisible))
6836 (and (eolp) (beginning-of-line 2)))
6837 (setq eol (point)))
6838 ;; Find out what to do next and set `this-command'
6839 (cond
6840 ((= eos eoh)
6841 ;; Nothing is hidden behind this heading
6842 (unless (org-before-first-heading-p)
6843 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6844 (org-unlogged-message "EMPTY ENTRY")
6845 (setq org-cycle-subtree-status nil)
6846 (save-excursion
6847 (goto-char eos)
6848 (outline-next-heading)
6849 (when (org-invisible-p) (org-flag-heading nil))))
6850 ((and (or (>= eol eos)
6851 (not (string-match "\\S-" (buffer-substring eol eos))))
6852 (or has-children
6853 (not (setq children-skipped
6854 org-cycle-skip-children-state-if-no-children))))
6855 ;; Entire subtree is hidden in one line: children view
6856 (unless (org-before-first-heading-p)
6857 (run-hook-with-args 'org-pre-cycle-hook 'children))
6858 (if (org-at-item-p)
6859 (org-list-set-item-visibility (point-at-bol) struct 'children)
6860 (org-show-entry)
6861 (org-with-limited-levels (org-show-children))
6862 (org-show-set-visibility 'canonical)
6863 ;; FIXME: This slows down the func way too much.
6864 ;; How keep drawers hidden in subtree anyway?
6865 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6866 ;; (org-cycle-hide-drawers 'subtree))
6868 ;; Fold every list in subtree to top-level items.
6869 (when (eq org-cycle-include-plain-lists 'integrate)
6870 (save-excursion
6871 (org-back-to-heading)
6872 (while (org-list-search-forward (org-item-beginning-re) eos t)
6873 (beginning-of-line 1)
6874 (let* ((struct (org-list-struct))
6875 (prevs (org-list-prevs-alist struct))
6876 (end (org-list-get-bottom-point struct)))
6877 (dolist (e (org-list-get-all-items (point) struct prevs))
6878 (org-list-set-item-visibility e struct 'folded))
6879 (goto-char (if (< end eos) end eos)))))))
6880 (org-unlogged-message "CHILDREN")
6881 (save-excursion
6882 (goto-char eos)
6883 (outline-next-heading)
6884 (when (org-invisible-p) (org-flag-heading nil)))
6885 (setq org-cycle-subtree-status 'children)
6886 (unless (org-before-first-heading-p)
6887 (run-hook-with-args 'org-cycle-hook 'children)))
6888 ((or children-skipped
6889 (and (eq last-command this-command)
6890 (eq org-cycle-subtree-status 'children)))
6891 ;; We just showed the children, or no children are there,
6892 ;; now show everything.
6893 (unless (org-before-first-heading-p)
6894 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6895 (outline-flag-region eoh eos nil)
6896 (org-unlogged-message
6897 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6898 (setq org-cycle-subtree-status 'subtree)
6899 (unless (org-before-first-heading-p)
6900 (run-hook-with-args 'org-cycle-hook 'subtree)))
6902 ;; Default action: hide the subtree.
6903 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6904 (outline-flag-region eoh eos t)
6905 (org-unlogged-message "FOLDED")
6906 (setq org-cycle-subtree-status 'folded)
6907 (unless (org-before-first-heading-p)
6908 (run-hook-with-args 'org-cycle-hook 'folded))))))
6910 ;;;###autoload
6911 (defun org-global-cycle (&optional arg)
6912 "Cycle the global visibility. For details see `org-cycle'.
6913 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6914 With a numeric prefix, show all headlines up to that level."
6915 (interactive "P")
6916 (let ((org-cycle-include-plain-lists
6917 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6918 (cond
6919 ((integerp arg)
6920 (outline-show-all)
6921 (outline-hide-sublevels arg)
6922 (setq org-cycle-global-status 'contents))
6923 ((equal arg '(4))
6924 (org-set-startup-visibility)
6925 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6927 (org-cycle '(4))))))
6929 (defun org-set-startup-visibility ()
6930 "Set the visibility required by startup options and properties."
6931 (cond
6932 ((eq org-startup-folded t)
6933 (org-overview))
6934 ((eq org-startup-folded 'content)
6935 (org-content))
6936 ((or (eq org-startup-folded 'showeverything)
6937 (eq org-startup-folded nil))
6938 (outline-show-all)))
6939 (unless (eq org-startup-folded 'showeverything)
6940 (when org-hide-block-startup (org-hide-block-all))
6941 (org-set-visibility-according-to-property 'no-cleanup)
6942 (org-cycle-hide-archived-subtrees 'all)
6943 (org-cycle-hide-drawers 'all)
6944 (org-cycle-show-empty-lines t)))
6946 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6947 "Switch subtree visibilities according to :VISIBILITY: property."
6948 (interactive)
6949 (org-with-wide-buffer
6950 (goto-char (point-min))
6951 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6952 (if (not (org-at-property-p)) (outline-next-heading)
6953 (let ((state (match-string 3)))
6954 (save-excursion
6955 (org-back-to-heading t)
6956 (outline-hide-subtree)
6957 (org-reveal)
6958 (cond
6959 ((equal state "folded")
6960 (outline-hide-subtree))
6961 ((equal state "children")
6962 (org-show-hidden-entry)
6963 (org-show-children))
6964 ((equal state "content")
6965 (save-excursion
6966 (save-restriction
6967 (org-narrow-to-subtree)
6968 (org-content))))
6969 ((member state '("all" "showall"))
6970 (outline-show-subtree)))))))
6971 (unless no-cleanup
6972 (org-cycle-hide-archived-subtrees 'all)
6973 (org-cycle-hide-drawers 'all)
6974 (org-cycle-show-empty-lines 'all))))
6976 ;; This function uses outline-regexp instead of the more fundamental
6977 ;; org-outline-regexp so that org-cycle-global works outside of Org
6978 ;; buffers, where outline-regexp is needed.
6979 (defun org-overview ()
6980 "Switch to overview mode, showing only top-level headlines.
6981 This shows all headlines with a level equal or greater than the level
6982 of the first headline in the buffer. This is important, because if the
6983 first headline is not level one, then (hide-sublevels 1) gives confusing
6984 results."
6985 (interactive)
6986 (save-excursion
6987 (let ((level
6988 (save-excursion
6989 (goto-char (point-min))
6990 (when (re-search-forward (concat "^" outline-regexp) nil t)
6991 (goto-char (match-beginning 0))
6992 (funcall outline-level)))))
6993 (and level (outline-hide-sublevels level)))))
6995 (defun org-content (&optional arg)
6996 "Show all headlines in the buffer, like a table of contents.
6997 With numerical argument N, show content up to level N."
6998 (interactive "P")
6999 (org-overview)
7000 (save-excursion
7001 ;; Visit all headings and show their offspring
7002 (and (integerp arg) (org-overview))
7003 (goto-char (point-max))
7004 (catch 'exit
7005 (while (and (progn (condition-case nil
7006 (outline-previous-visible-heading 1)
7007 (error (goto-char (point-min))))
7009 (looking-at org-outline-regexp))
7010 (if (integerp arg)
7011 (org-show-children (1- arg))
7012 (outline-show-branches))
7013 (when (bobp) (throw 'exit nil))))))
7015 (defun org-optimize-window-after-visibility-change (state)
7016 "Adjust the window after a change in outline visibility.
7017 This function is the default value of the hook `org-cycle-hook'."
7018 (when (get-buffer-window (current-buffer))
7019 (cond
7020 ((eq state 'content) nil)
7021 ((eq state 'all) nil)
7022 ((eq state 'folded) nil)
7023 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7024 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7026 (defun org-remove-empty-overlays-at (pos)
7027 "Remove outline overlays that do not contain non-white stuff."
7028 (dolist (o (overlays-at pos))
7029 (and (eq 'outline (overlay-get o 'invisible))
7030 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7031 (overlay-end o))))
7032 (delete-overlay o))))
7034 (defun org-clean-visibility-after-subtree-move ()
7035 "Fix visibility issues after moving a subtree."
7036 ;; First, find a reasonable region to look at:
7037 ;; Start two siblings above, end three below
7038 (let* ((beg (save-excursion
7039 (and (org-get-last-sibling)
7040 (org-get-last-sibling))
7041 (point)))
7042 (end (save-excursion
7043 (and (org-get-next-sibling)
7044 (org-get-next-sibling)
7045 (org-get-next-sibling))
7046 (if (org-at-heading-p)
7047 (point-at-eol)
7048 (point))))
7049 (level (looking-at "\\*+"))
7050 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7051 (save-excursion
7052 (save-restriction
7053 (narrow-to-region beg end)
7054 (when re
7055 ;; Properly fold already folded siblings
7056 (goto-char (point-min))
7057 (while (re-search-forward re nil t)
7058 (when (and (not (org-invisible-p))
7059 (save-excursion
7060 (goto-char (point-at-eol)) (org-invisible-p)))
7061 (outline-hide-entry))))
7062 (org-cycle-show-empty-lines 'overview)
7063 (org-cycle-hide-drawers 'overview)))))
7065 (defun org-cycle-show-empty-lines (state)
7066 "Show empty lines above all visible headlines.
7067 The region to be covered depends on STATE when called through
7068 `org-cycle-hook'. Lisp program can use t for STATE to get the
7069 entire buffer covered. Note that an empty line is only shown if there
7070 are at least `org-cycle-separator-lines' empty lines before the headline."
7071 (when (/= org-cycle-separator-lines 0)
7072 (save-excursion
7073 (let* ((n (abs org-cycle-separator-lines))
7074 (re (cond
7075 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7076 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7077 (t (let ((ns (number-to-string (- n 2))))
7078 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7079 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7080 beg end)
7081 (cond
7082 ((memq state '(overview contents t))
7083 (setq beg (point-min) end (point-max)))
7084 ((memq state '(children folded))
7085 (setq beg (point)
7086 end (progn (org-end-of-subtree t t)
7087 (line-beginning-position 2)))))
7088 (when beg
7089 (goto-char beg)
7090 (while (re-search-forward re end t)
7091 (unless (get-char-property (match-end 1) 'invisible)
7092 (let ((e (match-end 1))
7093 (b (if (>= org-cycle-separator-lines 0)
7094 (match-beginning 1)
7095 (save-excursion
7096 (goto-char (match-beginning 0))
7097 (skip-chars-backward " \t\n")
7098 (line-end-position)))))
7099 (outline-flag-region b e nil))))))))
7100 ;; Never hide empty lines at the end of the file.
7101 (save-excursion
7102 (goto-char (point-max))
7103 (outline-previous-heading)
7104 (outline-end-of-heading)
7105 (when (and (looking-at "[ \t\n]+")
7106 (= (match-end 0) (point-max)))
7107 (outline-flag-region (point) (match-end 0) nil))))
7109 (defun org-show-empty-lines-in-parent ()
7110 "Move to the parent and re-show empty lines before visible headlines."
7111 (save-excursion
7112 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7113 (org-cycle-show-empty-lines context))))
7115 (defun org-files-list ()
7116 "Return `org-agenda-files' list, plus all open Org files.
7117 This is useful for operations that need to scan all of a user's
7118 open and agenda-wise Org files."
7119 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7120 (dolist (buf (buffer-list))
7121 (with-current-buffer buf
7122 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7123 (cl-pushnew (expand-file-name (buffer-file-name)) files
7124 :test #'equal))))
7125 files))
7127 (defsubst org-entry-beginning-position ()
7128 "Return the beginning position of the current entry."
7129 (save-excursion (org-back-to-heading t) (point)))
7131 (defsubst org-entry-end-position ()
7132 "Return the end position of the current entry."
7133 (save-excursion (outline-next-heading) (point)))
7135 (defun org-cycle-hide-drawers (state &optional exceptions)
7136 "Re-hide all drawers after a visibility state change.
7137 STATE should be one of the symbols listed in the docstring of
7138 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7139 a list of strings specifying which drawers should not be hidden."
7140 (when (and (derived-mode-p 'org-mode)
7141 (not (memq state '(overview folded contents))))
7142 (save-excursion
7143 (let* ((globalp (eq state 'all))
7144 (beg (if globalp (point-min) (point)))
7145 (end (if globalp (point-max)
7146 (if (eq state 'children)
7147 (save-excursion (outline-next-heading) (point))
7148 (org-end-of-subtree t)))))
7149 (goto-char beg)
7150 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7151 (unless (member-ignore-case (match-string 1) exceptions)
7152 (let ((drawer (org-element-at-point)))
7153 (when (memq (org-element-type drawer) '(drawer property-drawer))
7154 (org-flag-drawer t drawer)
7155 ;; Make sure to skip drawer entirely or we might flag
7156 ;; it another time when matching its ending line with
7157 ;; `org-drawer-regexp'.
7158 (goto-char (org-element-property :end drawer))))))))))
7160 (defun org-flag-drawer (flag &optional element)
7161 "When FLAG is non-nil, hide the drawer we are at.
7162 Otherwise make it visible. When optional argument ELEMENT is
7163 a parsed drawer, as returned by `org-element-at-point', hide or
7164 show that drawer instead."
7165 (let ((drawer (or element
7166 (and (save-excursion
7167 (beginning-of-line)
7168 (looking-at-p org-drawer-regexp))
7169 (org-element-at-point)))))
7170 (when (memq (org-element-type drawer) '(drawer property-drawer))
7171 (let ((post (org-element-property :post-affiliated drawer)))
7172 (save-excursion
7173 (outline-flag-region
7174 (progn (goto-char post) (line-end-position))
7175 (progn (goto-char (org-element-property :end drawer))
7176 (skip-chars-backward " \r\t\n")
7177 (line-end-position))
7178 flag))
7179 ;; When the drawer is hidden away, make sure point lies in
7180 ;; a visible part of the buffer.
7181 (when (and flag (> (line-beginning-position) post))
7182 (goto-char post))))))
7184 (defun org-subtree-end-visible-p ()
7185 "Is the end of the current subtree visible?"
7186 (pos-visible-in-window-p
7187 (save-excursion (org-end-of-subtree t) (point))))
7189 (defun org-first-headline-recenter ()
7190 "Move cursor to the first headline and recenter the headline."
7191 (let ((window (get-buffer-window)))
7192 (when window
7193 (goto-char (point-min))
7194 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7195 (set-window-start window (line-beginning-position))))))
7197 ;;; Saving and restoring visibility
7199 (defun org-outline-overlay-data (&optional use-markers)
7200 "Return a list of the locations of all outline overlays.
7201 These are overlays with the `invisible' property value `outline'.
7202 The return value is a list of cons cells, with start and stop
7203 positions for each overlay.
7204 If USE-MARKERS is set, return the positions as markers."
7205 (let (beg end)
7206 (org-with-wide-buffer
7207 (delq nil
7208 (mapcar (lambda (o)
7209 (when (eq (overlay-get o 'invisible) 'outline)
7210 (setq beg (overlay-start o)
7211 end (overlay-end o))
7212 (and beg end (> end beg)
7213 (if use-markers
7214 (cons (copy-marker beg)
7215 (copy-marker end t))
7216 (cons beg end)))))
7217 (overlays-in (point-min) (point-max)))))))
7219 (defun org-set-outline-overlay-data (data)
7220 "Create visibility overlays for all positions in DATA.
7221 DATA should have been made by `org-outline-overlay-data'."
7222 (org-with-wide-buffer
7223 (outline-show-all)
7224 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7226 ;;; Folding of blocks
7228 (defvar-local org-hide-block-overlays nil
7229 "Overlays hiding blocks.")
7231 (defun org-block-map (function &optional start end)
7232 "Call FUNCTION at the head of all source blocks in the current buffer.
7233 Optional arguments START and END can be used to limit the range."
7234 (let ((start (or start (point-min)))
7235 (end (or end (point-max))))
7236 (save-excursion
7237 (goto-char start)
7238 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7239 (save-excursion
7240 (save-match-data
7241 (goto-char (match-beginning 0))
7242 (funcall function)))))))
7244 (defun org-hide-block-toggle-all ()
7245 "Toggle the visibility of all blocks in the current buffer."
7246 (org-block-map 'org-hide-block-toggle))
7248 (defun org-hide-block-all ()
7249 "Fold all blocks in the current buffer."
7250 (interactive)
7251 (org-show-block-all)
7252 (org-block-map 'org-hide-block-toggle-maybe))
7254 (defun org-show-block-all ()
7255 "Unfold all blocks in the current buffer."
7256 (interactive)
7257 (mapc #'delete-overlay org-hide-block-overlays)
7258 (setq org-hide-block-overlays nil))
7260 (defun org-hide-block-toggle-maybe ()
7261 "Toggle visibility of block at point.
7262 Unlike to `org-hide-block-toggle', this function does not throw
7263 an error. Return a non-nil value when toggling is successful."
7264 (interactive)
7265 (ignore-errors (org-hide-block-toggle)))
7267 (defun org-hide-block-toggle (&optional force)
7268 "Toggle the visibility of the current block.
7269 When optional argument FORCE is `off', make block visible. If it
7270 is non-nil, hide it unconditionally. Throw an error when not at
7271 a block. Return a non-nil value when toggling is successful."
7272 (interactive)
7273 (let ((element (org-element-at-point)))
7274 (unless (memq (org-element-type element)
7275 '(center-block comment-block dynamic-block example-block
7276 export-block quote-block special-block
7277 src-block verse-block))
7278 (user-error "Not at a block"))
7279 (let* ((start (save-excursion
7280 (goto-char (org-element-property :post-affiliated element))
7281 (line-end-position)))
7282 (end (save-excursion
7283 (goto-char (org-element-property :end element))
7284 (skip-chars-backward " \r\t\n")
7285 (line-end-position)))
7286 (overlays (overlays-at start)))
7287 (cond
7288 ;; Do nothing when not before or at the block opening line or
7289 ;; at the block closing line.
7290 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7291 ((and (not (eq force 'off))
7292 (not (memq t (mapcar
7293 (lambda (o)
7294 (eq (overlay-get o 'invisible) 'org-hide-block))
7295 overlays))))
7296 (let ((ov (make-overlay start end)))
7297 (overlay-put ov 'invisible 'org-hide-block)
7298 ;; Make the block accessible to `isearch'.
7299 (overlay-put
7300 ov 'isearch-open-invisible
7301 (lambda (ov)
7302 (when (memq ov org-hide-block-overlays)
7303 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7304 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7305 (delete-overlay ov))))
7306 (push ov org-hide-block-overlays)
7307 ;; When the block is hidden away, make sure point is left in
7308 ;; a visible part of the buffer.
7309 (when (> (line-beginning-position) start)
7310 (goto-char start)
7311 (beginning-of-line))
7312 ;; Signal successful toggling.
7314 ((or (not force) (eq force 'off))
7315 (dolist (ov overlays t)
7316 (when (memq ov org-hide-block-overlays)
7317 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7318 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7319 (delete-overlay ov))))))))
7321 ;; Remove overlays when changing major mode
7322 (add-hook 'org-mode-hook
7323 (lambda () (add-hook 'change-major-mode-hook
7324 'org-show-block-all 'append 'local)))
7326 ;;; Indirect buffer display of subtrees
7328 (defvar org-indirect-dedicated-frame nil
7329 "This is the frame being used for indirect tree display.")
7330 (defvar org-last-indirect-buffer nil)
7332 (defun org-tree-to-indirect-buffer (&optional arg)
7333 "Create indirect buffer and narrow it to current subtree.
7335 With a numerical prefix ARG, go up to this level and then take that tree.
7336 If ARG is negative, go up that many levels.
7338 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7339 indirect buffer previously made with this command, to avoid proliferation of
7340 indirect buffers. However, when you call the command with a \
7341 `\\[universal-argument]' prefix, or
7342 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7343 so that you can work with several indirect buffers at the same time. If
7344 `org-indirect-buffer-display' is `dedicated-frame', the \
7345 `\\[universal-argument]' prefix also
7346 requests that a new frame be made for the new buffer, so that the dedicated
7347 frame is not changed."
7348 (interactive "P")
7349 (let ((cbuf (current-buffer))
7350 (cwin (selected-window))
7351 (pos (point))
7352 beg end level heading ibuf)
7353 (save-excursion
7354 (org-back-to-heading t)
7355 (when (numberp arg)
7356 (setq level (org-outline-level))
7357 (when (< arg 0) (setq arg (+ level arg)))
7358 (while (> (setq level (org-outline-level)) arg)
7359 (org-up-heading-safe)))
7360 (setq beg (point)
7361 heading (org-get-heading 'no-tags))
7362 (org-end-of-subtree t t)
7363 (when (org-at-heading-p) (backward-char 1))
7364 (setq end (point)))
7365 (when (and (buffer-live-p org-last-indirect-buffer)
7366 (not (eq org-indirect-buffer-display 'new-frame))
7367 (not arg))
7368 (kill-buffer org-last-indirect-buffer))
7369 (setq ibuf (org-get-indirect-buffer cbuf heading)
7370 org-last-indirect-buffer ibuf)
7371 (cond
7372 ((or (eq org-indirect-buffer-display 'new-frame)
7373 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7374 (select-frame (make-frame))
7375 (delete-other-windows)
7376 (pop-to-buffer-same-window ibuf)
7377 (org-set-frame-title heading))
7378 ((eq org-indirect-buffer-display 'dedicated-frame)
7379 (raise-frame
7380 (select-frame (or (and org-indirect-dedicated-frame
7381 (frame-live-p org-indirect-dedicated-frame)
7382 org-indirect-dedicated-frame)
7383 (setq org-indirect-dedicated-frame (make-frame)))))
7384 (delete-other-windows)
7385 (pop-to-buffer-same-window ibuf)
7386 (org-set-frame-title (concat "Indirect: " heading)))
7387 ((eq org-indirect-buffer-display 'current-window)
7388 (pop-to-buffer-same-window ibuf))
7389 ((eq org-indirect-buffer-display 'other-window)
7390 (pop-to-buffer ibuf))
7391 (t (error "Invalid value")))
7392 (narrow-to-region beg end)
7393 (outline-show-all)
7394 (goto-char pos)
7395 (run-hook-with-args 'org-cycle-hook 'all)
7396 (and (window-live-p cwin) (select-window cwin))))
7398 (defun org-get-indirect-buffer (&optional buffer heading)
7399 (setq buffer (or buffer (current-buffer)))
7400 (let ((n 1) (base (buffer-name buffer)) bname)
7401 (while (buffer-live-p
7402 (get-buffer
7403 (setq bname
7404 (concat base "-"
7405 (if heading (concat heading "-" (number-to-string n))
7406 (number-to-string n))))))
7407 (setq n (1+ n)))
7408 (condition-case nil
7409 (make-indirect-buffer buffer bname 'clone)
7410 (error (make-indirect-buffer buffer bname)))))
7412 (defun org-set-frame-title (title)
7413 "Set the title of the current frame to the string TITLE."
7414 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7416 ;;;; Structure editing
7418 ;;; Inserting headlines
7420 (defun org--line-empty-p (n)
7421 "Is the Nth next line empty?
7423 Counts the current line as N = 1 and the previous line as N = 0;
7424 see `beginning-of-line'."
7425 (save-excursion
7426 (and (not (bobp))
7427 (or (beginning-of-line n) t)
7428 (save-match-data
7429 (looking-at "[ \t]*$")))))
7431 (defun org-previous-line-empty-p ()
7432 "Is the previous line a blank line?
7433 When NEXT is non-nil, check the next line instead."
7434 (org--line-empty-p 0))
7436 (defun org-next-line-empty-p ()
7437 "Is the previous line a blank line?
7438 When NEXT is non-nil, check the next line instead."
7439 (org--line-empty-p 2))
7441 (defun org--blank-before-heading-p (&optional parent)
7442 "Non-nil when an empty line should precede a new heading here.
7443 When optional argument PARENT is non-nil, consider parent
7444 headline instead of current one."
7445 (pcase (assq 'heading org-blank-before-new-entry)
7446 (`(heading . auto)
7447 (save-excursion
7448 (org-with-limited-levels
7449 (unless (and (org-before-first-heading-p)
7450 (not (outline-next-heading)))
7451 (org-back-to-heading t)
7452 (when parent (org-up-heading-safe))
7453 (cond ((not (bobp))
7454 (org-previous-line-empty-p))
7455 ((outline-next-heading)
7456 (org-previous-line-empty-p))
7457 ;; Ignore trailing spaces on last buffer line.
7458 ((progn (skip-chars-backward " \t") (bolp))
7459 (org-previous-line-empty-p))
7460 (t nil))))))
7461 (`(heading . ,value) value)
7462 (_ nil)))
7464 (defun org-insert-heading (&optional arg invisible-ok top)
7465 "Insert a new heading or an item with the same depth at point.
7467 If point is at the beginning of a heading, insert a new heading
7468 or a new headline above the current one. When at the beginning
7469 of a regular line of text, turn it into a heading.
7471 If point is in the middle of a line, split it and create a new
7472 headline with the text in the current line after point (see
7473 `org-M-RET-may-split-line' on how to modify this behavior). As
7474 a special case, on a headline, splitting can only happen on the
7475 title itself. E.g., this excludes breaking stars or tags.
7477 With a `\\[universal-argument]' prefix, set \
7478 `org-insert-heading-respect-content' to
7479 a non-nil value for the duration of the command. This forces the
7480 insertion of a heading after the current subtree, independently
7481 on the location of point.
7483 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7484 insert the heading at the end of the tree
7485 above the current heading. For example, if point is within a
7486 2nd-level heading, then it will insert a 2nd-level heading at
7487 the end of the 1st-level parent subtree.
7489 When INVISIBLE-OK is set, stop at invisible headlines when going
7490 back. This is important for non-interactive uses of the
7491 command.
7493 When optional argument TOP is non-nil, insert a level 1 heading,
7494 unconditionally."
7495 (interactive "P")
7496 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7497 (level (org-current-level))
7498 (stars (make-string (if (and level (not top)) level 1) ?*)))
7499 (cond
7500 ((or org-insert-heading-respect-content
7501 (member arg '((4) (16)))
7502 (and (not invisible-ok)
7503 (invisible-p (max (1- (point)) (point-min)))))
7504 ;; Position point at the location of insertion.
7505 (if (not level) ;before first headline
7506 (org-with-limited-levels (outline-next-heading))
7507 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7508 ;; is nil.
7509 (org-with-limited-levels (org-back-to-heading invisible-ok))
7510 (cond ((equal arg '(16))
7511 (org-up-heading-safe)
7512 (org-end-of-subtree t t))
7514 (org-end-of-subtree t t))))
7515 (unless (bolp) (insert "\n")) ;ensure final newline
7516 (unless (and blank? (org-previous-line-empty-p))
7517 (org-N-empty-lines-before-current (if blank? 1 0)))
7518 (insert stars " \n")
7519 (forward-char -1))
7520 ;; At a headline...
7521 ((org-at-heading-p)
7522 (cond ((bolp)
7523 (when blank? (save-excursion (insert "\n")))
7524 (save-excursion (insert stars " \n"))
7525 (unless (and blank? (org-previous-line-empty-p))
7526 (org-N-empty-lines-before-current (if blank? 1 0)))
7527 (end-of-line))
7528 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7529 (org-match-line org-complex-heading-regexp)
7530 (org-pos-in-match-range (point) 4))
7531 ;; Grab the text that should moved to the new headline.
7532 ;; Preserve tags.
7533 (let ((split (delete-and-extract-region (point) (match-end 4))))
7534 (if (looking-at "[ \t]*$") (replace-match "")
7535 (org-set-tags nil t))
7536 (end-of-line)
7537 (when blank? (insert "\n"))
7538 (insert "\n" stars " ")
7539 (when (org-string-nw-p split) (insert split))
7540 (when (eobp) (save-excursion (insert "\n")))))
7542 (end-of-line)
7543 (when blank? (insert "\n"))
7544 (insert "\n" stars " ")
7545 (when (eobp) (save-excursion (insert "\n"))))))
7546 ;; On regular text, turn line into a headline or split, if
7547 ;; appropriate.
7548 ((bolp)
7549 (insert stars " ")
7550 (unless (and blank? (org-previous-line-empty-p))
7551 (org-N-empty-lines-before-current (if blank? 1 0))))
7553 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7554 (end-of-line))
7555 (insert "\n" stars " ")
7556 (unless (and blank? (org-previous-line-empty-p))
7557 (org-N-empty-lines-before-current (if blank? 1 0))))))
7558 (run-hooks 'org-insert-heading-hook))
7560 (defun org-N-empty-lines-before-current (n)
7561 "Make the number of empty lines before current exactly N.
7562 So this will delete or add empty lines."
7563 (let ((column (current-column)))
7564 (beginning-of-line)
7565 (unless (bobp)
7566 (let ((start (save-excursion
7567 (skip-chars-backward " \r\t\n")
7568 (line-end-position))))
7569 (delete-region start (line-end-position 0))))
7570 (insert (make-string n ?\n))
7571 (move-to-column column)))
7573 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7574 "Return the heading of the current entry, without the stars.
7575 When NO-TAGS is non-nil, don't include tags.
7576 When NO-TODO is non-nil, don't include TODO keywords.
7577 When NO-PRIORITY is non-nil, don't include priority cookie.
7578 When NO-COMMENT is non-nil, don't include COMMENT string."
7579 (save-excursion
7580 (org-back-to-heading t)
7581 (let ((case-fold-search nil))
7582 (looking-at org-complex-heading-regexp)
7583 (let ((todo (and (not no-todo) (match-string 2)))
7584 (priority (and (not no-priority) (match-string 3)))
7585 (headline (pcase (match-string 4)
7586 (`nil "")
7587 ((and (guard no-comment) h)
7588 (replace-regexp-in-string
7589 (eval-when-compile
7590 (format "\\`%s[ \t]+" org-comment-string))
7591 "" h))
7592 (h h)))
7593 (tags (and (not no-tags) (match-string 5))))
7594 (mapconcat #'identity
7595 (delq nil (list todo priority headline tags))
7596 " ")))))
7598 (defvar orgstruct-mode) ; defined below
7600 (defun org-heading-components ()
7601 "Return the components of the current heading.
7602 This is a list with the following elements:
7603 - the level as an integer
7604 - the reduced level, different if `org-odd-levels-only' is set.
7605 - the TODO keyword, or nil
7606 - the priority character, like ?A, or nil if no priority is given
7607 - the headline text itself, or the tags string if no headline text
7608 - the tags string, or nil."
7609 (save-excursion
7610 (org-back-to-heading t)
7611 (when (let (case-fold-search)
7612 (looking-at
7613 (if orgstruct-mode
7614 org-heading-regexp
7615 org-complex-heading-regexp)))
7616 (if orgstruct-mode
7617 (list (length (match-string 1))
7618 (org-reduced-level (length (match-string 1)))
7621 (match-string 2)
7622 nil)
7623 (list (length (match-string 1))
7624 (org-reduced-level (length (match-string 1)))
7625 (match-string-no-properties 2)
7626 (and (match-end 3) (aref (match-string 3) 2))
7627 (match-string-no-properties 4)
7628 (match-string-no-properties 5))))))
7630 (defun org-get-entry ()
7631 "Get the entry text, after heading, entire subtree."
7632 (save-excursion
7633 (org-back-to-heading t)
7634 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7636 (defun org-edit-headline (&optional heading)
7637 "Edit the current headline.
7638 Set it to HEADING when provided."
7639 (interactive)
7640 (org-with-wide-buffer
7641 (org-back-to-heading t)
7642 (let ((case-fold-search nil))
7643 (when (looking-at org-complex-heading-regexp)
7644 (let* ((old (match-string-no-properties 4))
7645 (new (save-match-data
7646 (org-trim (or heading (read-string "Edit: " old))))))
7647 (unless (equal old new)
7648 (if old (replace-match new t t nil 4)
7649 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7650 (insert " " new))
7651 (org-set-tags nil t)
7652 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7654 (defun org-insert-heading-after-current ()
7655 "Insert a new heading with same level as current, after current subtree."
7656 (interactive)
7657 (org-back-to-heading)
7658 (org-insert-heading)
7659 (org-move-subtree-down)
7660 (end-of-line 1))
7662 (defun org-insert-heading-respect-content (&optional invisible-ok)
7663 "Insert heading with `org-insert-heading-respect-content' set to t."
7664 (interactive)
7665 (org-insert-heading '(4) invisible-ok))
7667 (defun org-insert-todo-heading-respect-content (&optional force-state)
7668 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7669 (interactive)
7670 (org-insert-todo-heading force-state '(4)))
7672 (defun org-insert-todo-heading (arg &optional force-heading)
7673 "Insert a new heading with the same level and TODO state as current heading.
7675 If the heading has no TODO state, or if the state is DONE, use
7676 the first state (TODO by default). Also with one prefix arg,
7677 force first state. With two prefix args, force inserting at the
7678 end of the parent subtree.
7680 When called at a plain list item, insert a new item with an
7681 unchecked check box."
7682 (interactive "P")
7683 (when (or force-heading (not (org-insert-item 'checkbox)))
7684 (org-insert-heading (or (and (equal arg '(16)) '(16))
7685 force-heading))
7686 (save-excursion
7687 (org-forward-heading-same-level -1)
7688 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7689 (let* ((new-mark-x
7690 (if (or (equal arg '(4))
7691 (not (match-beginning 2))
7692 (member (match-string 2) org-done-keywords))
7693 (car org-todo-keywords-1)
7694 (match-string 2)))
7695 (new-mark
7697 (run-hook-with-args-until-success
7698 'org-todo-get-default-hook new-mark-x nil)
7699 new-mark-x)))
7700 (beginning-of-line 1)
7701 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7702 (if org-treat-insert-todo-heading-as-state-change
7703 (org-todo new-mark)
7704 (insert new-mark " "))))
7705 (when org-provide-todo-statistics
7706 (org-update-parent-todo-statistics))))
7708 (defun org-insert-subheading (arg)
7709 "Insert a new subheading and demote it.
7710 Works for outline headings and for plain lists alike."
7711 (interactive "P")
7712 (org-insert-heading arg)
7713 (cond
7714 ((org-at-heading-p) (org-do-demote))
7715 ((org-at-item-p) (org-indent-item))))
7717 (defun org-insert-todo-subheading (arg)
7718 "Insert a new subheading with TODO keyword or checkbox and demote it.
7719 Works for outline headings and for plain lists alike."
7720 (interactive "P")
7721 (org-insert-todo-heading arg)
7722 (cond
7723 ((org-at-heading-p) (org-do-demote))
7724 ((org-at-item-p) (org-indent-item))))
7726 ;;; Promotion and Demotion
7728 (defvar org-after-demote-entry-hook nil
7729 "Hook run after an entry has been demoted.
7730 The cursor will be at the beginning of the entry.
7731 When a subtree is being demoted, the hook will be called for each node.")
7733 (defvar org-after-promote-entry-hook nil
7734 "Hook run after an entry has been promoted.
7735 The cursor will be at the beginning of the entry.
7736 When a subtree is being promoted, the hook will be called for each node.")
7738 (defun org-promote-subtree ()
7739 "Promote the entire subtree.
7740 See also `org-promote'."
7741 (interactive)
7742 (save-excursion
7743 (org-with-limited-levels (org-map-tree 'org-promote)))
7744 (org-fix-position-after-promote))
7746 (defun org-demote-subtree ()
7747 "Demote the entire subtree.
7748 See `org-demote' and `org-promote'."
7749 (interactive)
7750 (save-excursion
7751 (org-with-limited-levels (org-map-tree 'org-demote)))
7752 (org-fix-position-after-promote))
7754 (defun org-do-promote ()
7755 "Promote the current heading higher up the tree.
7756 If the region is active in `transient-mark-mode', promote all
7757 headings in the region."
7758 (interactive)
7759 (save-excursion
7760 (if (org-region-active-p)
7761 (org-map-region 'org-promote (region-beginning) (region-end))
7762 (org-promote)))
7763 (org-fix-position-after-promote))
7765 (defun org-do-demote ()
7766 "Demote the current heading lower down the tree.
7767 If the region is active in `transient-mark-mode', demote all
7768 headings in the region."
7769 (interactive)
7770 (save-excursion
7771 (if (org-region-active-p)
7772 (org-map-region 'org-demote (region-beginning) (region-end))
7773 (org-demote)))
7774 (org-fix-position-after-promote))
7776 (defun org-fix-position-after-promote ()
7777 "Fix cursor position and indentation after demoting/promoting."
7778 (let ((pos (point)))
7779 (when (save-excursion
7780 (beginning-of-line)
7781 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7782 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7783 (cond ((eobp) (insert " "))
7784 ((eolp) (insert " "))
7785 ((equal (char-after) ?\s) (forward-char 1))))))
7787 (defun org-current-level ()
7788 "Return the level of the current entry, or nil if before the first headline.
7789 The level is the number of stars at the beginning of the
7790 headline. Use `org-reduced-level' to remove the effect of
7791 `org-odd-levels'. Unlike to `org-outline-level', this function
7792 ignores inlinetasks."
7793 (let ((level (org-with-limited-levels (org-outline-level))))
7794 (and (> level 0) level)))
7796 (defun org-get-previous-line-level ()
7797 "Return the outline depth of the last headline before the current line.
7798 Returns 0 for the first headline in the buffer, and nil if before the
7799 first headline."
7800 (and (org-current-level)
7801 (or (and (/= (line-beginning-position) (point-min))
7802 (save-excursion (beginning-of-line 0) (org-current-level)))
7803 0)))
7805 (defun org-reduced-level (l)
7806 "Compute the effective level of a heading.
7807 This takes into account the setting of `org-odd-levels-only'."
7808 (cond
7809 ((zerop l) 0)
7810 (org-odd-levels-only (1+ (floor (/ l 2))))
7811 (t l)))
7813 (defun org-level-increment ()
7814 "Return the number of stars that will be added or removed at a
7815 time to headlines when structure editing, based on the value of
7816 `org-odd-levels-only'."
7817 (if org-odd-levels-only 2 1))
7819 (defun org-get-valid-level (level &optional change)
7820 "Rectify a level change under the influence of `org-odd-levels-only'.
7821 LEVEL is a current level, CHANGE is by how much the level should
7822 be modified. Even if CHANGE is nil, LEVEL may be returned
7823 modified because even level numbers will become the next higher
7824 odd number. Returns values greater than 0."
7825 (if org-odd-levels-only
7826 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7827 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7828 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7829 (max 1 (+ level (or change 0)))))
7831 (defun org-promote ()
7832 "Promote the current heading higher up the tree."
7833 (org-with-wide-buffer
7834 (org-back-to-heading t)
7835 (let* ((after-change-functions (remq 'flyspell-after-change-function
7836 after-change-functions))
7837 (level (save-match-data (funcall outline-level)))
7838 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7839 (diff (abs (- level (length up-head) -1))))
7840 (cond
7841 ((and (= level 1) org-allow-promoting-top-level-subtree)
7842 (replace-match "# " nil t))
7843 ((= level 1)
7844 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7845 (t (replace-match up-head nil t)))
7846 (unless (= level 1)
7847 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7848 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7849 (run-hooks 'org-after-promote-entry-hook))))
7851 (defun org-demote ()
7852 "Demote the current heading lower down the tree."
7853 (org-with-wide-buffer
7854 (org-back-to-heading t)
7855 (let* ((after-change-functions (remq 'flyspell-after-change-function
7856 after-change-functions))
7857 (level (save-match-data (funcall outline-level)))
7858 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7859 (diff (abs (- level (length down-head) -1))))
7860 (replace-match down-head nil t)
7861 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7862 (when org-adapt-indentation (org-fixup-indentation diff))
7863 (run-hooks 'org-after-demote-entry-hook))))
7865 (defun org-cycle-level ()
7866 "Cycle the level of an empty headline through possible states.
7867 This goes first to child, then to parent, level, then up the hierarchy.
7868 After top level, it switches back to sibling level."
7869 (interactive)
7870 (let ((org-adapt-indentation nil))
7871 (when (org-point-at-end-of-empty-headline)
7872 (setq this-command 'org-cycle-level) ; Only needed for caching
7873 (let ((cur-level (org-current-level))
7874 (prev-level (org-get-previous-line-level)))
7875 (cond
7876 ;; If first headline in file, promote to top-level.
7877 ((= prev-level 0)
7878 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7879 do (org-do-promote)))
7880 ;; If same level as prev, demote one.
7881 ((= prev-level cur-level)
7882 (org-do-demote))
7883 ;; If parent is top-level, promote to top level if not already.
7884 ((= prev-level 1)
7885 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7886 do (org-do-promote)))
7887 ;; If top-level, return to prev-level.
7888 ((= cur-level 1)
7889 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7890 do (org-do-demote)))
7891 ;; If less than prev-level, promote one.
7892 ((< cur-level prev-level)
7893 (org-do-promote))
7894 ;; If deeper than prev-level, promote until higher than
7895 ;; prev-level.
7896 ((> cur-level prev-level)
7897 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7898 do (org-do-promote))))
7899 t))))
7901 (defun org-map-tree (fun)
7902 "Call FUN for every heading underneath the current one."
7903 (org-back-to-heading t)
7904 (let ((level (funcall outline-level)))
7905 (save-excursion
7906 (funcall fun)
7907 (while (and (progn
7908 (outline-next-heading)
7909 (> (funcall outline-level) level))
7910 (not (eobp)))
7911 (funcall fun)))))
7913 (defun org-map-region (fun beg end)
7914 "Call FUN for every heading between BEG and END."
7915 (let ((org-ignore-region t))
7916 (save-excursion
7917 (setq end (copy-marker end))
7918 (goto-char beg)
7919 (when (and (re-search-forward org-outline-regexp-bol nil t)
7920 (< (point) end))
7921 (funcall fun))
7922 (while (and (progn
7923 (outline-next-heading)
7924 (< (point) end))
7925 (not (eobp)))
7926 (funcall fun)))))
7928 (defun org-fixup-indentation (diff)
7929 "Change the indentation in the current entry by DIFF.
7931 DIFF is an integer. Indentation is done according to the
7932 following rules:
7934 - Planning information and property drawers are always indented
7935 according to the new level of the headline;
7937 - Footnote definitions and their contents are ignored;
7939 - Inlinetasks' boundaries are not shifted;
7941 - Empty lines are ignored;
7943 - Other lines' indentation are shifted by DIFF columns, unless
7944 it would introduce a structural change in the document, in
7945 which case no shifting is done at all.
7947 Assume point is at a heading or an inlinetask beginning."
7948 (org-with-wide-buffer
7949 (narrow-to-region (line-beginning-position)
7950 (save-excursion
7951 (if (org-with-limited-levels (org-at-heading-p))
7952 (org-with-limited-levels (outline-next-heading))
7953 (org-inlinetask-goto-end))
7954 (point)))
7955 (forward-line)
7956 ;; Indent properly planning info and property drawer.
7957 (when (looking-at-p org-planning-line-re)
7958 (org-indent-line)
7959 (forward-line))
7960 (when (looking-at org-property-drawer-re)
7961 (goto-char (match-end 0))
7962 (forward-line)
7963 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7964 (catch 'no-shift
7965 (when (zerop diff) (throw 'no-shift nil))
7966 ;; If DIFF is negative, first check if a shift is possible at all
7967 ;; (e.g., it doesn't break structure). This can only happen if
7968 ;; some contents are not properly indented.
7969 (let ((case-fold-search t))
7970 (when (< diff 0)
7971 (let ((diff (- diff))
7972 (forbidden-re (concat org-outline-regexp
7973 "\\|"
7974 (substring org-footnote-definition-re 1))))
7975 (save-excursion
7976 (while (not (eobp))
7977 (cond
7978 ((looking-at-p "[ \t]*$") (forward-line))
7979 ((and (looking-at-p org-footnote-definition-re)
7980 (let ((e (org-element-at-point)))
7981 (and (eq (org-element-type e) 'footnote-definition)
7982 (goto-char (org-element-property :end e))))))
7983 ((looking-at-p org-outline-regexp) (forward-line))
7984 ;; Give up if shifting would move before column 0 or
7985 ;; if it would introduce a headline or a footnote
7986 ;; definition.
7988 (skip-chars-forward " \t")
7989 (let ((ind (current-column)))
7990 (when (or (< ind diff)
7991 (and (= ind diff) (looking-at-p forbidden-re)))
7992 (throw 'no-shift nil)))
7993 ;; Ignore contents of example blocks and source
7994 ;; blocks if their indentation is meant to be
7995 ;; preserved. Jump to block's closing line.
7996 (beginning-of-line)
7997 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7998 (let ((e (org-element-at-point)))
7999 (and (memq (org-element-type e)
8000 '(example-block src-block))
8001 (or org-src-preserve-indentation
8002 (org-element-property :preserve-indent e))
8003 (goto-char (org-element-property :end e))
8004 (progn (skip-chars-backward " \r\t\n")
8005 (beginning-of-line)
8006 t))))
8007 (forward-line))))))))
8008 ;; Shift lines but footnote definitions, inlinetasks boundaries
8009 ;; by DIFF. Also skip contents of source or example blocks
8010 ;; when indentation is meant to be preserved.
8011 (while (not (eobp))
8012 (cond
8013 ((and (looking-at-p org-footnote-definition-re)
8014 (let ((e (org-element-at-point)))
8015 (and (eq (org-element-type e) 'footnote-definition)
8016 (goto-char (org-element-property :end e))))))
8017 ((looking-at-p org-outline-regexp) (forward-line))
8018 ((looking-at-p "[ \t]*$") (forward-line))
8020 (indent-line-to (+ (org-get-indentation) diff))
8021 (beginning-of-line)
8022 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8023 (let ((e (org-element-at-point)))
8024 (and (memq (org-element-type e)
8025 '(example-block src-block))
8026 (or org-src-preserve-indentation
8027 (org-element-property :preserve-indent e))
8028 (goto-char (org-element-property :end e))
8029 (progn (skip-chars-backward " \r\t\n")
8030 (beginning-of-line)
8031 t))))
8032 (forward-line)))))))))
8034 (defun org-convert-to-odd-levels ()
8035 "Convert an Org file with all levels allowed to one with odd levels.
8036 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8037 level 5 etc."
8038 (interactive)
8039 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8040 (let ((outline-level 'org-outline-level)
8041 (org-odd-levels-only nil) n)
8042 (save-excursion
8043 (goto-char (point-min))
8044 (while (re-search-forward "^\\*\\*+ " nil t)
8045 (setq n (- (length (match-string 0)) 2))
8046 (while (>= (setq n (1- n)) 0)
8047 (org-demote))
8048 (end-of-line 1))))))
8050 (defun org-convert-to-oddeven-levels ()
8051 "Convert an Org file with only odd levels to one with odd/even levels.
8052 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8053 file contains a section with an even level, conversion would
8054 destroy the structure of the file. An error is signaled in this
8055 case."
8056 (interactive)
8057 (goto-char (point-min))
8058 ;; First check if there are no even levels
8059 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8060 (org-show-set-visibility 'canonical)
8061 (error "Not all levels are odd in this file. Conversion not possible"))
8062 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8063 (let ((outline-regexp org-outline-regexp)
8064 (outline-level 'org-outline-level)
8065 (org-odd-levels-only nil) n)
8066 (save-excursion
8067 (goto-char (point-min))
8068 (while (re-search-forward "^\\*\\*+ " nil t)
8069 (setq n (/ (1- (length (match-string 0))) 2))
8070 (while (>= (setq n (1- n)) 0)
8071 (org-promote))
8072 (end-of-line 1))))))
8074 (defun org-tr-level (n)
8075 "Make N odd if required."
8076 (if org-odd-levels-only (1+ (/ n 2)) n))
8078 ;;; Vertical tree motion, cutting and pasting of subtrees
8080 (defun org-move-subtree-up (&optional arg)
8081 "Move the current subtree up past ARG headlines of the same level."
8082 (interactive "p")
8083 (org-move-subtree-down (- (prefix-numeric-value arg))))
8085 (defun org-move-subtree-down (&optional arg)
8086 "Move the current subtree down past ARG headlines of the same level."
8087 (interactive "p")
8088 (setq arg (prefix-numeric-value arg))
8089 (org-preserve-local-variables
8090 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8091 'org-get-last-sibling))
8092 (ins-point (make-marker))
8093 (cnt (abs arg))
8094 (col (current-column))
8095 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8096 ;; Select the tree
8097 (org-back-to-heading)
8098 (setq beg0 (point))
8099 (save-excursion
8100 (setq ne-beg (org-back-over-empty-lines))
8101 (setq beg (point)))
8102 (save-match-data
8103 (save-excursion (outline-end-of-heading)
8104 (setq folded (org-invisible-p)))
8105 (progn (org-end-of-subtree nil t)
8106 (unless (eobp) (backward-char))))
8107 (outline-next-heading)
8108 (setq ne-end (org-back-over-empty-lines))
8109 (setq end (point))
8110 (goto-char beg0)
8111 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8112 ;; include less whitespace
8113 (save-excursion
8114 (goto-char beg)
8115 (forward-line (- ne-beg ne-end))
8116 (setq beg (point))))
8117 ;; Find insertion point, with error handling
8118 (while (> cnt 0)
8119 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8120 (progn (goto-char beg0)
8121 (user-error "Cannot move past superior level or buffer limit")))
8122 (setq cnt (1- cnt)))
8123 (when (> arg 0)
8124 ;; Moving forward - still need to move over subtree
8125 (org-end-of-subtree t t)
8126 (save-excursion
8127 (org-back-over-empty-lines)
8128 (unless (bolp) (insert "\n"))))
8129 (setq ne-ins (org-back-over-empty-lines))
8130 (move-marker ins-point (point))
8131 (setq txt (buffer-substring beg end))
8132 (org-save-markers-in-region beg end)
8133 (delete-region beg end)
8134 (org-remove-empty-overlays-at beg)
8135 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8136 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8137 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8138 (let ((bbb (point)))
8139 (insert-before-markers txt)
8140 (org-reinstall-markers-in-region bbb)
8141 (move-marker ins-point bbb))
8142 (or (bolp) (insert "\n"))
8143 (setq ins-end (point))
8144 (goto-char ins-point)
8145 (org-skip-whitespace)
8146 (when (and (< arg 0)
8147 (org-first-sibling-p)
8148 (> ne-ins ne-beg))
8149 ;; Move whitespace back to beginning.
8150 (save-excursion
8151 (goto-char ins-end)
8152 (let ((kill-whole-line t))
8153 (kill-line (- ne-ins ne-beg)) (point)))
8154 (insert (make-string (- ne-ins ne-beg) ?\n)))
8155 (move-marker ins-point nil)
8156 (if folded
8157 (outline-hide-subtree)
8158 (org-show-entry)
8159 (org-show-children)
8160 (org-cycle-hide-drawers 'children))
8161 (org-clean-visibility-after-subtree-move)
8162 ;; Move back to the initial column we were at.
8163 (move-to-column col))))
8165 (defvar org-subtree-clip ""
8166 "Clipboard for cut and paste of subtrees.
8167 This is actually only a copy of the kill, because we use the normal kill
8168 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8170 (defvar org-subtree-clip-folded nil
8171 "Was the last copied subtree folded?
8172 This is used to fold the tree back after pasting.")
8174 (defun org-cut-subtree (&optional n)
8175 "Cut the current subtree into the clipboard.
8176 With prefix arg N, cut this many sequential subtrees.
8177 This is a short-hand for marking the subtree and then cutting it."
8178 (interactive "p")
8179 (org-copy-subtree n 'cut))
8181 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8182 "Copy the current subtree it in the clipboard.
8183 With prefix arg N, copy this many sequential subtrees.
8184 This is a short-hand for marking the subtree and then copying it.
8185 If CUT is non-nil, actually cut the subtree.
8186 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8187 of some markers in the region, even if CUT is non-nil. This is
8188 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8189 (interactive "p")
8190 (org-preserve-local-variables
8191 (let (beg end folded (beg0 (point)))
8192 (if (called-interactively-p 'any)
8193 (org-back-to-heading nil) ; take what looks like a subtree
8194 (org-back-to-heading t)) ; take what is really there
8195 (setq beg (point))
8196 (skip-chars-forward " \t\r\n")
8197 (save-match-data
8198 (if nosubtrees
8199 (outline-next-heading)
8200 (save-excursion (outline-end-of-heading)
8201 (setq folded (org-invisible-p)))
8202 (ignore-errors (org-forward-heading-same-level (1- n) t))
8203 (org-end-of-subtree t t)))
8204 ;; Include the end of an inlinetask
8205 (when (and (featurep 'org-inlinetask)
8206 (looking-at-p (concat (org-inlinetask-outline-regexp)
8207 "END[ \t]*$")))
8208 (end-of-line))
8209 (setq end (point))
8210 (goto-char beg0)
8211 (when (> end beg)
8212 (setq org-subtree-clip-folded folded)
8213 (when (or cut force-store-markers)
8214 (org-save-markers-in-region beg end))
8215 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8216 (setq org-subtree-clip (current-kill 0))
8217 (message "%s: Subtree(s) with %d characters"
8218 (if cut "Cut" "Copied")
8219 (length org-subtree-clip))))))
8221 (defun org-paste-subtree (&optional level tree for-yank remove)
8222 "Paste the clipboard as a subtree, with modification of headline level.
8223 The entire subtree is promoted or demoted in order to match a new headline
8224 level.
8226 If the cursor is at the beginning of a headline, the same level as
8227 that headline is used to paste the tree.
8229 If not, the new level is derived from the *visible* headings
8230 before and after the insertion point, and taken to be the inferior headline
8231 level of the two. So if the previous visible heading is level 3 and the
8232 next is level 4 (or vice versa), level 4 will be used for insertion.
8233 This makes sure that the subtree remains an independent subtree and does
8234 not swallow low level entries.
8236 You can also force a different level, either by using a numeric prefix
8237 argument, or by inserting the heading marker by hand. For example, if the
8238 cursor is after \"*****\", then the tree will be shifted to level 5.
8240 If optional TREE is given, use this text instead of the kill ring.
8242 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8243 move back over whitespace before inserting, and move point to the end of
8244 the inserted text when done.
8246 When REMOVE is non-nil, remove the subtree from the clipboard."
8247 (interactive "P")
8248 (setq tree (or tree (and kill-ring (current-kill 0))))
8249 (unless (org-kill-is-subtree-p tree)
8250 (user-error "%s"
8251 (substitute-command-keys
8252 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8253 (org-with-limited-levels
8254 (let* ((visp (not (org-invisible-p)))
8255 (txt tree)
8256 (^re_ "\\(\\*+\\)[ \t]*")
8257 (old-level (if (string-match org-outline-regexp-bol txt)
8258 (- (match-end 0) (match-beginning 0) 1)
8259 -1))
8260 (force-level (cond (level (prefix-numeric-value level))
8261 ((and (looking-at "[ \t]*$")
8262 (string-match
8263 "^\\*+$" (buffer-substring
8264 (point-at-bol) (point))))
8265 (- (match-end 0) (match-beginning 0)))
8266 ((and (bolp)
8267 (looking-at org-outline-regexp))
8268 (- (match-end 0) (point) 1))))
8269 (previous-level (save-excursion
8270 (condition-case nil
8271 (progn
8272 (outline-previous-visible-heading 1)
8273 (if (looking-at ^re_)
8274 (- (match-end 0) (match-beginning 0) 1)
8276 (error 1))))
8277 (next-level (save-excursion
8278 (condition-case nil
8279 (progn
8280 (or (looking-at org-outline-regexp)
8281 (outline-next-visible-heading 1))
8282 (if (looking-at ^re_)
8283 (- (match-end 0) (match-beginning 0) 1)
8285 (error 1))))
8286 (new-level (or force-level (max previous-level next-level)))
8287 (shift (if (or (= old-level -1)
8288 (= new-level -1)
8289 (= old-level new-level))
8291 (- new-level old-level)))
8292 (delta (if (> shift 0) -1 1))
8293 (func (if (> shift 0) 'org-demote 'org-promote))
8294 (org-odd-levels-only nil)
8295 beg end newend)
8296 ;; Remove the forced level indicator
8297 (when force-level
8298 (delete-region (point-at-bol) (point)))
8299 ;; Paste
8300 (beginning-of-line (if (bolp) 1 2))
8301 (setq beg (point))
8302 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8303 (insert-before-markers txt)
8304 (unless (string-suffix-p "\n" txt) (insert "\n"))
8305 (setq newend (point))
8306 (org-reinstall-markers-in-region beg)
8307 (setq end (point))
8308 (goto-char beg)
8309 (skip-chars-forward " \t\n\r")
8310 (setq beg (point))
8311 (when (and (org-invisible-p) visp)
8312 (save-excursion (outline-show-heading)))
8313 ;; Shift if necessary
8314 (unless (= shift 0)
8315 (save-restriction
8316 (narrow-to-region beg end)
8317 (while (not (= shift 0))
8318 (org-map-region func (point-min) (point-max))
8319 (setq shift (+ delta shift)))
8320 (goto-char (point-min))
8321 (setq newend (point-max))))
8322 (when (or (called-interactively-p 'interactive) for-yank)
8323 (message "Clipboard pasted as level %d subtree" new-level))
8324 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8325 kill-ring
8326 (eq org-subtree-clip (current-kill 0))
8327 org-subtree-clip-folded)
8328 ;; The tree was folded before it was killed/copied
8329 (outline-hide-subtree))
8330 (and for-yank (goto-char newend))
8331 (and remove (setq kill-ring (cdr kill-ring))))))
8333 (defun org-kill-is-subtree-p (&optional txt)
8334 "Check if the current kill is an outline subtree, or a set of trees.
8335 Returns nil if kill does not start with a headline, or if the first
8336 headline level is not the largest headline level in the tree.
8337 So this will actually accept several entries of equal levels as well,
8338 which is OK for `org-paste-subtree'.
8339 If optional TXT is given, check this string instead of the current kill."
8340 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8341 (re (org-get-limited-outline-regexp))
8342 (^re (concat "^" re))
8343 (start-level (and kill
8344 (string-match
8345 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8346 kill)
8347 (- (match-end 2) (match-beginning 2) 1)))
8348 (start (1+ (or (match-beginning 2) -1))))
8349 (if (not start-level)
8350 (progn
8351 nil) ;; does not even start with a heading
8352 (catch 'exit
8353 (while (setq start (string-match ^re kill (1+ start)))
8354 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8355 (throw 'exit nil)))
8356 t))))
8358 (defvar org-markers-to-move nil
8359 "Markers that should be moved with a cut-and-paste operation.
8360 Those markers are stored together with their positions relative to
8361 the start of the region.")
8363 (defun org-save-markers-in-region (beg end)
8364 "Check markers in region.
8365 If these markers are between BEG and END, record their position relative
8366 to BEG, so that after moving the block of text, we can put the markers back
8367 into place.
8368 This function gets called just before an entry or tree gets cut from the
8369 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8370 called immediately, to move the markers with the entries."
8371 (setq org-markers-to-move nil)
8372 (when (featurep 'org-clock)
8373 (org-clock-save-markers-for-cut-and-paste beg end))
8374 (when (featurep 'org-agenda)
8375 (org-agenda-save-markers-for-cut-and-paste beg end)))
8377 (defun org-check-and-save-marker (marker beg end)
8378 "Check if MARKER is between BEG and END.
8379 If yes, remember the marker and the distance to BEG."
8380 (when (and (marker-buffer marker)
8381 (equal (marker-buffer marker) (current-buffer))
8382 (>= marker beg) (< marker end))
8383 (push (cons marker (- marker beg)) org-markers-to-move)))
8385 (defun org-reinstall-markers-in-region (beg)
8386 "Move all remembered markers to their position relative to BEG."
8387 (dolist (x org-markers-to-move)
8388 (move-marker (car x) (+ beg (cdr x))))
8389 (setq org-markers-to-move nil))
8391 (defun org-narrow-to-subtree ()
8392 "Narrow buffer to the current subtree."
8393 (interactive)
8394 (save-excursion
8395 (save-match-data
8396 (org-with-limited-levels
8397 (narrow-to-region
8398 (progn (org-back-to-heading t) (point))
8399 (progn (org-end-of-subtree t t)
8400 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8401 (point)))))))
8403 (defun org-narrow-to-block ()
8404 "Narrow buffer to the current block."
8405 (interactive)
8406 (let* ((case-fold-search t)
8407 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8408 "^[ \t]*#\\+end_.*")))
8409 (if blockp
8410 (narrow-to-region (car blockp) (cdr blockp))
8411 (user-error "Not in a block"))))
8413 (defun org-clone-subtree-with-time-shift (n &optional shift)
8414 "Clone the task (subtree) at point N times.
8415 The clones will be inserted as siblings.
8417 In interactive use, the user will be prompted for the number of
8418 clones to be produced. If the entry has a timestamp, the user
8419 will also be prompted for a time shift, which may be a repeater
8420 as used in time stamps, for example `+3d'. To disable this,
8421 you can call the function with a universal prefix argument.
8423 When a valid repeater is given and the entry contains any time
8424 stamps, the clones will become a sequence in time, with time
8425 stamps in the subtree shifted for each clone produced. If SHIFT
8426 is nil or the empty string, time stamps will be left alone. The
8427 ID property of the original subtree is removed.
8429 In each clone, all the CLOCK entries will be removed. This
8430 prevents Org from considering that the clocked times overlap.
8432 If the original subtree did contain time stamps with a repeater,
8433 the following will happen:
8434 - the repeater will be removed in each clone
8435 - an additional clone will be produced, with the current, unshifted
8436 date(s) in the entry.
8437 - the original entry will be placed *after* all the clones, with
8438 repeater intact.
8439 - the start days in the repeater in the original entry will be shifted
8440 to past the last clone.
8441 In this way you can spell out a number of instances of a repeating task,
8442 and still retain the repeater to cover future instances of the task.
8444 As described above, N+1 clones are produced when the original
8445 subtree has a repeater. Setting N to 0, then, can be used to
8446 remove the repeater from a subtree and create a shifted clone
8447 with the original repeater."
8448 (interactive "nNumber of clones to produce: ")
8449 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8450 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8451 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8452 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8453 (shift
8454 (or shift
8455 (if (and (not (equal current-prefix-arg '(4)))
8456 (save-excursion
8457 (goto-char beg)
8458 (re-search-forward org-ts-regexp-both end-of-tree t)))
8459 (read-from-minibuffer
8460 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8461 ""))) ;No time shift
8462 (doshift
8463 (and (org-string-nw-p shift)
8464 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8465 shift)
8466 (user-error "Invalid shift specification %s" shift)))))
8467 (goto-char end-of-tree)
8468 (unless (bolp) (insert "\n"))
8469 (let* ((end (point))
8470 (template (buffer-substring beg end))
8471 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8472 (shift-what (pcase (and doshift (match-string 2 shift))
8473 (`nil nil)
8474 ("d" 'day)
8475 ("w" (setq shift-n (* 7 shift-n)) 'day)
8476 ("m" 'month)
8477 ("y" 'year)
8478 (_ (error "Unsupported time unit"))))
8479 (nmin 1)
8480 (nmax n)
8481 (n-no-remove -1)
8482 (idprop (org-entry-get nil "ID")))
8483 (when (and doshift
8484 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8485 template))
8486 (delete-region beg end)
8487 (setq end beg)
8488 (setq nmin 0)
8489 (setq nmax (1+ nmax))
8490 (setq n-no-remove nmax))
8491 (goto-char end)
8492 (cl-loop for n from nmin to nmax do
8493 (insert
8494 ;; Prepare clone.
8495 (with-temp-buffer
8496 (insert template)
8497 (org-mode)
8498 (goto-char (point-min))
8499 (org-show-subtree)
8500 (and idprop (if org-clone-delete-id
8501 (org-entry-delete nil "ID")
8502 (org-id-get-create t)))
8503 (unless (= n 0)
8504 (while (re-search-forward org-clock-line-re nil t)
8505 (delete-region (line-beginning-position)
8506 (line-beginning-position 2)))
8507 (goto-char (point-min))
8508 (while (re-search-forward org-drawer-regexp nil t)
8509 (org-remove-empty-drawer-at (point))))
8510 (goto-char (point-min))
8511 (when doshift
8512 (while (re-search-forward org-ts-regexp-both nil t)
8513 (org-timestamp-change (* n shift-n) shift-what))
8514 (unless (= n n-no-remove)
8515 (goto-char (point-min))
8516 (while (re-search-forward org-ts-regexp nil t)
8517 (save-excursion
8518 (goto-char (match-beginning 0))
8519 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8520 (delete-region (match-beginning 1) (match-end 1)))))))
8521 (buffer-string)))))
8522 (goto-char beg)))
8524 ;;; Outline Sorting
8526 (defun org-sort (&optional with-case)
8527 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8528 Optional argument WITH-CASE means sort case-sensitively."
8529 (interactive "P")
8530 (org-call-with-arg
8531 (cond ((org-at-table-p) #'org-table-sort-lines)
8532 ((org-at-item-p) #'org-sort-list)
8533 (t #'org-sort-entries))
8534 with-case))
8536 (defun org-sort-remove-invisible (s)
8537 "Remove invisible part of links and emphasis markers from string S."
8538 (remove-text-properties 0 (length s) org-rm-props s)
8539 (replace-regexp-in-string
8540 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8541 (replace-regexp-in-string
8542 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8543 (org-link-display-format s)
8544 t t) t t))
8546 (defvar org-priority-regexp) ; defined later in the file
8548 (defvar org-after-sorting-entries-or-items-hook nil
8549 "Hook that is run after a bunch of entries or items have been sorted.
8550 When children are sorted, the cursor is in the parent line when this
8551 hook gets called. When a region or a plain list is sorted, the cursor
8552 will be in the first entry of the sorted region/list.")
8554 (defun org-sort-entries
8555 (&optional with-case sorting-type getkey-func compare-func property
8556 interactive?)
8557 "Sort entries on a certain level of an outline tree.
8558 If there is an active region, the entries in the region are sorted.
8559 Else, if the cursor is before the first entry, sort the top-level items.
8560 Else, the children of the entry at point are sorted.
8562 Sorting can be alphabetically, numerically, by date/time as given by
8563 a time stamp, by a property, by priority order, or by a custom function.
8565 The command prompts for the sorting type unless it has been given to the
8566 function through the SORTING-TYPE argument, which needs to be a character,
8567 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8568 the precise meaning of each character:
8570 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8571 c By creation time, which is assumed to be the first inactive time stamp
8572 at the beginning of a line.
8573 d By deadline date/time.
8574 k By clocking time.
8575 n Numerically, by converting the beginning of the entry/item to a number.
8576 o By order of TODO keywords.
8577 p By priority according to the cookie.
8578 r By the value of a property.
8579 s By scheduled date/time.
8580 t By date/time, either the first active time stamp in the entry, or, if
8581 none exist, by the first inactive one.
8583 Capital letters will reverse the sort order.
8585 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8586 called with point at the beginning of the record. It must return a
8587 value that is compatible with COMPARE-FUNC, the function used to
8588 compare entries.
8590 Comparing entries ignores case by default. However, with an optional argument
8591 WITH-CASE, the sorting considers case as well.
8593 Sorting is done against the visible part of the headlines, it ignores hidden
8594 links.
8596 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8598 A non-nil value for INTERACTIVE? is used to signal that this
8599 function is being called interactively."
8600 (interactive (list current-prefix-arg nil nil nil nil t))
8601 (let ((case-func (if with-case 'identity 'downcase))
8602 start beg end stars re re2
8603 txt what tmp)
8604 ;; Find beginning and end of region to sort
8605 (cond
8606 ((org-region-active-p)
8607 ;; we will sort the region
8608 (setq end (region-end)
8609 what "region")
8610 (goto-char (region-beginning))
8611 (unless (org-at-heading-p) (outline-next-heading))
8612 (setq start (point)))
8613 ((or (org-at-heading-p)
8614 (ignore-errors (progn (org-back-to-heading) t)))
8615 ;; we will sort the children of the current headline
8616 (org-back-to-heading)
8617 (setq start (point)
8618 end (progn (org-end-of-subtree t t)
8619 (or (bolp) (insert "\n"))
8620 (when (>= (org-back-over-empty-lines) 1)
8621 (forward-line 1))
8622 (point))
8623 what "children")
8624 (goto-char start)
8625 (outline-show-subtree)
8626 (outline-next-heading))
8628 ;; we will sort the top-level entries in this file
8629 (goto-char (point-min))
8630 (or (org-at-heading-p) (outline-next-heading))
8631 (setq start (point))
8632 (goto-char (point-max))
8633 (beginning-of-line 1)
8634 (when (looking-at ".*?\\S-")
8635 ;; File ends in a non-white line
8636 (end-of-line 1)
8637 (insert "\n"))
8638 (setq end (point-max))
8639 (setq what "top-level")
8640 (goto-char start)
8641 (outline-show-all)))
8643 (setq beg (point))
8644 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8646 (looking-at "\\(\\*+\\)")
8647 (setq stars (match-string 1)
8648 re (concat "^" (regexp-quote stars) " +")
8649 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8650 txt (buffer-substring beg end))
8651 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8652 (when (and (not (equal stars "*")) (string-match re2 txt))
8653 (user-error "Region to sort contains a level above the first entry"))
8655 (unless sorting-type
8656 (message
8657 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8658 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8659 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8660 what)
8661 (setq sorting-type (read-char-exclusive)))
8663 (unless getkey-func
8664 (and (= (downcase sorting-type) ?f)
8665 (setq getkey-func
8666 (or (and interactive?
8667 (org-read-function
8668 "Function for extracting keys: "))
8669 (error "Missing key extractor")))))
8671 (and (= (downcase sorting-type) ?r)
8672 (not property)
8673 (setq property
8674 (completing-read "Property: "
8675 (mapcar #'list (org-buffer-property-keys t))
8676 nil t)))
8678 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8679 (message "Sorting entries...")
8681 (save-restriction
8682 (narrow-to-region start end)
8683 (let ((restore-clock?
8684 ;; The clock marker is lost when using `sort-subr'; mark
8685 ;; the clock with temporary `:org-clock-marker-backup'
8686 ;; text property.
8687 (when (and (eq (org-clock-is-active) (current-buffer))
8688 (<= start (marker-position org-clock-marker))
8689 (>= end (marker-position org-clock-marker)))
8690 (org-with-silent-modifications
8691 (put-text-property (1- org-clock-marker) org-clock-marker
8692 :org-clock-marker-backup t))
8694 (dcst (downcase sorting-type))
8695 (case-fold-search nil)
8696 (now (current-time)))
8697 (org-preserve-local-variables
8698 (sort-subr
8699 (/= dcst sorting-type)
8700 ;; This function moves to the beginning character of the
8701 ;; "record" to be sorted.
8702 (lambda nil
8703 (if (re-search-forward re nil t)
8704 (goto-char (match-beginning 0))
8705 (goto-char (point-max))))
8706 ;; This function moves to the last character of the "record" being
8707 ;; sorted.
8708 (lambda nil
8709 (save-match-data
8710 (condition-case nil
8711 (outline-forward-same-level 1)
8712 (error
8713 (goto-char (point-max))))))
8714 ;; This function returns the value that gets sorted against.
8715 (lambda ()
8716 (cond
8717 ((= dcst ?n)
8718 (if (looking-at org-complex-heading-regexp)
8719 (string-to-number
8720 (org-sort-remove-invisible (match-string 4)))
8721 nil))
8722 ((= dcst ?a)
8723 (if (looking-at org-complex-heading-regexp)
8724 (funcall case-func
8725 (org-sort-remove-invisible (match-string 4)))
8726 nil))
8727 ((= dcst ?k)
8728 (or (get-text-property (point) :org-clock-minutes) 0))
8729 ((= dcst ?t)
8730 (let ((end (save-excursion (outline-next-heading) (point))))
8731 (if (or (re-search-forward org-ts-regexp end t)
8732 (re-search-forward org-ts-regexp-both end t))
8733 (org-time-string-to-seconds (match-string 0))
8734 (float-time now))))
8735 ((= dcst ?c)
8736 (let ((end (save-excursion (outline-next-heading) (point))))
8737 (if (re-search-forward
8738 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8739 end t)
8740 (org-time-string-to-seconds (match-string 0))
8741 (float-time now))))
8742 ((= dcst ?s)
8743 (let ((end (save-excursion (outline-next-heading) (point))))
8744 (if (re-search-forward org-scheduled-time-regexp end t)
8745 (org-time-string-to-seconds (match-string 1))
8746 (float-time now))))
8747 ((= dcst ?d)
8748 (let ((end (save-excursion (outline-next-heading) (point))))
8749 (if (re-search-forward org-deadline-time-regexp end t)
8750 (org-time-string-to-seconds (match-string 1))
8751 (float-time now))))
8752 ((= dcst ?p)
8753 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8754 (string-to-char (match-string 2))
8755 org-default-priority))
8756 ((= dcst ?r)
8757 (or (org-entry-get nil property) ""))
8758 ((= dcst ?o)
8759 (when (looking-at org-complex-heading-regexp)
8760 (let* ((m (match-string 2))
8761 (s (if (member m org-done-keywords) '- '+)))
8762 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8763 ((= dcst ?f)
8764 (if getkey-func
8765 (progn
8766 (setq tmp (funcall getkey-func))
8767 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8768 tmp)
8769 (error "Invalid key function `%s'" getkey-func)))
8770 (t (error "Invalid sorting type `%c'" sorting-type))))
8772 (cond
8773 ((= dcst ?a) 'string<)
8774 ((= dcst ?f)
8775 (or compare-func
8776 (and interactive?
8777 (org-read-function
8778 (concat "Function for comparing keys "
8779 "(empty for default `sort-subr' predicate): ")
8780 'allow-empty))))
8781 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8782 (when restore-clock?
8783 (move-marker org-clock-marker
8784 (1+ (next-single-property-change
8785 start :org-clock-marker-backup)))
8786 (remove-text-properties (1- org-clock-marker) org-clock-marker
8787 '(:org-clock-marker-backup t)))))
8788 (run-hooks 'org-after-sorting-entries-or-items-hook)
8789 (message "Sorting entries...done")))
8791 ;;; The orgstruct minor mode
8793 ;; Define a minor mode which can be used in other modes in order to
8794 ;; integrate the Org mode structure editing commands.
8796 ;; This is really a hack, because the Org mode structure commands use
8797 ;; keys which normally belong to the major mode. Here is how it
8798 ;; works: The minor mode defines all the keys necessary to operate the
8799 ;; structure commands, but wraps the commands into a function which
8800 ;; tests if the cursor is currently at a headline or a plain list
8801 ;; item. If that is the case, the structure command is used,
8802 ;; temporarily setting many Org mode variables like regular
8803 ;; expressions for filling etc. However, when any of those keys is
8804 ;; used at a different location, function uses `key-binding' to look
8805 ;; up if the key has an associated command in another currently active
8806 ;; keymap (minor modes, major mode, global), and executes that
8807 ;; command. There might be problems if any of the keys is otherwise
8808 ;; used as a prefix key.
8810 (defcustom orgstruct-heading-prefix-regexp ""
8811 "Regexp that matches the custom prefix of Org headlines in
8812 orgstruct(++)-mode."
8813 :group 'org
8814 :version "26.1"
8815 :package-version '(Org . "8.3")
8816 :type 'regexp)
8817 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8819 (defcustom orgstruct-setup-hook nil
8820 "Hook run after orgstruct-mode-map is filled."
8821 :group 'org
8822 :version "24.4"
8823 :package-version '(Org . "8.0")
8824 :type 'hook)
8826 (defvar orgstruct-initialized nil)
8828 (defvar org-local-vars nil
8829 "List of local variables, for use by `orgstruct-mode'.")
8831 ;;;###autoload
8832 (define-minor-mode orgstruct-mode
8833 "Toggle the minor mode `orgstruct-mode'.
8834 This mode is for using Org mode structure commands in other
8835 modes. The following keys behave as if Org mode were active, if
8836 the cursor is on a headline, or on a plain list item (both as
8837 defined by Org mode)."
8838 nil " OrgStruct" (make-sparse-keymap)
8839 (funcall (if orgstruct-mode
8840 'add-to-invisibility-spec
8841 'remove-from-invisibility-spec)
8842 '(outline . t))
8843 (when orgstruct-mode
8844 (org-load-modules-maybe)
8845 (unless orgstruct-initialized
8846 (orgstruct-setup)
8847 (setq orgstruct-initialized t))))
8849 ;;;###autoload
8850 (defun turn-on-orgstruct ()
8851 "Unconditionally turn on `orgstruct-mode'."
8852 (orgstruct-mode 1))
8854 (defvar-local orgstruct-is-++ nil
8855 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8856 (defvar-local org-fb-vars nil)
8857 (defun orgstruct++-mode (&optional arg)
8858 "Toggle `orgstruct-mode', the enhanced version of it.
8859 In addition to setting orgstruct-mode, this also exports all
8860 indentation and autofilling variables from Org mode into the
8861 buffer. It will also recognize item context in multiline items."
8862 (interactive "P")
8863 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8864 (if (< arg 1)
8865 (progn (orgstruct-mode -1)
8866 (dolist (v org-fb-vars)
8867 (set (make-local-variable (car v))
8868 (if (eq (car-safe (cadr v)) 'quote)
8869 (cl-cadadr v)
8870 (nth 1 v)))))
8871 (orgstruct-mode 1)
8872 (setq org-fb-vars nil)
8873 (unless org-local-vars
8874 (setq org-local-vars (org-get-local-variables)))
8875 (let (var val)
8876 (dolist (x org-local-vars)
8877 (when (string-match
8878 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
8879 \\|fill-prefix\\|indent-\\)"
8880 (symbol-name (car x)))
8881 (setq var (car x) val (nth 1 x))
8882 (push (list var `(quote ,(eval var))) org-fb-vars)
8883 (set (make-local-variable var)
8884 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8885 (setq-local orgstruct-is-++ t))))
8887 ;;;###autoload
8888 (defun turn-on-orgstruct++ ()
8889 "Unconditionally turn on `orgstruct++-mode'."
8890 (orgstruct++-mode 1))
8892 (defun orgstruct-error ()
8893 "Error when there is no default binding for a structure key."
8894 (interactive)
8895 (funcall (if (fboundp 'user-error)
8896 'user-error
8897 'error)
8898 "This key has no function outside structure elements"))
8900 (defun orgstruct-setup ()
8901 "Setup orgstruct keymap."
8902 (dolist (cell '((org-demote . t)
8903 (org-metaleft . t)
8904 (org-metaright . t)
8905 (org-promote . t)
8906 (org-shiftmetaleft . t)
8907 (org-shiftmetaright . t)
8908 org-backward-element
8909 org-backward-heading-same-level
8910 org-ctrl-c-ret
8911 org-ctrl-c-minus
8912 org-ctrl-c-star
8913 org-cycle
8914 org-force-cycle-archived
8915 org-forward-heading-same-level
8916 org-insert-heading
8917 org-insert-heading-respect-content
8918 org-kill-note-or-show-branches
8919 org-mark-subtree
8920 org-meta-return
8921 org-metadown
8922 org-metaup
8923 org-narrow-to-subtree
8924 org-promote-subtree
8925 org-reveal
8926 org-shiftdown
8927 org-shiftleft
8928 org-shiftmetadown
8929 org-shiftmetaup
8930 org-shiftright
8931 org-shifttab
8932 org-shifttab
8933 org-shiftup
8934 org-show-children
8935 org-show-subtree
8936 org-sort
8937 org-up-element
8938 outline-demote
8939 outline-next-visible-heading
8940 outline-previous-visible-heading
8941 outline-promote
8942 outline-up-heading))
8943 (let ((f (or (car-safe cell) cell))
8944 (disable-when-heading-prefix (cdr-safe cell)))
8945 (when (fboundp f)
8946 (let ((new-bindings))
8947 (dolist (binding (nconc (where-is-internal f org-mode-map)
8948 (where-is-internal f outline-mode-map)))
8949 (push binding new-bindings)
8950 ;; TODO use local-function-key-map
8951 (dolist (rep '(("<tab>" . "TAB")
8952 ("<return>" . "RET")
8953 ("<escape>" . "ESC")
8954 ("<delete>" . "DEL")))
8955 (setq binding (read-kbd-macro
8956 (let ((case-fold-search))
8957 (replace-regexp-in-string
8958 (regexp-quote (cdr rep))
8959 (car rep)
8960 (key-description binding)))))
8961 (cl-pushnew binding new-bindings :test 'equal)))
8962 (dolist (binding new-bindings)
8963 (let ((key (lookup-key orgstruct-mode-map binding)))
8964 (when (or (not key) (numberp key))
8965 (ignore-errors
8966 (org-defkey orgstruct-mode-map
8967 binding
8968 (orgstruct-make-binding
8969 f binding disable-when-heading-prefix))))))))))
8970 (run-hooks 'orgstruct-setup-hook))
8972 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8973 "Create a function for binding in the structure minor mode.
8974 FUN is the command to call inside a table. KEY is the key that
8975 should be checked in for a command to execute outside of tables.
8976 Non-nil `disable-when-heading-prefix' means to disable the command
8977 if `orgstruct-heading-prefix-regexp' is not empty."
8978 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8979 (let ((nname name)
8980 (i 0))
8981 (while (fboundp (intern nname))
8982 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8983 (setq name (intern nname)))
8984 (eval
8985 (let ((bindings '((org-heading-regexp
8986 (concat "^"
8987 orgstruct-heading-prefix-regexp
8988 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8989 (org-outline-regexp
8990 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8991 (org-outline-regexp-bol
8992 (concat "^" org-outline-regexp))
8993 (outline-regexp org-outline-regexp)
8994 (outline-heading-end-regexp "\n")
8995 (outline-level 'org-outline-level)
8996 (outline-heading-alist))))
8997 `(defun ,name (arg)
8998 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8999 "Outside of structure, run the binding of `"
9000 (key-description key) "'."
9001 (when disable-when-heading-prefix
9002 (concat
9003 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9004 "back to the default binding due to limitations of Org's implementation of\n"
9005 "`" (symbol-name fun) "'.")))
9006 (interactive "p")
9007 (let* ((disable
9008 ,(and disable-when-heading-prefix
9009 '(not (string= orgstruct-heading-prefix-regexp ""))))
9010 (fallback
9011 (or disable
9012 (not
9013 (let* ,bindings
9014 (org-context-p 'headline 'item
9015 ,(when (memq fun
9016 '(org-insert-heading
9017 org-insert-heading-respect-content
9018 org-meta-return))
9019 '(when orgstruct-is-++
9020 'item-body))))))))
9021 (if fallback
9022 (let* ((orgstruct-mode)
9023 (binding
9024 (let ((key ,key))
9025 (catch 'exit
9026 (dolist
9027 (rep
9028 '(nil
9029 ("<\\([^>]*\\)tab>" . "\\1TAB")
9030 ("<\\([^>]*\\)return>" . "\\1RET")
9031 ("<\\([^>]*\\)escape>" . "\\1ESC")
9032 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9033 nil)
9034 (when rep
9035 (setq key (read-kbd-macro
9036 (let ((case-fold-search))
9037 (replace-regexp-in-string
9038 (car rep)
9039 (cdr rep)
9040 (key-description key))))))
9041 (when (key-binding key)
9042 (throw 'exit (key-binding key))))))))
9043 (if (keymapp binding)
9044 (org-set-transient-map binding)
9045 (let ((func (or binding
9046 (unless disable
9047 'orgstruct-error))))
9048 (when func
9049 (call-interactively func)))))
9050 (org-run-like-in-org-mode
9051 (lambda ()
9052 (interactive)
9053 (let* ,bindings
9054 (call-interactively ',fun)))))))))
9055 name))
9057 (defun org-contextualize-keys (alist contexts)
9058 "Return valid elements in ALIST depending on CONTEXTS.
9060 `org-agenda-custom-commands' or `org-capture-templates' are the
9061 values used for ALIST, and `org-agenda-custom-commands-contexts'
9062 or `org-capture-templates-contexts' are the associated contexts
9063 definitions."
9064 (let ((contexts
9065 ;; normalize contexts
9066 (mapcar
9067 (lambda(c) (cond ((listp (cadr c))
9068 (list (car c) (car c) (nth 1 c)))
9069 ((string= "" (cadr c))
9070 (list (car c) (car c) (nth 2 c)))
9071 (t c)))
9072 contexts))
9073 (a alist) r s)
9074 ;; loop over all commands or templates
9075 (dolist (c a)
9076 (let (vrules repl)
9077 (cond
9078 ((not (assoc (car c) contexts))
9079 (push c r))
9080 ((and (assoc (car c) contexts)
9081 (setq vrules (org-contextualize-validate-key
9082 (car c) contexts)))
9083 (mapc (lambda (vr)
9084 (unless (equal (car vr) (cadr vr))
9085 (setq repl vr)))
9086 vrules)
9087 (if (not repl) (push c r)
9088 (push (cadr repl) s)
9089 (push
9090 (cons (car c)
9091 (cdr (or (assoc (cadr repl) alist)
9092 (error "Undefined key `%s' as contextual replacement for `%s'"
9093 (cadr repl) (car c)))))
9094 r))))))
9095 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9096 (delq
9098 (delete-dups
9099 (mapcar (lambda (x)
9100 (let ((tpl (car x)))
9101 (unless (delq
9103 (mapcar (lambda (y)
9104 (equal y tpl))
9106 x)))
9107 (reverse r))))))
9109 (defun org-contextualize-validate-key (key contexts)
9110 "Check CONTEXTS for agenda or capture KEY."
9111 (let (res)
9112 (dolist (r contexts)
9113 (dolist (rr (car (last r)))
9114 (when
9115 (and (equal key (car r))
9116 (if (functionp rr) (funcall rr)
9117 (or (and (eq (car rr) 'in-file)
9118 (buffer-file-name)
9119 (string-match (cdr rr) (buffer-file-name)))
9120 (and (eq (car rr) 'in-mode)
9121 (string-match (cdr rr) (symbol-name major-mode)))
9122 (and (eq (car rr) 'in-buffer)
9123 (string-match (cdr rr) (buffer-name)))
9124 (when (and (eq (car rr) 'not-in-file)
9125 (buffer-file-name))
9126 (not (string-match (cdr rr) (buffer-file-name))))
9127 (when (eq (car rr) 'not-in-mode)
9128 (not (string-match (cdr rr) (symbol-name major-mode))))
9129 (when (eq (car rr) 'not-in-buffer)
9130 (not (string-match (cdr rr) (buffer-name)))))))
9131 (push r res))))
9132 (delete-dups (delq nil res))))
9134 (defun org-context-p (&rest contexts)
9135 "Check if local context is any of CONTEXTS.
9136 Possible values in the list of contexts are `table', `headline', and `item'."
9137 (let ((pos (point)))
9138 (goto-char (point-at-bol))
9139 (prog1 (or (and (memq 'table contexts)
9140 (looking-at "[ \t]*|"))
9141 (and (memq 'headline contexts)
9142 (looking-at org-outline-regexp))
9143 (and (memq 'item contexts)
9144 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9145 (and (memq 'item-body contexts)
9146 (org-in-item-p)))
9147 (goto-char pos))))
9149 ;;;###autoload
9150 (defun org-run-like-in-org-mode (cmd)
9151 "Run a command, pretending that the current buffer is in Org mode.
9152 This will temporarily bind local variables that are typically bound in
9153 Org mode to the values they have in Org mode, and then interactively
9154 call CMD."
9155 (org-load-modules-maybe)
9156 (unless org-local-vars
9157 (setq org-local-vars (org-get-local-variables)))
9158 (let (binds)
9159 (dolist (var org-local-vars)
9160 (when (or (not (boundp (car var)))
9161 (eq (symbol-value (car var))
9162 (default-value (car var))))
9163 (push (list (car var) `(quote ,(cadr var))) binds)))
9164 (eval `(let ,binds
9165 (call-interactively (quote ,cmd))))))
9167 (defun org-get-category (&optional pos force-refresh)
9168 "Get the category applying to position POS."
9169 (save-match-data
9170 (when force-refresh (org-refresh-category-properties))
9171 (let ((pos (or pos (point))))
9172 (or (get-text-property pos 'org-category)
9173 (progn (org-refresh-category-properties)
9174 (get-text-property pos 'org-category))))))
9176 ;;; Refresh properties
9178 (defun org-refresh-properties (dprop tprop)
9179 "Refresh buffer text properties.
9180 DPROP is the drawer property and TPROP is either the
9181 corresponding text property to set, or an alist with each element
9182 being a text property (as a symbol) and a function to apply to
9183 the value of the drawer property."
9184 (let* ((case-fold-search t)
9185 (inhibit-read-only t)
9186 (inherit? (org-property-inherit-p dprop))
9187 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9188 (global (and inherit? (org--property-global-value dprop nil))))
9189 (org-with-silent-modifications
9190 (org-with-point-at 1
9191 ;; Set global values (e.g., values defined through
9192 ;; "#+PROPERTY:" keywords) to the whole buffer.
9193 (when global (put-text-property (point-min) (point-max) tprop global))
9194 ;; Set local values.
9195 (while (re-search-forward property-re nil t)
9196 (when (org-at-property-p)
9197 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9198 (outline-next-heading))))))
9200 (defun org-refresh-property (tprop p &optional inherit)
9201 "Refresh the buffer text property TPROP from the drawer property P.
9202 The refresh happens only for the current headline, or the whole
9203 sub-tree if optional argument INHERIT is non-nil."
9204 (unless (org-before-first-heading-p)
9205 (save-excursion
9206 (org-back-to-heading t)
9207 (let ((start (point))
9208 (end (save-excursion
9209 (if inherit (org-end-of-subtree t t)
9210 (or (outline-next-heading) (point-max))))))
9211 (if (symbolp tprop)
9212 ;; TPROP is a text property symbol.
9213 (put-text-property start end tprop p)
9214 ;; TPROP is an alist with (property . function) elements.
9215 (pcase-dolist (`(,prop . ,f) tprop)
9216 (put-text-property start end prop (funcall f p))))))))
9218 (defun org-refresh-category-properties ()
9219 "Refresh category text properties in the buffer."
9220 (let ((case-fold-search t)
9221 (inhibit-read-only t)
9222 (default-category
9223 (cond ((null org-category)
9224 (if buffer-file-name
9225 (file-name-sans-extension
9226 (file-name-nondirectory buffer-file-name))
9227 "???"))
9228 ((symbolp org-category) (symbol-name org-category))
9229 (t org-category))))
9230 (org-with-silent-modifications
9231 (org-with-wide-buffer
9232 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9233 ;; This is the default category for the buffer. If none is
9234 ;; found, fall-back to `org-category' or buffer file name.
9235 (put-text-property
9236 (point-min) (point-max)
9237 'org-category
9238 (catch 'buffer-category
9239 (goto-char (point-max))
9240 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9241 (let ((element (org-element-at-point)))
9242 (when (eq (org-element-type element) 'keyword)
9243 (throw 'buffer-category
9244 (org-element-property :value element)))))
9245 default-category))
9246 ;; Set sub-tree specific categories.
9247 (goto-char (point-min))
9248 (let ((regexp (org-re-property "CATEGORY")))
9249 (while (re-search-forward regexp nil t)
9250 (let ((value (match-string-no-properties 3)))
9251 (when (org-at-property-p)
9252 (put-text-property
9253 (save-excursion (org-back-to-heading t) (point))
9254 (save-excursion (org-end-of-subtree t t) (point))
9255 'org-category
9256 value)))))))))
9258 (defun org-refresh-stats-properties ()
9259 "Refresh stats text properties in the buffer."
9260 (org-with-silent-modifications
9261 (org-with-point-at 1
9262 (let ((regexp (concat org-outline-regexp-bol
9263 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9264 (while (re-search-forward regexp nil t)
9265 (let* ((numerator (string-to-number (match-string 1)))
9266 (denominator (and (match-end 2)
9267 (string-to-number (match-string 2))))
9268 (stats (cond ((not denominator) numerator) ;percent
9269 ((= denominator 0) 0)
9270 (t (/ (* numerator 100) denominator)))))
9271 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9272 'org-stats stats)))))))
9274 (defun org-refresh-effort-properties ()
9275 "Refresh effort properties"
9276 (org-refresh-properties
9277 org-effort-property
9278 '((effort . identity)
9279 (effort-minutes . org-duration-to-minutes))))
9281 ;;;; Link Stuff
9283 ;;; Link abbreviations
9285 (defun org-link-expand-abbrev (link)
9286 "Apply replacements as defined in `org-link-abbrev-alist'."
9287 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9288 (let* ((key (match-string 1 link))
9289 (as (or (assoc key org-link-abbrev-alist-local)
9290 (assoc key org-link-abbrev-alist)))
9291 (tag (and (match-end 2) (match-string 3 link)))
9292 rpl)
9293 (if (not as)
9294 link
9295 (setq rpl (cdr as))
9296 (cond
9297 ((symbolp rpl) (funcall rpl tag))
9298 ((string-match "%(\\([^)]+\\))" rpl)
9299 (replace-match
9300 (save-match-data
9301 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9302 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9303 ((string-match "%h" rpl)
9304 (replace-match (url-hexify-string (or tag "")) t t rpl))
9305 (t (concat rpl tag)))))
9306 link))
9308 ;;; Storing and inserting links
9310 (defvar org-insert-link-history nil
9311 "Minibuffer history for links inserted with `org-insert-link'.")
9313 (defvar org-stored-links nil
9314 "Contains the links stored with `org-store-link'.")
9316 (defvar org-store-link-plist nil
9317 "Plist with info about the most recently link created with `org-store-link'.")
9319 (defun org-store-link-functions ()
9320 "Return a list of functions that are called to create and store a link.
9321 The functions defined in the :store property of
9322 `org-link-parameters'.
9324 Each function will be called in turn until one returns a non-nil
9325 value. Each function should check if it is responsible for
9326 creating this link (for example by looking at the major mode).
9327 If not, it must exit and return nil. If yes, it should return
9328 a non-nil value after calling `org-store-link-props' with a list
9329 of properties and values. Special properties are:
9331 :type The link prefix, like \"http\". This must be given.
9332 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9333 This is obligatory as well.
9334 :description Optional default description for the second pair
9335 of brackets in an Org mode link. The user can still change
9336 this when inserting this link into an Org mode buffer.
9338 In addition to these, any additional properties can be specified
9339 and then used in capture templates."
9340 (cl-loop for link in org-link-parameters
9341 with store-func
9342 do (setq store-func (org-link-get-parameter (car link) :store))
9343 if store-func
9344 collect store-func))
9346 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9347 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9349 ;;;###autoload
9350 (defun org-store-link (arg)
9351 "Store an org-link to the current location.
9352 \\<org-mode-map>
9353 This link is added to `org-stored-links' and can later be inserted
9354 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9356 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9357 A single
9358 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9359 `org-gnus-prefer-web-links' for links to Usenet articles.
9361 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9362 skipping storing functions that are not
9363 part of Org core.
9365 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9366 prefix ARG forces storing a link for each line in the
9367 active region."
9368 (interactive "P")
9369 (org-load-modules-maybe)
9370 (if (and (equal arg '(64)) (org-region-active-p))
9371 (save-excursion
9372 (let ((end (region-end)))
9373 (goto-char (region-beginning))
9374 (set-mark (point))
9375 (while (< (point-at-eol) end)
9376 (move-end-of-line 1) (activate-mark)
9377 (let (current-prefix-arg)
9378 (call-interactively 'org-store-link))
9379 (move-beginning-of-line 2)
9380 (set-mark (point)))))
9381 (setq org-store-link-plist nil)
9382 (let (link cpltxt desc description search txt custom-id agenda-link)
9383 (cond
9384 ;; Store a link using an external link type, if any function is
9385 ;; available. If more than one can generate a link from current
9386 ;; location, ask which one to use.
9387 ((and (not (equal arg '(16)))
9388 (let ((results-alist nil))
9389 (dolist (f (org-store-link-functions))
9390 (when (funcall f)
9391 ;; XXX: return value is not link's plist, so we
9392 ;; store the new value before it is modified. It
9393 ;; would be cleaner to ask store link functions to
9394 ;; return the plist instead.
9395 (push (cons f (copy-sequence org-store-link-plist))
9396 results-alist)))
9397 (pcase results-alist
9398 (`nil nil)
9399 (`((,_ . ,_)) t) ;single choice: nothing to do
9400 (`((,name . ,_) . ,_)
9401 ;; Reinstate link plist associated to the chosen
9402 ;; function.
9403 (apply #'org-store-link-props
9404 (cdr (assoc-string
9405 (completing-read
9406 "Which function for creating the link? "
9407 (mapcar #'car results-alist) nil t name)
9408 results-alist)))
9409 t))))
9410 (setq link (plist-get org-store-link-plist :link))
9411 (setq desc (or (plist-get org-store-link-plist :description)
9412 link)))
9414 ;; Store a link from a source code buffer.
9415 ((org-src-edit-buffer-p)
9416 (let ((coderef-format (org-src-coderef-format)))
9417 (cond ((save-excursion
9418 (beginning-of-line)
9419 (looking-at (org-src-coderef-regexp coderef-format)))
9420 (setq link (format "(%s)" (match-string-no-properties 3))))
9421 ((called-interactively-p 'any)
9422 (let ((label (read-string "Code line label: ")))
9423 (end-of-line)
9424 (setq link (format coderef-format label))
9425 (let ((gc (- 79 (length link))))
9426 (if (< (current-column) gc)
9427 (org-move-to-column gc t)
9428 (insert " ")))
9429 (insert link)
9430 (setq link (concat "(" label ")"))
9431 (setq desc nil)))
9432 (t (setq link nil)))))
9434 ;; We are in the agenda, link to referenced location
9435 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9436 (let ((m (or (get-text-property (point) 'org-hd-marker)
9437 (get-text-property (point) 'org-marker))))
9438 (when m
9439 (org-with-point-at m
9440 (setq agenda-link
9441 (if (called-interactively-p 'any)
9442 (call-interactively 'org-store-link)
9443 (org-store-link nil)))))))
9445 ((eq major-mode 'calendar-mode)
9446 (let ((cd (calendar-cursor-to-date)))
9447 (setq link
9448 (format-time-string
9449 (car org-time-stamp-formats)
9450 (apply 'encode-time
9451 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9452 nil nil nil))))
9453 (org-store-link-props :type "calendar" :date cd)))
9455 ((eq major-mode 'help-mode)
9456 (setq link (concat "help:" (save-excursion
9457 (goto-char (point-min))
9458 (looking-at "^[^ ]+")
9459 (match-string 0))))
9460 (org-store-link-props :type "help"))
9462 ((eq major-mode 'w3-mode)
9463 (setq cpltxt (if (and (buffer-name)
9464 (not (string-match "Untitled" (buffer-name))))
9465 (buffer-name)
9466 (url-view-url t))
9467 link (url-view-url t))
9468 (org-store-link-props :type "w3" :url (url-view-url t)))
9470 ((eq major-mode 'image-mode)
9471 (setq cpltxt (concat "file:"
9472 (abbreviate-file-name buffer-file-name))
9473 link cpltxt)
9474 (org-store-link-props :type "image" :file buffer-file-name))
9476 ;; In dired, store a link to the file of the current line
9477 ((derived-mode-p 'dired-mode)
9478 (let ((file (dired-get-filename nil t)))
9479 (setq file (if file
9480 (abbreviate-file-name
9481 (expand-file-name (dired-get-filename nil t)))
9482 ;; otherwise, no file so use current directory.
9483 default-directory))
9484 (setq cpltxt (concat "file:" file)
9485 link cpltxt)))
9487 ((setq search (run-hook-with-args-until-success
9488 'org-create-file-search-functions))
9489 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9490 "::" search))
9491 (setq cpltxt (or description link)))
9493 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9494 (org-with-limited-levels
9495 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9496 (cond
9497 ;; Store a link using the target at point
9498 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9499 (setq cpltxt
9500 (concat "file:"
9501 (abbreviate-file-name
9502 (buffer-file-name (buffer-base-buffer)))
9503 "::" (match-string 1))
9504 link cpltxt))
9505 ((and (featurep 'org-id)
9506 (or (eq org-id-link-to-org-use-id t)
9507 (and (called-interactively-p 'any)
9508 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9509 (and (eq org-id-link-to-org-use-id
9510 'create-if-interactive-and-no-custom-id)
9511 (not custom-id))))
9512 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9513 ;; Store a link using the ID at point
9514 (setq link (condition-case nil
9515 (prog1 (org-id-store-link)
9516 (setq desc (or (plist-get org-store-link-plist
9517 :description)
9518 "")))
9519 (error
9520 ;; Probably before first headline, link only to file
9521 (concat "file:"
9522 (abbreviate-file-name
9523 (buffer-file-name (buffer-base-buffer))))))))
9525 ;; Just link to current headline
9526 (setq cpltxt (concat "file:"
9527 (abbreviate-file-name
9528 (buffer-file-name (buffer-base-buffer)))))
9529 ;; Add a context search string
9530 (when (org-xor org-context-in-file-links
9531 (equal arg '(4)))
9532 (let* ((element (org-element-at-point))
9533 (name (org-element-property :name element)))
9534 (setq txt (cond
9535 ((org-at-heading-p) nil)
9536 (name)
9537 ((org-region-active-p)
9538 (buffer-substring (region-beginning) (region-end)))))
9539 (when (or (null txt) (string-match "\\S-" txt))
9540 (setq cpltxt
9541 (concat cpltxt "::"
9542 (condition-case nil
9543 (org-make-org-heading-search-string txt)
9544 (error "")))
9545 desc (or name
9546 (nth 4 (ignore-errors (org-heading-components)))
9547 "NONE")))))
9548 (when (string-match "::\\'" cpltxt)
9549 (setq cpltxt (substring cpltxt 0 -2)))
9550 (setq link cpltxt)))))
9552 ((buffer-file-name (buffer-base-buffer))
9553 ;; Just link to this file here.
9554 (setq cpltxt (concat "file:"
9555 (abbreviate-file-name
9556 (buffer-file-name (buffer-base-buffer)))))
9557 ;; Add a context string.
9558 (when (org-xor org-context-in-file-links
9559 (equal arg '(4)))
9560 (setq txt (if (org-region-active-p)
9561 (buffer-substring (region-beginning) (region-end))
9562 (buffer-substring (point-at-bol) (point-at-eol))))
9563 ;; Only use search option if there is some text.
9564 (when (string-match "\\S-" txt)
9565 (setq cpltxt
9566 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9567 desc "NONE")))
9568 (setq link cpltxt))
9570 ((called-interactively-p 'interactive)
9571 (user-error "No method for storing a link from this buffer"))
9573 (t (setq link nil)))
9575 ;; We're done setting link and desc, clean up
9576 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9577 (setq link (or link cpltxt)
9578 desc (or desc cpltxt))
9579 (cond ((not desc))
9580 ((equal desc "NONE") (setq desc nil))
9581 (t (setq desc
9582 (replace-regexp-in-string
9583 org-bracket-link-analytic-regexp
9584 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9585 desc))))
9586 ;; Return the link
9587 (if (not (and (or (called-interactively-p 'any)
9588 executing-kbd-macro)
9589 link))
9590 (or agenda-link (and link (org-make-link-string link desc)))
9591 (push (list link desc) org-stored-links)
9592 (message "Stored: %s" (or desc link))
9593 (when custom-id
9594 (setq link (concat "file:" (abbreviate-file-name
9595 (buffer-file-name)) "::#" custom-id))
9596 (push (list link desc) org-stored-links))
9597 (car org-stored-links)))))
9599 (defun org-store-link-props (&rest plist)
9600 "Store link properties.
9601 The properties are pre-processed by extracting names, addresses
9602 and dates."
9603 (let ((x (plist-get plist :from)))
9604 (when x
9605 (let ((adr (mail-extract-address-components x)))
9606 (setq plist (plist-put plist :fromname (car adr)))
9607 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9608 (let ((x (plist-get plist :to)))
9609 (when x
9610 (let ((adr (mail-extract-address-components x)))
9611 (setq plist (plist-put plist :toname (car adr)))
9612 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9613 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9614 (when x
9615 (setq plist (plist-put plist :date-timestamp
9616 (format-time-string
9617 (org-time-stamp-format t) x)))
9618 (setq plist (plist-put plist :date-timestamp-inactive
9619 (format-time-string
9620 (org-time-stamp-format t t) x)))))
9621 (let ((from (plist-get plist :from))
9622 (to (plist-get plist :to)))
9623 (when (and from to org-from-is-user-regexp)
9624 (setq plist
9625 (plist-put plist :fromto
9626 (if (string-match org-from-is-user-regexp from)
9627 (concat "to %t")
9628 (concat "from %f"))))))
9629 (setq org-store-link-plist plist))
9631 (defun org-add-link-props (&rest plist)
9632 "Add these properties to the link property list."
9633 (let (key value)
9634 (while plist
9635 (setq key (pop plist) value (pop plist))
9636 (setq org-store-link-plist
9637 (plist-put org-store-link-plist key value)))))
9639 (defun org-email-link-description (&optional fmt)
9640 "Return the description part of an email link.
9641 This takes information from `org-store-link-plist' and formats it
9642 according to FMT (default from `org-email-link-description-format')."
9643 (setq fmt (or fmt org-email-link-description-format))
9644 (let* ((p org-store-link-plist)
9645 (to (plist-get p :toaddress))
9646 (from (plist-get p :fromaddress))
9647 (table
9648 (list
9649 (cons "%c" (plist-get p :fromto))
9650 (cons "%F" (plist-get p :from))
9651 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9652 (cons "%T" (plist-get p :to))
9653 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9654 (cons "%s" (plist-get p :subject))
9655 (cons "%d" (plist-get p :date))
9656 (cons "%m" (plist-get p :message-id)))))
9657 (when (string-match "%c" fmt)
9658 ;; Check if the user wrote this message
9659 (if (and org-from-is-user-regexp from to
9660 (save-match-data (string-match org-from-is-user-regexp from)))
9661 (setq fmt (replace-match "to %t" t t fmt))
9662 (setq fmt (replace-match "from %f" t t fmt))))
9663 (org-replace-escapes fmt table)))
9665 (defun org-make-org-heading-search-string (&optional string)
9666 "Make search string for the current headline or STRING."
9667 (let ((s (or string
9668 (and (derived-mode-p 'org-mode)
9669 (save-excursion
9670 (org-back-to-heading t)
9671 (org-element-property :raw-value (org-element-at-point))))))
9672 (lines org-context-in-file-links))
9673 (unless string (setq s (concat "*" s))) ;Add * for headlines
9674 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9675 (when (and string (integerp lines) (> lines 0))
9676 (let ((slines (org-split-string s "\n")))
9677 (when (< lines (length slines))
9678 (setq s (mapconcat
9679 'identity
9680 (reverse (nthcdr (- (length slines) lines)
9681 (reverse slines))) "\n")))))
9682 (mapconcat #'identity (split-string s) " ")))
9684 (defconst org-link-escape-chars
9685 ;;%20 %5B %5D %25
9686 '(?\s ?\[ ?\] ?%)
9687 "List of characters that should be escaped in a link when stored to Org.
9688 This is the list that is used for internal purposes.")
9690 (defun org-make-link-string (link &optional description)
9691 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9692 (unless (org-string-nw-p link) (error "Empty link"))
9693 (let ((uri (cond ((string-match org-link-types-re link)
9694 (concat (match-string 1 link)
9695 (org-link-escape (substring link (match-end 1)))))
9696 ((or (file-name-absolute-p link)
9697 (string-match-p "\\`\\.\\.?/" link))
9698 (org-link-escape link))
9699 ;; For readability, do not encode space characters
9700 ;; in fuzzy links.
9701 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9702 (description
9703 (and (org-string-nw-p description)
9704 ;; Remove brackets from description, as they are fatal.
9705 (replace-regexp-in-string
9706 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9707 (org-trim description)))))
9708 (format "[[%s]%s]"
9710 (if description (format "[%s]" description) ""))))
9712 (defun org-link-escape (text &optional table merge)
9713 "Return percent escaped representation of TEXT.
9714 TEXT is a string with the text to escape.
9715 Optional argument TABLE is a list with characters that should be
9716 escaped. When nil, `org-link-escape-chars' is used.
9717 If optional argument MERGE is set, merge TABLE into
9718 `org-link-escape-chars'."
9719 (let ((characters-to-encode
9720 (cond ((null table) org-link-escape-chars)
9721 (merge (append org-link-escape-chars table))
9722 (t table))))
9723 (mapconcat
9724 (lambda (c)
9725 (if (or (memq c characters-to-encode)
9726 (and org-url-hexify-p (or (< c 32) (> c 126))))
9727 (mapconcat (lambda (e) (format "%%%.2X" e))
9728 (or (encode-coding-char c 'utf-8)
9729 (error "Unable to percent escape character: %c" c))
9731 (char-to-string c)))
9732 text "")))
9734 (defun org-link-unescape (str)
9735 "Unhex hexified Unicode parts in string STR.
9736 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9737 reciprocal of `org-link-escape', which see."
9738 (if (org-string-nw-p str)
9739 (replace-regexp-in-string
9740 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9741 str))
9743 (defun org-link-unescape-compound (hex)
9744 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9745 Note: this function also decodes single byte encodings like
9746 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9747 (save-match-data
9748 (let* ((bytes (cdr (split-string hex "%")))
9749 (ret "")
9750 (eat 0)
9751 (sum 0))
9752 (while bytes
9753 (let* ((val (string-to-number (pop bytes) 16))
9754 (shift-xor
9755 (if (= 0 eat)
9756 (cond
9757 ((>= val 252) (cons 6 252))
9758 ((>= val 248) (cons 5 248))
9759 ((>= val 240) (cons 4 240))
9760 ((>= val 224) (cons 3 224))
9761 ((>= val 192) (cons 2 192))
9762 (t (cons 0 0)))
9763 (cons 6 128))))
9764 (when (>= val 192) (setq eat (car shift-xor)))
9765 (setq val (logxor val (cdr shift-xor)))
9766 (setq sum (+ (lsh sum (car shift-xor)) val))
9767 (when (> eat 0) (setq eat (- eat 1)))
9768 (cond
9769 ((= 0 eat) ;multi byte
9770 (setq ret (concat ret (char-to-string sum)))
9771 (setq sum 0))
9772 ((not bytes) ; single byte(s)
9773 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9774 ret)))
9776 (defun org-link-unescape-single-byte-sequence (hex)
9777 "Unhexify hex-encoded single byte character sequences."
9778 (mapconcat (lambda (byte)
9779 (char-to-string (string-to-number byte 16)))
9780 (cdr (split-string hex "%")) ""))
9782 (defun org-fixup-message-id-for-http (s)
9783 "Replace special characters in a message id, so it can be used in an http query."
9784 (when (string-match "%" s)
9785 (setq s (mapconcat (lambda (c)
9786 (if (eq c ?%)
9787 "%25"
9788 (char-to-string c)))
9789 s "")))
9790 (while (string-match "<" s)
9791 (setq s (replace-match "%3C" t t s)))
9792 (while (string-match ">" s)
9793 (setq s (replace-match "%3E" t t s)))
9794 (while (string-match "@" s)
9795 (setq s (replace-match "%40" t t s)))
9798 (defun org-link-prettify (link)
9799 "Return a human-readable representation of LINK.
9800 The car of LINK must be a raw link.
9801 The cdr of LINK must be either a link description or nil."
9802 (let ((desc (or (cadr link) "<no description>")))
9803 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9804 "<" (car link) ">")))
9806 ;;;###autoload
9807 (defun org-insert-link-global ()
9808 "Insert a link like Org mode does.
9809 This command can be called in any mode to insert a link in Org syntax."
9810 (interactive)
9811 (org-load-modules-maybe)
9812 (org-run-like-in-org-mode 'org-insert-link))
9814 (defun org-insert-all-links (arg &optional pre post)
9815 "Insert all links in `org-stored-links'.
9816 When a universal prefix, do not delete the links from `org-stored-links'.
9817 When `ARG' is a number, insert the last N link(s).
9818 `PRE' and `POST' are optional arguments to define a string to
9819 prepend or to append."
9820 (interactive "P")
9821 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9822 (links (copy-sequence org-stored-links))
9823 (pr (or pre "- "))
9824 (po (or post "\n"))
9825 (cnt 1) l)
9826 (if (null org-stored-links)
9827 (message "No link to insert")
9828 (while (and (or (listp arg) (>= arg cnt))
9829 (setq l (if (listp arg)
9830 (pop links)
9831 (pop org-stored-links))))
9832 (setq cnt (1+ cnt))
9833 (insert pr)
9834 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9835 (insert po)))))
9837 (defun org-insert-last-stored-link (arg)
9838 "Insert the last link stored in `org-stored-links'."
9839 (interactive "p")
9840 (org-insert-all-links arg "" "\n"))
9842 (defun org-link-fontify-links-to-this-file ()
9843 "Fontify links to the current file in `org-stored-links'."
9844 (let ((f (buffer-file-name)) a b)
9845 (setq a (mapcar (lambda(l)
9846 (let ((ll (car l)))
9847 (when (and (string-match "^file:\\(.+\\)::" ll)
9848 (equal f (expand-file-name (match-string 1 ll))))
9849 ll)))
9850 org-stored-links))
9851 (when (featurep 'org-id)
9852 (setq b (mapcar (lambda(l)
9853 (let ((ll (car l)))
9854 (when (and (string-match "^id:\\(.+\\)$" ll)
9855 (equal f (expand-file-name
9856 (or (org-id-find-id-file
9857 (match-string 1 ll)) ""))))
9858 ll)))
9859 org-stored-links)))
9860 (mapcar (lambda(l)
9861 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9862 (delq nil (append a b)))))
9864 (defvar org--links-history nil)
9865 (defun org-insert-link (&optional complete-file link-location default-description)
9866 "Insert a link. At the prompt, enter the link.
9868 Completion can be used to insert any of the link protocol prefixes in use.
9870 The history can be used to select a link previously stored with
9871 `org-store-link'. When the empty string is entered (i.e. if you just
9872 press `RET' at the prompt), the link defaults to the most recently
9873 stored link. As `SPC' triggers completion in the minibuffer, you need to
9874 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9876 You will also be prompted for a description, and if one is given, it will
9877 be displayed in the buffer instead of the link.
9879 If there is already a link at point, this command will allow you to edit
9880 link and description parts.
9882 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9883 file name can be
9884 selected using completion. The path to the file will be relative to the
9885 current directory if the file is in the current directory or a subdirectory.
9886 Otherwise, the link will be the absolute path as completed in the minibuffer
9887 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9888 option `org-link-file-path-type'.
9890 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9891 absolute path even if the file is in
9892 the current directory or below.
9894 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9895 prefix negates `org-keep-stored-link-after-insertion'.
9897 If the LINK-LOCATION parameter is non-nil, this value will be used as
9898 the link location instead of reading one interactively.
9900 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9901 be used as the default description. Otherwise, if
9902 `org-make-link-description-function' is non-nil, this function
9903 will be called with the link target, and the result will be the
9904 default link description."
9905 (interactive "P")
9906 (let* ((wcf (current-window-configuration))
9907 (origbuf (current-buffer))
9908 (region (when (org-region-active-p)
9909 (buffer-substring (region-beginning) (region-end))))
9910 (remove (and region (list (region-beginning) (region-end))))
9911 (desc region)
9912 (link link-location)
9913 (abbrevs org-link-abbrev-alist-local)
9914 entry all-prefixes auto-desc)
9915 (cond
9916 (link-location) ; specified by arg, just use it.
9917 ((org-in-regexp org-bracket-link-regexp 1)
9918 ;; We do have a link at point, and we are going to edit it.
9919 (setq remove (list (match-beginning 0) (match-end 0)))
9920 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9921 (setq link (read-string "Link: "
9922 (org-link-unescape
9923 (match-string-no-properties 1)))))
9924 ((or (org-in-regexp org-angle-link-re)
9925 (org-in-regexp org-plain-link-re))
9926 ;; Convert to bracket link
9927 (setq remove (list (match-beginning 0) (match-end 0))
9928 link (read-string "Link: "
9929 (org-unbracket-string "<" ">" (match-string 0)))))
9930 ((member complete-file '((4) (16)))
9931 ;; Completing read for file names.
9932 (setq link (org-file-complete-link complete-file)))
9934 ;; Read link, with completion for stored links.
9935 (org-link-fontify-links-to-this-file)
9936 (org-switch-to-buffer-other-window "*Org Links*")
9937 (with-current-buffer "*Org Links*"
9938 (erase-buffer)
9939 (insert "Insert a link.
9940 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9941 (when org-stored-links
9942 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9943 (insert (mapconcat 'org-link-prettify
9944 (reverse org-stored-links) "\n")))
9945 (goto-char (point-min)))
9946 (let ((cw (selected-window)))
9947 (select-window (get-buffer-window "*Org Links*" 'visible))
9948 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9949 (unless (pos-visible-in-window-p (point-max))
9950 (org-fit-window-to-buffer))
9951 (and (window-live-p cw) (select-window cw)))
9952 (setq all-prefixes (append (mapcar 'car abbrevs)
9953 (mapcar 'car org-link-abbrev-alist)
9954 (org-link-types)))
9955 (unwind-protect
9956 ;; Fake a link history, containing the stored links.
9957 (let ((org--links-history
9958 (append (mapcar #'car org-stored-links)
9959 org-insert-link-history)))
9960 (setq link
9961 (org-completing-read
9962 "Link: "
9963 (append
9964 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9965 (mapcar #'car org-stored-links))
9966 nil nil nil
9967 'org--links-history
9968 (caar org-stored-links)))
9969 (unless (org-string-nw-p link) (user-error "No link selected"))
9970 (dolist (l org-stored-links)
9971 (when (equal link (cadr l))
9972 (setq link (car l))
9973 (setq auto-desc t)))
9974 (when (or (member link all-prefixes)
9975 (and (equal ":" (substring link -1))
9976 (member (substring link 0 -1) all-prefixes)
9977 (setq link (substring link 0 -1))))
9978 (setq link (with-current-buffer origbuf
9979 (org-link-try-special-completion link)))))
9980 (set-window-configuration wcf)
9981 (kill-buffer "*Org Links*"))
9982 (setq entry (assoc link org-stored-links))
9983 (or entry (push link org-insert-link-history))
9984 (setq desc (or desc (nth 1 entry)))))
9986 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9987 (not org-keep-stored-link-after-insertion))
9988 (setq org-stored-links (delq (assoc link org-stored-links)
9989 org-stored-links)))
9991 (when (and (string-match org-plain-link-re link)
9992 (not (string-match org-ts-regexp link)))
9993 ;; URL-like link, normalize the use of angular brackets.
9994 (setq link (org-unbracket-string "<" ">" link)))
9996 ;; Check if we are linking to the current file with a search
9997 ;; option If yes, simplify the link by using only the search
9998 ;; option.
9999 (when (and buffer-file-name
10000 (let ((case-fold-search nil))
10001 (string-match "\\`file:\\(.+?\\)::" link)))
10002 (let ((path (match-string-no-properties 1 link))
10003 (search (substring-no-properties link (match-end 0))))
10004 (save-match-data
10005 (when (equal (file-truename buffer-file-name) (file-truename path))
10006 ;; We are linking to this same file, with a search option
10007 (setq link search)))))
10009 ;; Check if we can/should use a relative path. If yes, simplify
10010 ;; the link.
10011 (let ((case-fold-search nil))
10012 (when (string-match "\\`\\(file\\|docview\\):" link)
10013 (let* ((type (match-string-no-properties 0 link))
10014 (path-start (match-end 0))
10015 (search (and (string-match "::\\(.*\\)\\'" link)
10016 (match-string 1 link)))
10017 (path
10018 (if search
10019 (substring-no-properties
10020 link path-start (match-beginning 0))
10021 (substring-no-properties link (match-end 0))))
10022 (origpath path))
10023 (cond
10024 ((or (eq org-link-file-path-type 'absolute)
10025 (equal complete-file '(16)))
10026 (setq path (abbreviate-file-name (expand-file-name path))))
10027 ((eq org-link-file-path-type 'noabbrev)
10028 (setq path (expand-file-name path)))
10029 ((eq org-link-file-path-type 'relative)
10030 (setq path (file-relative-name path)))
10032 (save-match-data
10033 (if (string-match (concat "^" (regexp-quote
10034 (expand-file-name
10035 (file-name-as-directory
10036 default-directory))))
10037 (expand-file-name path))
10038 ;; We are linking a file with relative path name.
10039 (setq path (substring (expand-file-name path)
10040 (match-end 0)))
10041 (setq path (abbreviate-file-name (expand-file-name path)))))))
10042 (setq link (concat type path (and search (concat "::" search))))
10043 (when (equal desc origpath)
10044 (setq desc path)))))
10046 (unless auto-desc
10047 (let ((initial-input
10048 (cond
10049 (default-description)
10050 ((not org-make-link-description-function) desc)
10051 (t (condition-case nil
10052 (funcall org-make-link-description-function link desc)
10053 (error
10054 (message "Can't get link description from `%s'"
10055 (symbol-name org-make-link-description-function))
10056 (sit-for 2)
10057 nil))))))
10058 (setq desc (read-string "Description: " initial-input))))
10060 (unless (string-match "\\S-" desc) (setq desc nil))
10061 (when remove (apply 'delete-region remove))
10062 (insert (org-make-link-string link desc))
10063 ;; Redisplay so as the new link has proper invisible characters.
10064 (sit-for 0)))
10066 (defun org-link-try-special-completion (type)
10067 "If there is completion support for link type TYPE, offer it."
10068 (let ((fun (org-link-get-parameter type :complete)))
10069 (if (functionp fun)
10070 (funcall fun)
10071 (read-string "Link (no completion support): " (concat type ":")))))
10073 (defun org-file-complete-link (&optional arg)
10074 "Create a file link using completion."
10075 (let ((file (read-file-name "File: "))
10076 (pwd (file-name-as-directory (expand-file-name ".")))
10077 (pwd1 (file-name-as-directory (abbreviate-file-name
10078 (expand-file-name ".")))))
10079 (cond ((equal arg '(16))
10080 (concat "file:"
10081 (abbreviate-file-name (expand-file-name file))))
10082 ((string-match
10083 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10084 (concat "file:" (match-string 1 file)))
10085 ((string-match
10086 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10087 (expand-file-name file))
10088 (concat "file:"
10089 (match-string 1 (expand-file-name file))))
10090 (t (concat "file:" file)))))
10093 ;;; Opening/following a link
10095 (defvar org-link-search-failed nil)
10097 (defvar org-open-link-functions nil
10098 "Hook for functions finding a plain text link.
10099 These functions must take a single argument, the link content.
10100 They will be called for links that look like [[link text][description]]
10101 when LINK TEXT does not have a protocol like \"http:\" and does not look
10102 like a filename (e.g. \"./blue.png\").
10104 These functions will be called *before* Org attempts to resolve the
10105 link by doing text searches in the current buffer - so if you want a
10106 link \"[[target]]\" to still find \"<<target>>\", your function should
10107 handle this as a special case.
10109 When the function does handle the link, it must return a non-nil value.
10110 If it decides that it is not responsible for this link, it must return
10111 nil to indicate that that Org can continue with other options like
10112 exact and fuzzy text search.")
10114 (defun org-next-link (&optional search-backward)
10115 "Move forward to the next link.
10116 If the link is in hidden text, expose it."
10117 (interactive "P")
10118 (when (and org-link-search-failed (eq this-command last-command))
10119 (goto-char (point-min))
10120 (message "Link search wrapped back to beginning of buffer"))
10121 (setq org-link-search-failed nil)
10122 (let* ((pos (point))
10123 (ct (org-context))
10124 (a (assq :link ct))
10125 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10126 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10127 ((looking-at org-any-link-re)
10128 ;; Don't stay stuck at link without an org-link face
10129 (forward-char (if search-backward -1 1))))
10130 (if (funcall srch-fun org-any-link-re nil t)
10131 (progn
10132 (goto-char (match-beginning 0))
10133 (when (org-invisible-p) (org-show-context)))
10134 (goto-char pos)
10135 (setq org-link-search-failed t)
10136 (message "No further link found"))))
10138 (defun org-previous-link ()
10139 "Move backward to the previous link.
10140 If the link is in hidden text, expose it."
10141 (interactive)
10142 (funcall 'org-next-link t))
10144 (defun org-translate-link (s)
10145 "Translate a link string if a translation function has been defined."
10146 (with-temp-buffer
10147 (insert (org-trim s))
10148 (org-trim (org-element-interpret-data (org-element-context)))))
10150 (defun org-translate-link-from-planner (type path)
10151 "Translate a link from Emacs Planner syntax so that Org can follow it.
10152 This is still an experimental function, your mileage may vary."
10153 (cond
10154 ((member type '("http" "https" "news" "ftp"))
10155 ;; standard Internet links are the same.
10156 nil)
10157 ((and (equal type "irc") (string-match "^//" path))
10158 ;; Planner has two / at the beginning of an irc link, we have 1.
10159 ;; We should have zero, actually....
10160 (setq path (substring path 1)))
10161 ((and (equal type "lisp") (string-match "^/" path))
10162 ;; Planner has a slash, we do not.
10163 (setq type "elisp" path (substring path 1)))
10164 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10165 ;; A typical message link. Planner has the id after the final slash,
10166 ;; we separate it with a hash mark
10167 (setq path (concat (match-string 1 path) "#"
10168 (org-unbracket-string "<" ">" (match-string 2 path))))))
10169 (cons type path))
10171 (defun org-find-file-at-mouse (ev)
10172 "Open file link or URL at mouse."
10173 (interactive "e")
10174 (mouse-set-point ev)
10175 (org-open-at-point 'in-emacs))
10177 (defun org-open-at-mouse (ev)
10178 "Open file link or URL at mouse.
10179 See the docstring of `org-open-file' for details."
10180 (interactive "e")
10181 (mouse-set-point ev)
10182 (when (eq major-mode 'org-agenda-mode)
10183 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10184 (org-open-at-point))
10186 (defvar org-window-config-before-follow-link nil
10187 "The window configuration before following a link.
10188 This is saved in case the need arises to restore it.")
10190 ;;;###autoload
10191 (defun org-open-at-point-global ()
10192 "Follow a link or time-stamp like Org mode does.
10193 This command can be called in any mode to follow an external link
10194 or a time-stamp that has Org mode syntax. Its behavior is
10195 undefined when called on internal links (e.g., fuzzy links).
10196 Raise an error when there is nothing to follow. "
10197 (interactive)
10198 (cond ((org-in-regexp org-any-link-re)
10199 (org-open-link-from-string (match-string-no-properties 0)))
10200 ((or (org-in-regexp org-ts-regexp-both nil t)
10201 (org-in-regexp org-tsr-regexp-both nil t))
10202 (org-follow-timestamp-link))
10203 (t (user-error "No link found"))))
10205 ;;;###autoload
10206 (defun org-open-link-from-string (s &optional arg reference-buffer)
10207 "Open a link in the string S, as if it was in Org mode."
10208 (interactive "sLink: \nP")
10209 (let ((reference-buffer (or reference-buffer (current-buffer))))
10210 (with-temp-buffer
10211 (let ((org-inhibit-startup (not reference-buffer)))
10212 (org-mode)
10213 (insert s)
10214 (goto-char (point-min))
10215 (when reference-buffer
10216 (setq org-link-abbrev-alist-local
10217 (with-current-buffer reference-buffer
10218 org-link-abbrev-alist-local)))
10219 (org-open-at-point arg reference-buffer)))))
10221 (defvar org-open-at-point-functions nil
10222 "Hook that is run when following a link at point.
10224 Functions in this hook must return t if they identify and follow
10225 a link at point. If they don't find anything interesting at point,
10226 they must return nil.")
10228 (defvar org-link-search-inhibit-query nil)
10229 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10230 (defun org--open-doi-link (path)
10231 "Open a \"doi\" type link.
10232 PATH is a the path to search for, as a string."
10233 (browse-url (url-encode-url (concat org-doi-server-url path))))
10235 (defun org--open-elisp-link (path)
10236 "Open a \"elisp\" type link.
10237 PATH is the sexp to evaluate, as a string."
10238 (let ((cmd path))
10239 (if (or (and (org-string-nw-p
10240 org-confirm-elisp-link-not-regexp)
10241 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10242 (not org-confirm-elisp-link-function)
10243 (funcall org-confirm-elisp-link-function
10244 (format "Execute \"%s\" as elisp? "
10245 (org-add-props cmd nil 'face 'org-warning))))
10246 (message "%s => %s" cmd
10247 (if (eq (string-to-char cmd) ?\()
10248 (eval (read cmd))
10249 (call-interactively (read cmd))))
10250 (user-error "Abort"))))
10252 (defun org--open-help-link (path)
10253 "Open a \"help\" type link.
10254 PATH is a symbol name, as a string."
10255 (pcase (intern path)
10256 ((and (pred fboundp) variable) (describe-function variable))
10257 ((and (pred boundp) function) (describe-variable function))
10258 (name (user-error "Unknown function or variable: %s" name))))
10260 (defun org--open-shell-link (path)
10261 "Open a \"shell\" type link.
10262 PATH is the command to execute, as a string."
10263 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10264 (cmd path))
10265 (if (or (and (org-string-nw-p
10266 org-confirm-shell-link-not-regexp)
10267 (string-match
10268 org-confirm-shell-link-not-regexp cmd))
10269 (not org-confirm-shell-link-function)
10270 (funcall org-confirm-shell-link-function
10271 (format "Execute \"%s\" in shell? "
10272 (org-add-props cmd nil
10273 'face 'org-warning))))
10274 (progn
10275 (message "Executing %s" cmd)
10276 (shell-command cmd buf)
10277 (when (featurep 'midnight)
10278 (setq clean-buffer-list-kill-buffer-names
10279 (cons (buffer-name buf)
10280 clean-buffer-list-kill-buffer-names))))
10281 (user-error "Abort"))))
10283 (defun org-open-at-point (&optional arg reference-buffer)
10284 "Open link, timestamp, footnote or tags at point.
10286 When point is on a link, follow it. Normally, files will be
10287 opened by an appropriate application. If the optional prefix
10288 argument ARG is non-nil, Emacs will visit the file. With
10289 a double prefix argument, try to open outside of Emacs, in the
10290 application the system uses for this file type.
10292 When point is on a timestamp, open the agenda at the day
10293 specified.
10295 When point is a footnote definition, move to the first reference
10296 found. If it is on a reference, move to the associated
10297 definition.
10299 When point is on a headline, display a list of every link in the
10300 entry, so it is possible to pick one, or all, of them. If point
10301 is on a tag, call `org-tags-view' instead.
10303 When optional argument REFERENCE-BUFFER is non-nil, it should
10304 specify a buffer from where the link search should happen. This
10305 is used internally by `org-open-link-from-string'.
10307 On top of syntactically correct links, this function will also
10308 try to open links and time-stamps in comments, example
10309 blocks... i.e., whenever point is on something looking like
10310 a timestamp or a link."
10311 (interactive "P")
10312 ;; On a code block, open block's results.
10313 (unless (call-interactively 'org-babel-open-src-block-result)
10314 (org-load-modules-maybe)
10315 (setq org-window-config-before-follow-link (current-window-configuration))
10316 (org-remove-occur-highlights nil nil t)
10317 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10318 (let* ((context
10319 ;; Only consider supported types, even if they are not
10320 ;; the closest one.
10321 (org-element-lineage
10322 (org-element-context)
10323 '(clock footnote-definition footnote-reference headline
10324 inlinetask link timestamp)
10326 (type (org-element-type context))
10327 (value (org-element-property :value context)))
10328 (cond
10329 ;; On a headline or an inlinetask, but not on a timestamp,
10330 ;; a link, a footnote reference.
10331 ((memq type '(headline inlinetask))
10332 (org-match-line org-complex-heading-regexp)
10333 (if (and (match-beginning 5)
10334 (>= (point) (match-beginning 5))
10335 (< (point) (match-end 5)))
10336 ;; On tags.
10337 (org-tags-view arg (substring (match-string 5) 0 -1))
10338 ;; Not on tags.
10339 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10340 (`(nil . ,_)
10341 (require 'org-attach)
10342 (org-attach-reveal 'if-exists))
10343 (`(,links . ,links-end)
10344 (dolist (link (if (stringp links) (list links) links))
10345 (search-forward link nil links-end)
10346 (goto-char (match-beginning 0))
10347 (org-open-at-point))))))
10348 ;; On a footnote reference or at definition's label.
10349 ((or (eq type 'footnote-reference)
10350 (and (eq type 'footnote-definition)
10351 (save-excursion
10352 ;; Do not validate action when point is on the
10353 ;; spaces right after the footnote label, in
10354 ;; order to be on par with behaviour on links.
10355 (skip-chars-forward " \t")
10356 (let ((begin
10357 (org-element-property :contents-begin context)))
10358 (if begin (< (point) begin)
10359 (= (org-element-property :post-affiliated context)
10360 (line-beginning-position)))))))
10361 (org-footnote-action))
10362 ;; No valid context. Ignore catch-all types like `headline'.
10363 ;; If point is on something looking like a link or
10364 ;; a time-stamp, try opening it. It may be useful in
10365 ;; comments, example blocks...
10366 ((memq type '(footnote-definition headline inlinetask nil))
10367 (call-interactively #'org-open-at-point-global))
10368 ;; On a clock line, make sure point is on the timestamp
10369 ;; before opening it.
10370 ((and (eq type 'clock)
10371 value
10372 (>= (point) (org-element-property :begin value))
10373 (<= (point) (org-element-property :end value)))
10374 (org-follow-timestamp-link))
10375 ;; Do nothing on white spaces after an object.
10376 ((>= (point)
10377 (save-excursion
10378 (goto-char (org-element-property :end context))
10379 (skip-chars-backward " \t")
10380 (point)))
10381 (user-error "No link found"))
10382 ((eq type 'timestamp) (org-follow-timestamp-link))
10383 ((eq type 'link)
10384 (let ((type (org-element-property :type context))
10385 (path (org-link-unescape (org-element-property :path context))))
10386 ;; Switch back to REFERENCE-BUFFER needed when called in
10387 ;; a temporary buffer through `org-open-link-from-string'.
10388 (with-current-buffer (or reference-buffer (current-buffer))
10389 (cond
10390 ((equal type "file")
10391 (if (string-match "[*?{]" (file-name-nondirectory path))
10392 (dired path)
10393 ;; Look into `org-link-parameters' in order to find
10394 ;; a DEDICATED-FUNCTION to open file. The function
10395 ;; will be applied on raw link instead of parsed
10396 ;; link due to the limitation in `org-add-link-type'
10397 ;; ("open" function called with a single argument).
10398 ;; If no such function is found, fallback to
10399 ;; `org-open-file'.
10400 (let* ((option (org-element-property :search-option context))
10401 (app (org-element-property :application context))
10402 (dedicated-function
10403 (org-link-get-parameter
10404 (if app (concat type "+" app) type)
10405 :follow)))
10406 (if dedicated-function
10407 (funcall dedicated-function
10408 (concat path
10409 (and option (concat "::" option))))
10410 (apply #'org-open-file
10411 path
10412 (cond (arg)
10413 ((equal app "emacs") 'emacs)
10414 ((equal app "sys") 'system))
10415 (cond ((not option) nil)
10416 ((string-match-p "\\`[0-9]+\\'" option)
10417 (list (string-to-number option)))
10418 (t (list nil
10419 (org-link-unescape option)))))))))
10420 ((functionp (org-link-get-parameter type :follow))
10421 (funcall (org-link-get-parameter type :follow) path))
10422 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10423 (unless (run-hook-with-args-until-success
10424 'org-open-link-functions path)
10425 (if (not arg) (org-mark-ring-push)
10426 (switch-to-buffer-other-window
10427 (org-get-buffer-for-internal-link (current-buffer))))
10428 (let ((destination
10429 (org-with-wide-buffer
10430 (if (equal type "radio")
10431 (org-search-radio-target
10432 (org-element-property :path context))
10433 (org-link-search
10434 (if (member type '("custom-id" "coderef"))
10435 (org-element-property :raw-link context)
10436 path)
10437 ;; Prevent fuzzy links from matching
10438 ;; themselves.
10439 (and (equal type "fuzzy")
10440 (+ 2 (org-element-property :begin context)))))
10441 (point))))
10442 (unless (and (<= (point-min) destination)
10443 (>= (point-max) destination))
10444 (widen))
10445 (goto-char destination))))
10446 (t (browse-url-at-point))))))
10447 (t (user-error "No link found")))))
10448 (run-hook-with-args 'org-follow-link-hook)))
10450 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10451 "Offer links in the current entry and return the selected link.
10452 If there is only one link, return it.
10453 If NTH is an integer, return the NTH link found.
10454 If ZERO is a string, check also this string for a link, and if
10455 there is one, return it."
10456 (with-current-buffer buffer
10457 (org-with-wide-buffer
10458 (goto-char marker)
10459 (let ((cnt ?0)
10460 have-zero end links link c)
10461 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10462 (push (match-string 0 zero) links)
10463 (setq cnt (1- cnt) have-zero t))
10464 (save-excursion
10465 (org-back-to-heading t)
10466 (setq end (save-excursion (outline-next-heading) (point)))
10467 (while (re-search-forward org-any-link-re end t)
10468 (push (match-string 0) links))
10469 (setq links (org-uniquify (reverse links))))
10470 (cond
10471 ((null links)
10472 (message "No links"))
10473 ((equal (length links) 1)
10474 (setq link (car links)))
10475 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10476 (setq link (nth (if have-zero nth (1- nth)) links)))
10477 (t ; we have to select a link
10478 (save-excursion
10479 (save-window-excursion
10480 (delete-other-windows)
10481 (with-output-to-temp-buffer "*Select Link*"
10482 (dolist (l links)
10483 (cond
10484 ((not (string-match org-bracket-link-regexp l))
10485 (princ (format "[%c] %s\n" (cl-incf cnt)
10486 (org-unbracket-string "<" ">" l))))
10487 ((match-end 3)
10488 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10489 (match-string 3 l) (match-string 1 l))))
10490 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10491 (match-string 1 l)))))))
10492 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10493 (message "Select link to open, RET to open all:")
10494 (setq c (read-char-exclusive))
10495 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10496 (when (equal c ?q) (user-error "Abort"))
10497 (if (equal c ?\C-m)
10498 (setq link links)
10499 (setq nth (- c ?0))
10500 (when have-zero (setq nth (1+ nth)))
10501 (unless (and (integerp nth) (>= (length links) nth))
10502 (user-error "Invalid link selection"))
10503 (setq link (nth (1- nth) links)))))
10504 (cons link end)))))
10506 ;; TODO: These functions are deprecated since `org-open-at-point'
10507 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10508 (defun org-open-file-with-system (path)
10509 "Open file at PATH using the system way of opening it."
10510 (org-open-file path 'system))
10511 (defun org-open-file-with-emacs (path)
10512 "Open file at PATH in Emacs."
10513 (org-open-file path 'emacs))
10516 ;;; File search
10518 (defvar org-create-file-search-functions nil
10519 "List of functions to construct the right search string for a file link.
10520 These functions are called in turn with point at the location to
10521 which the link should point.
10523 A function in the hook should first test if it would like to
10524 handle this file type, for example by checking the `major-mode'
10525 or the file extension. If it decides not to handle this file, it
10526 should just return nil to give other functions a chance. If it
10527 does handle the file, it must return the search string to be used
10528 when following the link. The search string will be part of the
10529 file link, given after a double colon, and `org-open-at-point'
10530 will automatically search for it. If special measures must be
10531 taken to make the search successful, another function should be
10532 added to the companion hook `org-execute-file-search-functions',
10533 which see.
10535 A function in this hook may also use `setq' to set the variable
10536 `description' to provide a suggestion for the descriptive text to
10537 be used for this link when it gets inserted into an Org buffer
10538 with \\[org-insert-link].")
10540 (defvar org-execute-file-search-functions nil
10541 "List of functions to execute a file search triggered by a link.
10543 Functions added to this hook must accept a single argument, the
10544 search string that was part of the file link, the part after the
10545 double colon. The function must first check if it would like to
10546 handle this search, for example by checking the `major-mode' or
10547 the file extension. If it decides not to handle this search, it
10548 should just return nil to give other functions a chance. If it
10549 does handle the search, it must return a non-nil value to keep
10550 other functions from trying.
10552 Each function can access the current prefix argument through the
10553 variable `current-prefix-arg'. Note that a single prefix is used
10554 to force opening a link in Emacs, so it may be good to only use a
10555 numeric or double prefix to guide the search function.
10557 In case this is needed, a function in this hook can also restore
10558 the window configuration before `org-open-at-point' was called using:
10560 (set-window-configuration org-window-config-before-follow-link)")
10562 (defun org-search-radio-target (target)
10563 "Search a radio target matching TARGET in current buffer.
10564 White spaces are not significant."
10565 (let ((re (format "<<<%s>>>"
10566 (mapconcat #'regexp-quote
10567 (split-string target)
10568 "[ \t]+\\(?:\n[ \t]*\\)?")))
10569 (origin (point)))
10570 (goto-char (point-min))
10571 (catch :radio-match
10572 (while (re-search-forward re nil t)
10573 (backward-char)
10574 (let ((object (org-element-context)))
10575 (when (eq (org-element-type object) 'radio-target)
10576 (goto-char (org-element-property :begin object))
10577 (org-show-context 'link-search)
10578 (throw :radio-match nil))))
10579 (goto-char origin)
10580 (user-error "No match for radio target: %s" target))))
10582 (defun org-link-search (s &optional avoid-pos stealth)
10583 "Search for a search string S.
10585 If S starts with \"#\", it triggers a custom ID search.
10587 If S is enclosed within parenthesis, it initiates a coderef
10588 search.
10590 If S is surrounded by forward slashes, it is interpreted as
10591 a regular expression. In Org mode files, this will create an
10592 `org-occur' sparse tree. In ordinary files, `occur' will be used
10593 to list matches. If the current buffer is in `dired-mode', grep
10594 will be used to search in all files.
10596 When AVOID-POS is given, ignore matches near that position.
10598 When optional argument STEALTH is non-nil, do not modify
10599 visibility around point, thus ignoring `org-show-context-detail'
10600 variable.
10602 Search is case-insensitive and ignores white spaces. Return type
10603 of matched result, which is either `dedicated' or `fuzzy'."
10604 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10605 (let* ((case-fold-search t)
10606 (origin (point))
10607 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10608 (starred (eq (string-to-char normalized) ?*))
10609 (words (split-string (if starred (substring s 1) s)))
10610 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10611 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10612 type)
10613 (cond
10614 ;; Check if there are any special search functions.
10615 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10616 ((eq (string-to-char s) ?#)
10617 ;; Look for a custom ID S if S starts with "#".
10618 (let* ((id (substring normalized 1))
10619 (match (org-find-property "CUSTOM_ID" id)))
10620 (if match (progn (goto-char match) (setf type 'dedicated))
10621 (error "No match for custom ID: %s" id))))
10622 ((string-match "\\`(\\(.*\\))\\'" normalized)
10623 ;; Look for coderef targets if S is enclosed within parenthesis.
10624 (let ((coderef (match-string-no-properties 1 normalized))
10625 (re (substring s-single-re 1 -1)))
10626 (goto-char (point-min))
10627 (catch :coderef-match
10628 (while (re-search-forward re nil t)
10629 (let ((element (org-element-at-point)))
10630 (when (and (memq (org-element-type element)
10631 '(example-block src-block))
10632 ;; Build proper regexp according to current
10633 ;; block's label format.
10634 (let ((label-fmt
10635 (regexp-quote
10636 (or (org-element-property :label-fmt element)
10637 org-coderef-label-format))))
10638 (save-excursion
10639 (beginning-of-line)
10640 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10641 (format label-fmt coderef))))))
10642 (setq type 'dedicated)
10643 (goto-char (match-beginning 1))
10644 (throw :coderef-match nil))))
10645 (goto-char origin)
10646 (error "No match for coderef: %s" coderef))))
10647 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10648 ;; Look for a regular expression.
10649 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10650 (match-string 1 s)))
10651 ;; From here, we handle fuzzy links.
10653 ;; Look for targets, only if not in a headline search.
10654 ((and (not starred)
10655 (let ((target (format "<<%s>>" s-multi-re)))
10656 (catch :target-match
10657 (goto-char (point-min))
10658 (while (re-search-forward target nil t)
10659 (backward-char)
10660 (let ((context (org-element-context)))
10661 (when (eq (org-element-type context) 'target)
10662 (setq type 'dedicated)
10663 (goto-char (org-element-property :begin context))
10664 (throw :target-match t))))
10665 nil))))
10666 ;; Look for elements named after S, only if not in a headline
10667 ;; search.
10668 ((and (not starred)
10669 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10670 (catch :name-match
10671 (goto-char (point-min))
10672 (while (re-search-forward name nil t)
10673 (let ((element (org-element-at-point)))
10674 (when (equal words
10675 (split-string
10676 (org-element-property :name element)))
10677 (setq type 'dedicated)
10678 (beginning-of-line)
10679 (throw :name-match t))))
10680 nil))))
10681 ;; Regular text search. Prefer headlines in Org mode buffers.
10682 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10683 ;; statistics cookies and tags.
10684 ((and (derived-mode-p 'org-mode)
10685 (let ((title-re
10686 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10687 org-outline-regexp-bol
10688 org-comment-string
10689 (mapconcat #'regexp-quote words ".+")))
10690 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10691 (comment-re (eval-when-compile
10692 (format "\\`%s[ \t]+" org-comment-string))))
10693 (goto-char (point-min))
10694 (catch :found
10695 (while (re-search-forward title-re nil t)
10696 (when (equal words
10697 (split-string
10698 (replace-regexp-in-string
10699 cookie-re ""
10700 (replace-regexp-in-string
10701 comment-re "" (org-get-heading t t t)))))
10702 (throw :found t)))
10703 nil)))
10704 (beginning-of-line)
10705 (setq type 'dedicated))
10706 ;; Offer to create non-existent headline depending on
10707 ;; `org-link-search-must-match-exact-headline'.
10708 ((and (derived-mode-p 'org-mode)
10709 (not org-link-search-inhibit-query)
10710 (eq org-link-search-must-match-exact-headline 'query-to-create)
10711 (yes-or-no-p "No match - create this as a new heading? "))
10712 (goto-char (point-max))
10713 (unless (bolp) (newline))
10714 (org-insert-heading nil t t)
10715 (insert s "\n")
10716 (beginning-of-line 0))
10717 ;; Only headlines are looked after. No need to process
10718 ;; further: throw an error.
10719 ((and (derived-mode-p 'org-mode)
10720 (or starred org-link-search-must-match-exact-headline))
10721 (goto-char origin)
10722 (error "No match for fuzzy expression: %s" normalized))
10723 ;; Regular text search.
10724 ((catch :fuzzy-match
10725 (goto-char (point-min))
10726 (while (re-search-forward s-multi-re nil t)
10727 ;; Skip match if it contains AVOID-POS or it is included in
10728 ;; a link with a description but outside the description.
10729 (unless (or (and avoid-pos
10730 (<= (match-beginning 0) avoid-pos)
10731 (> (match-end 0) avoid-pos))
10732 (and (save-match-data
10733 (org-in-regexp org-bracket-link-regexp))
10734 (match-beginning 3)
10735 (or (> (match-beginning 3) (point))
10736 (<= (match-end 3) (point)))
10737 (org-element-lineage
10738 (save-match-data (org-element-context))
10739 '(link) t)))
10740 (goto-char (match-beginning 0))
10741 (setq type 'fuzzy)
10742 (throw :fuzzy-match t)))
10743 nil))
10744 ;; All failed. Throw an error.
10745 (t (goto-char origin)
10746 (error "No match for fuzzy expression: %s" normalized)))
10747 ;; Disclose surroundings of match, if appropriate.
10748 (when (and (derived-mode-p 'org-mode) (not stealth))
10749 (org-show-context 'link-search))
10750 type))
10752 (defun org-get-buffer-for-internal-link (buffer)
10753 "Return a buffer to be used for displaying the link target of internal links."
10754 (cond
10755 ((not org-display-internal-link-with-indirect-buffer)
10756 buffer)
10757 ((string-suffix-p "(Clone)" (buffer-name buffer))
10758 (message "Buffer is already a clone, not making another one")
10759 ;; we also do not modify visibility in this case
10760 buffer)
10761 (t ; make a new indirect buffer for displaying the link
10762 (let* ((bn (buffer-name buffer))
10763 (ibn (concat bn "(Clone)"))
10764 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10765 (with-current-buffer ib (org-overview))
10766 ib))))
10768 (defun org-do-occur (regexp &optional cleanup)
10769 "Call the Emacs command `occur'.
10770 If CLEANUP is non-nil, remove the printout of the regular expression
10771 in the *Occur* buffer. This is useful if the regex is long and not useful
10772 to read."
10773 (occur regexp)
10774 (when cleanup
10775 (let ((cwin (selected-window)) win beg end)
10776 (when (setq win (get-buffer-window "*Occur*"))
10777 (select-window win))
10778 (goto-char (point-min))
10779 (when (re-search-forward "match[a-z]+" nil t)
10780 (setq beg (match-end 0))
10781 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10782 (setq end (1- (match-beginning 0)))))
10783 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10784 (goto-char (point-min))
10785 (select-window cwin))))
10787 ;;; The mark ring for links jumps
10789 (defvar org-mark-ring nil
10790 "Mark ring for positions before jumps in Org mode.")
10791 (defvar org-mark-ring-last-goto nil
10792 "Last position in the mark ring used to go back.")
10793 ;; Fill and close the ring
10794 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10795 (dotimes (_ org-mark-ring-length)
10796 (push (make-marker) org-mark-ring))
10797 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10798 org-mark-ring)
10800 (defun org-mark-ring-push (&optional pos buffer)
10801 "Put the current position or POS into the mark ring and rotate it."
10802 (interactive)
10803 (setq pos (or pos (point)))
10804 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10805 (move-marker (car org-mark-ring)
10806 (or pos (point))
10807 (or buffer (current-buffer)))
10808 (message "%s"
10809 (substitute-command-keys
10810 "Position saved to mark ring, go back with \
10811 `\\[org-mark-ring-goto]'.")))
10813 (defun org-mark-ring-goto (&optional n)
10814 "Jump to the previous position in the mark ring.
10815 With prefix arg N, jump back that many stored positions. When
10816 called several times in succession, walk through the entire ring.
10817 Org mode commands jumping to a different position in the current file,
10818 or to another Org file, automatically push the old position onto the ring."
10819 (interactive "p")
10820 (let (p m)
10821 (if (eq last-command this-command)
10822 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10823 (setq p org-mark-ring))
10824 (setq org-mark-ring-last-goto p)
10825 (setq m (car p))
10826 (pop-to-buffer-same-window (marker-buffer m))
10827 (goto-char m)
10828 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10830 (defun org-add-angle-brackets (s)
10831 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10832 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10835 ;;; Following specific links
10837 (defvar org-agenda-buffer-tmp-name)
10838 (defvar org-agenda-start-on-weekday)
10839 (defun org-follow-timestamp-link ()
10840 "Open an agenda view for the time-stamp date/range at point."
10841 (cond
10842 ((org-at-date-range-p t)
10843 (let ((org-agenda-start-on-weekday)
10844 (t1 (match-string 1))
10845 (t2 (match-string 2)) tt1 tt2)
10846 (setq tt1 (time-to-days (org-time-string-to-time t1))
10847 tt2 (time-to-days (org-time-string-to-time t2)))
10848 (let ((org-agenda-buffer-tmp-name
10849 (format "*Org Agenda(a:%s)"
10850 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10851 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10852 ((org-at-timestamp-p 'lax)
10853 (let ((org-agenda-buffer-tmp-name
10854 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10855 (org-agenda-list nil (time-to-days (org-time-string-to-time
10856 (substring (match-string 1) 0 10)))
10857 1)))
10858 (t (error "This should not happen"))))
10861 ;;; Following file links
10862 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10863 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10864 (declare-function mailcap-mime-info
10865 "mailcap" (string &optional request no-decode))
10866 (defvar org-wait nil)
10867 (defun org-open-file (path &optional in-emacs line search)
10868 "Open the file at PATH.
10869 First, this expands any special file name abbreviations. Then the
10870 configuration variable `org-file-apps' is checked if it contains an
10871 entry for this file type, and if yes, the corresponding command is launched.
10873 If no application is found, Emacs simply visits the file.
10875 With optional prefix argument IN-EMACS, Emacs will visit the file.
10876 With a double \\[universal-argument] \\[universal-argument] \
10877 prefix arg, Org tries to avoid opening in Emacs
10878 and to use an external application to visit the file.
10880 Optional LINE specifies a line to go to, optional SEARCH a string
10881 to search for. If LINE or SEARCH is given, the file will be
10882 opened in Emacs, unless an entry from org-file-apps that makes
10883 use of groups in a regexp matches.
10885 If you want to change the way frames are used when following a
10886 link, please customize `org-link-frame-setup'.
10888 If the file does not exist, an error is thrown."
10889 (let* ((file (if (equal path "")
10890 buffer-file-name
10891 (substitute-in-file-name (expand-file-name path))))
10892 (file-apps (append org-file-apps (org-default-apps)))
10893 (apps (cl-remove-if
10894 'org-file-apps-entry-match-against-dlink-p file-apps))
10895 (apps-dlink (cl-remove-if-not
10896 'org-file-apps-entry-match-against-dlink-p file-apps))
10897 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10898 (dirp (unless remp (file-directory-p file)))
10899 (file (if (and dirp org-open-directory-means-index-dot-org)
10900 (concat (file-name-as-directory file) "index.org")
10901 file))
10902 (a-m-a-p (assq 'auto-mode apps))
10903 (dfile (downcase file))
10904 ;; Reconstruct the original link from the PATH, LINE and
10905 ;; SEARCH args.
10906 (link (cond (line (concat file "::" (number-to-string line)))
10907 (search (concat file "::" search))
10908 (t file)))
10909 (dlink (downcase link))
10910 (ext
10911 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10912 (match-string 1 dfile)))
10913 (save-position-maybe
10914 (let ((old-buffer (current-buffer))
10915 (old-pos (point))
10916 (old-mode major-mode))
10917 (lambda ()
10918 (and (derived-mode-p 'org-mode)
10919 (eq old-mode 'org-mode)
10920 (or (not (eq old-buffer (current-buffer)))
10921 (not (eq old-pos (point))))
10922 (org-mark-ring-push old-pos old-buffer)))))
10923 cmd link-match-data)
10924 (cond
10925 ((member in-emacs '((16) system))
10926 (setq cmd (cdr (assq 'system apps))))
10927 (in-emacs (setq cmd 'emacs))
10929 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10930 (and dirp (cdr (assq 'directory apps)))
10931 ;; First, try matching against apps-dlink if we
10932 ;; get a match here, store the match data for
10933 ;; later.
10934 (let ((match (assoc-default dlink apps-dlink
10935 'string-match)))
10936 (if match
10937 (progn (setq link-match-data (match-data))
10938 match)
10939 (progn (setq in-emacs (or in-emacs line search))
10940 nil))) ; if we have no match in apps-dlink,
10941 ; always open the file in emacs if line or search
10942 ; is given (for backwards compatibility)
10943 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10944 'string-match)
10945 (cdr (assoc ext apps))
10946 (cdr (assq t apps))))))
10947 (when (eq cmd 'system)
10948 (setq cmd (cdr (assq 'system apps))))
10949 (when (eq cmd 'default)
10950 (setq cmd (cdr (assoc t apps))))
10951 (when (eq cmd 'mailcap)
10952 (require 'mailcap)
10953 (mailcap-parse-mailcaps)
10954 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10955 (command (mailcap-mime-info mime-type)))
10956 (if (stringp command)
10957 (setq cmd command)
10958 (setq cmd 'emacs))))
10959 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10960 (not (file-exists-p file))
10961 (not org-open-non-existing-files))
10962 (user-error "No such file: %s" file))
10963 (cond
10964 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10965 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10966 (while (string-match "['\"]%s['\"]" cmd)
10967 (setq cmd (replace-match "%s" t t cmd)))
10968 (setq cmd (replace-regexp-in-string
10969 "%s"
10970 (shell-quote-argument (convert-standard-filename file))
10972 nil t))
10974 ;; Replace "%1", "%2" etc. in command with group matches from regex
10975 (save-match-data
10976 (let ((match-index 1)
10977 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10978 (set-match-data link-match-data)
10979 (while (<= match-index number-of-groups)
10980 (let ((regex (concat "%" (number-to-string match-index)))
10981 (replace-with (match-string match-index dlink)))
10982 (while (string-match regex cmd)
10983 (setq cmd (replace-match replace-with t t cmd))))
10984 (setq match-index (+ match-index 1)))))
10986 (save-window-excursion
10987 (message "Running %s...done" cmd)
10988 (start-process-shell-command cmd nil cmd)
10989 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10990 ((or (stringp cmd)
10991 (eq cmd 'emacs))
10992 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10993 (widen)
10994 (cond (line (org-goto-line line)
10995 (when (derived-mode-p 'org-mode) (org-reveal)))
10996 (search (condition-case err
10997 (org-link-search search)
10998 ;; Save position before error-ing out so user
10999 ;; can easily move back to the original buffer.
11000 (error (funcall save-position-maybe)
11001 (error (nth 1 err)))))))
11002 ((functionp cmd)
11003 (save-match-data
11004 (set-match-data link-match-data)
11005 (condition-case nil
11006 (funcall cmd file link)
11007 ;; FIXME: Remove this check when most default installations
11008 ;; of Emacs have at least Org 9.0.
11009 ((debug wrong-number-of-arguments wrong-type-argument
11010 invalid-function)
11011 (user-error "Please see Org News for version 9.0 about \
11012 `org-file-apps'--Lisp error: %S" cmd)))))
11013 ((consp cmd)
11014 ;; FIXME: Remove this check when most default installations of
11015 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11016 ;; fall back to `org-link-frame-setup' for an old usage of
11017 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11018 (user-error "Please see Org News for version 9.0 about \
11019 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11020 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11021 (funcall save-position-maybe)))
11023 (defun org-file-apps-entry-match-against-dlink-p (entry)
11024 "This function returns non-nil if `entry' uses a regular
11025 expression which should be matched against the whole link by
11026 org-open-file.
11028 It assumes that is the case when the entry uses a regular
11029 expression which has at least one grouping construct and the
11030 action is either a lisp form or a command string containing
11031 `%1', i.e. using at least one subexpression match as a
11032 parameter."
11033 (let ((selector (car entry))
11034 (action (cdr entry)))
11035 (if (stringp selector)
11036 (and (> (regexp-opt-depth selector) 0)
11037 (or (and (stringp action)
11038 (string-match "%[0-9]" action))
11039 (consp action)))
11040 nil)))
11042 (defun org-default-apps ()
11043 "Return the default applications for this operating system."
11044 (cond
11045 ((eq system-type 'darwin)
11046 org-file-apps-defaults-macosx)
11047 ((eq system-type 'windows-nt)
11048 org-file-apps-defaults-windowsnt)
11049 (t org-file-apps-defaults-gnu)))
11051 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11052 "Convert extensions to regular expressions in the cars of LIST.
11053 Also, weed out any non-string entries, because the return value is used
11054 only for regexp matching.
11055 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11056 point to the symbol `emacs', indicating that the file should
11057 be opened in Emacs."
11058 (append
11059 (delq nil
11060 (mapcar (lambda (x)
11061 (unless (not (stringp (car x)))
11062 (if (string-match "\\W" (car x))
11064 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11065 list))
11066 (when add-auto-mode
11067 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11069 (defvar ange-ftp-name-format)
11070 (defun org-file-remote-p (file)
11071 "Test whether FILE specifies a location on a remote system.
11072 Return non-nil if the location is indeed remote.
11074 For example, the filename \"/user@host:/foo\" specifies a location
11075 on the system \"/user@host:\"."
11076 (cond ((fboundp 'file-remote-p)
11077 (file-remote-p file))
11078 ((fboundp 'tramp-handle-file-remote-p)
11079 (tramp-handle-file-remote-p file))
11080 ((and (boundp 'ange-ftp-name-format)
11081 (string-match (car ange-ftp-name-format) file))
11082 t)))
11085 ;;;; Refiling
11087 (defun org-get-org-file ()
11088 "Read a filename, with default directory `org-directory'."
11089 (let ((default (or org-default-notes-file remember-data-file)))
11090 (read-file-name (format "File name [%s]: " default)
11091 (file-name-as-directory org-directory)
11092 default)))
11094 (defun org-notes-order-reversed-p ()
11095 "Check if the current file should receive notes in reversed order."
11096 (cond
11097 ((not org-reverse-note-order) nil)
11098 ((eq t org-reverse-note-order) t)
11099 ((not (listp org-reverse-note-order)) nil)
11100 (t (catch 'exit
11101 (dolist (entry org-reverse-note-order)
11102 (when (string-match (car entry) buffer-file-name)
11103 (throw 'exit (cdr entry))))))))
11105 (defvar org-refile-target-table nil
11106 "The list of refile targets, created by `org-refile'.")
11108 (defvar org-agenda-new-buffers nil
11109 "Buffers created to visit agenda files.")
11111 (defvar org-refile-cache nil
11112 "Cache for refile targets.")
11114 (defvar org-refile-markers nil
11115 "All the markers used for caching refile locations.")
11117 (defun org-refile-marker (pos)
11118 "Get a new refile marker, but only if caching is in use."
11119 (if (not org-refile-use-cache)
11121 (let ((m (make-marker)))
11122 (move-marker m pos)
11123 (push m org-refile-markers)
11124 m)))
11126 (defun org-refile-cache-clear ()
11127 "Clear the refile cache and disable all the markers."
11128 (dolist (m org-refile-markers) (move-marker m nil))
11129 (setq org-refile-markers nil)
11130 (setq org-refile-cache nil)
11131 (message "Refile cache has been cleared"))
11133 (defun org-refile-cache-check-set (set)
11134 "Check if all the markers in the cache still have live buffers."
11135 (let (marker)
11136 (catch 'exit
11137 (while (and set (setq marker (nth 3 (pop set))))
11138 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11139 (when (and marker (null (marker-buffer marker)))
11140 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11141 (sit-for 3)
11142 (throw 'exit nil)))
11143 t)))
11145 (defun org-refile-cache-put (set &rest identifiers)
11146 "Push the refile targets SET into the cache, under IDENTIFIERS."
11147 (let* ((key (sha1 (prin1-to-string identifiers)))
11148 (entry (assoc key org-refile-cache)))
11149 (if entry
11150 (setcdr entry set)
11151 (push (cons key set) org-refile-cache))))
11153 (defun org-refile-cache-get (&rest identifiers)
11154 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11155 (cond
11156 ((not org-refile-cache) nil)
11157 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11159 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11160 org-refile-cache))))
11161 (and set (org-refile-cache-check-set set) set)))))
11163 (defvar org-outline-path-cache nil
11164 "Alist between buffer positions and outline paths.
11165 It value is an alist (POSITION . PATH) where POSITION is the
11166 buffer position at the beginning of an entry and PATH is a list
11167 of strings describing the outline path for that entry, in reverse
11168 order.")
11170 (defun org-refile-get-targets (&optional default-buffer)
11171 "Produce a table with refile targets."
11172 (let ((case-fold-search nil)
11173 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11174 (entries (or org-refile-targets '((nil . (:level . 1)))))
11175 targets tgs files desc descre)
11176 (message "Getting targets...")
11177 (with-current-buffer (or default-buffer (current-buffer))
11178 (dolist (entry entries)
11179 (setq files (car entry) desc (cdr entry))
11180 (cond
11181 ((null files) (setq files (list (current-buffer))))
11182 ((eq files 'org-agenda-files)
11183 (setq files (org-agenda-files 'unrestricted)))
11184 ((and (symbolp files) (fboundp files))
11185 (setq files (funcall files)))
11186 ((and (symbolp files) (boundp files))
11187 (setq files (symbol-value files))))
11188 (when (stringp files) (setq files (list files)))
11189 (cond
11190 ((eq (car desc) :tag)
11191 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11192 ((eq (car desc) :todo)
11193 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11194 ((eq (car desc) :regexp)
11195 (setq descre (cdr desc)))
11196 ((eq (car desc) :level)
11197 (setq descre (concat "^\\*\\{" (number-to-string
11198 (if org-odd-levels-only
11199 (1- (* 2 (cdr desc)))
11200 (cdr desc)))
11201 "\\}[ \t]")))
11202 ((eq (car desc) :maxlevel)
11203 (setq descre (concat "^\\*\\{1," (number-to-string
11204 (if org-odd-levels-only
11205 (1- (* 2 (cdr desc)))
11206 (cdr desc)))
11207 "\\}[ \t]")))
11208 (t (error "Bad refiling target description %s" desc)))
11209 (dolist (f files)
11210 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11212 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11213 (progn
11214 (when (bufferp f)
11215 (setq f (buffer-file-name (buffer-base-buffer f))))
11216 (setq f (and f (expand-file-name f)))
11217 (when (eq org-refile-use-outline-path 'file)
11218 (push (list (file-name-nondirectory f) f nil nil) tgs))
11219 (when (eq org-refile-use-outline-path 'buffer-name)
11220 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11221 (when (eq org-refile-use-outline-path 'full-file-path)
11222 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11223 (org-with-wide-buffer
11224 (goto-char (point-min))
11225 (setq org-outline-path-cache nil)
11226 (while (re-search-forward descre nil t)
11227 (beginning-of-line)
11228 (let ((case-fold-search nil))
11229 (looking-at org-complex-heading-regexp))
11230 (let ((begin (point))
11231 (heading (match-string-no-properties 4)))
11232 (unless (or (and
11233 org-refile-target-verify-function
11234 (not
11235 (funcall org-refile-target-verify-function)))
11236 (not heading))
11237 (let ((re (format org-complex-heading-regexp-format
11238 (regexp-quote heading)))
11239 (target
11240 (if (not org-refile-use-outline-path) heading
11241 (mapconcat
11242 #'identity
11243 (append
11244 (pcase org-refile-use-outline-path
11245 (`file (list (file-name-nondirectory
11246 (buffer-file-name
11247 (buffer-base-buffer)))))
11248 (`full-file-path
11249 (list (buffer-file-name
11250 (buffer-base-buffer))))
11251 (`buffer-name
11252 (list (buffer-name
11253 (buffer-base-buffer))))
11254 (_ nil))
11255 (mapcar (lambda (s) (replace-regexp-in-string
11256 "/" "\\/" s nil t))
11257 (org-get-outline-path t t)))
11258 "/"))))
11259 (push (list target f re (org-refile-marker (point)))
11260 tgs)))
11261 (when (= (point) begin)
11262 ;; Verification function has not moved point.
11263 (end-of-line)))))))
11264 (when org-refile-use-cache
11265 (org-refile-cache-put tgs (buffer-file-name) descre))
11266 (setq targets (append tgs targets))))))
11267 (message "Getting targets...done")
11268 (delete-dups (nreverse targets))))
11270 (defun org--get-outline-path-1 (&optional use-cache)
11271 "Return outline path to current headline.
11273 Outline path is a list of strings, in reverse order. When
11274 optional argument USE-CACHE is non-nil, make use of a cache. See
11275 `org-get-outline-path' for details.
11277 Assume buffer is widened and point is on a headline."
11278 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11279 (let ((p (point))
11280 (heading (let ((case-fold-search nil))
11281 (looking-at org-complex-heading-regexp)
11282 (if (not (match-end 4)) ""
11283 ;; Remove statistics cookies.
11284 (org-trim
11285 (org-link-display-format
11286 (replace-regexp-in-string
11287 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11288 (match-string-no-properties 4))))))))
11289 (if (org-up-heading-safe)
11290 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11291 (when use-cache
11292 (push (cons p path) org-outline-path-cache))
11293 path)
11294 ;; This is a new root node. Since we assume we are moving
11295 ;; forward, we can drop previous cache so as to limit number
11296 ;; of associations there.
11297 (let ((path (list heading)))
11298 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11299 path)))))
11301 (defun org-get-outline-path (&optional with-self use-cache)
11302 "Return the outline path to the current entry.
11304 An outline path is a list of ancestors for current headline, as
11305 a list of strings. Statistics cookies are removed and links are
11306 replaced with their description, if any, or their path otherwise.
11308 When optional argument WITH-SELF is non-nil, the path also
11309 includes the current headline.
11311 When optional argument USE-CACHE is non-nil, cache outline paths
11312 between calls to this function so as to avoid backtracking. This
11313 argument is useful when planning to find more than one outline
11314 path in the same document. In that case, there are two
11315 conditions to satisfy:
11316 - `org-outline-path-cache' is set to nil before starting the
11317 process;
11318 - outline paths are computed by increasing buffer positions."
11319 (org-with-wide-buffer
11320 (and (or (and with-self (org-back-to-heading t))
11321 (org-up-heading-safe))
11322 (reverse (org--get-outline-path-1 use-cache)))))
11324 (defun org-format-outline-path (path &optional width prefix separator)
11325 "Format the outline path PATH for display.
11326 WIDTH is the maximum number of characters that is available.
11327 PREFIX is a prefix to be included in the returned string,
11328 such as the file name.
11329 SEPARATOR is inserted between the different parts of the path,
11330 the default is \"/\"."
11331 (setq width (or width 79))
11332 (setq path (delq nil path))
11333 (unless (> width 0)
11334 (user-error "Argument `width' must be positive"))
11335 (setq separator (or separator "/"))
11336 (let* ((org-odd-levels-only nil)
11337 (fpath (concat
11338 prefix (and prefix path separator)
11339 (mapconcat
11340 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11341 (cl-loop for head in path
11342 for n from 0
11343 collect (org-add-props
11344 head nil 'face
11345 (nth (% n org-n-level-faces) org-level-faces)))
11346 separator))))
11347 (when (> (length fpath) width)
11348 (if (< width 7)
11349 ;; It's unlikely that `width' will be this small, but don't
11350 ;; waste characters by adding ".." if it is.
11351 (setq fpath (substring fpath 0 width))
11352 (setf (substring fpath (- width 2)) "..")))
11353 fpath))
11355 (defun org-display-outline-path (&optional file current separator just-return-string)
11356 "Display the current outline path in the echo area.
11358 If FILE is non-nil, prepend the output with the file name.
11359 If CURRENT is non-nil, append the current heading to the output.
11360 SEPARATOR is passed through to `org-format-outline-path'. It separates
11361 the different parts of the path and defaults to \"/\".
11362 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11363 (interactive "P")
11364 (let* (case-fold-search
11365 (bfn (buffer-file-name (buffer-base-buffer)))
11366 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11367 res)
11368 (when current (setq path (append path
11369 (save-excursion
11370 (org-back-to-heading t)
11371 (when (looking-at org-complex-heading-regexp)
11372 (list (match-string 4)))))))
11373 (setq res
11374 (org-format-outline-path
11375 path
11376 (1- (frame-width))
11377 (and file bfn (concat (file-name-nondirectory bfn) separator))
11378 separator))
11379 (if just-return-string
11380 (org-no-properties res)
11381 (org-unlogged-message "%s" res))))
11383 (defvar org-refile-history nil
11384 "History for refiling operations.")
11386 (defvar org-after-refile-insert-hook nil
11387 "Hook run after `org-refile' has inserted its stuff at the new location.
11388 Note that this is still *before* the stuff will be removed from
11389 the *old* location.")
11391 (defvar org-capture-last-stored-marker)
11392 (defvar org-refile-keep nil
11393 "Non-nil means `org-refile' will copy instead of refile.")
11395 (defun org-copy ()
11396 "Like `org-refile', but copy."
11397 (interactive)
11398 (let ((org-refile-keep t))
11399 (funcall 'org-refile nil nil nil "Copy")))
11401 (defun org-refile (&optional arg default-buffer rfloc msg)
11402 "Move the entry or entries at point to another heading.
11404 The list of target headings is compiled using the information in
11405 `org-refile-targets', which see.
11407 At the target location, the entry is filed as a subitem of the
11408 target heading. Depending on `org-reverse-note-order', the new
11409 subitem will either be the first or the last subitem.
11411 If there is an active region, all entries in that region will be
11412 refiled. However, the region must fulfill the requirement that
11413 the first heading sets the top-level of the moved text.
11415 With a `\\[universal-argument]' ARG, the command will only visit the target \
11416 location
11417 and not actually move anything.
11419 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11420 location where the last
11421 refiling operation has put the subtree.
11423 With a numeric prefix argument of `2', refile to the running clock.
11425 With a numeric prefix argument of `3', emulate `org-refile-keep'
11426 being set to t and copy to the target location, don't move it.
11427 Beware that keeping refiled entries may result in duplicated ID
11428 properties.
11430 RFLOC can be a refile location obtained in a different way.
11432 MSG is a string to replace \"Refile\" in the default prompt with
11433 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11435 See also `org-refile-use-outline-path'.
11437 If you are using target caching (see `org-refile-use-cache'), you
11438 have to clear the target cache in order to find new targets.
11439 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11440 prefix argument (`C-u C-u C-u C-c C-w')."
11441 (interactive "P")
11442 (if (member arg '(0 (64)))
11443 (org-refile-cache-clear)
11444 (let* ((actionmsg (cond (msg msg)
11445 ((equal arg 3) "Refile (and keep)")
11446 (t "Refile")))
11447 (regionp (org-region-active-p))
11448 (region-start (and regionp (region-beginning)))
11449 (region-end (and regionp (region-end)))
11450 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11451 pos it nbuf file level reversed)
11452 (setq last-command nil)
11453 (when regionp
11454 (goto-char region-start)
11455 (or (bolp) (goto-char (point-at-bol)))
11456 (setq region-start (point))
11457 (unless (or (org-kill-is-subtree-p
11458 (buffer-substring region-start region-end))
11459 (prog1 org-refile-active-region-within-subtree
11460 (let ((s (point-at-eol)))
11461 (org-toggle-heading)
11462 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11463 (user-error "The region is not a (sequence of) subtree(s)")))
11464 (if (equal arg '(16))
11465 (org-refile-goto-last-stored)
11466 (when (or
11467 (and (equal arg 2)
11468 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11469 (prog1
11470 (setq it (list (or org-clock-heading "running clock")
11471 (buffer-file-name
11472 (marker-buffer org-clock-hd-marker))
11474 (marker-position org-clock-hd-marker)))
11475 (setq arg nil)))
11476 (setq it
11477 (or rfloc
11478 (let (heading-text)
11479 (save-excursion
11480 (unless (and arg (listp arg))
11481 (org-back-to-heading t)
11482 (setq heading-text
11483 (replace-regexp-in-string
11484 org-bracket-link-regexp
11485 "\\3"
11486 (or (nth 4 (org-heading-components))
11487 ""))))
11488 (org-refile-get-location
11489 (cond ((and arg (listp arg)) "Goto")
11490 (regionp (concat actionmsg " region to"))
11491 (t (concat actionmsg " subtree \""
11492 heading-text "\" to")))
11493 default-buffer
11494 (and (not (equal '(4) arg))
11495 org-refile-allow-creating-parent-nodes)))))))
11496 (setq file (nth 1 it)
11497 pos (nth 3 it))
11498 (when (and (not arg)
11500 (equal (buffer-file-name) file)
11501 (if regionp
11502 (and (>= pos region-start)
11503 (<= pos region-end))
11504 (and (>= pos (point))
11505 (< pos (save-excursion
11506 (org-end-of-subtree t t))))))
11507 (error "Cannot refile to position inside the tree or region"))
11508 (setq nbuf (or (find-buffer-visiting file)
11509 (find-file-noselect file)))
11510 (if (and arg (not (equal arg 3)))
11511 (progn
11512 (pop-to-buffer-same-window nbuf)
11513 (goto-char (cond (pos)
11514 ((org-notes-order-reversed-p) (point-min))
11515 (t (point-max))))
11516 (org-show-context 'org-goto))
11517 (if regionp
11518 (progn
11519 (org-kill-new (buffer-substring region-start region-end))
11520 (org-save-markers-in-region region-start region-end))
11521 (org-copy-subtree 1 nil t))
11522 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11523 (find-file-noselect file)))
11524 (setq reversed (org-notes-order-reversed-p))
11525 (org-with-wide-buffer
11526 (if pos
11527 (progn
11528 (goto-char pos)
11529 (setq level (org-get-valid-level (funcall outline-level) 1))
11530 (goto-char
11531 (if reversed
11532 (or (outline-next-heading) (point-max))
11533 (or (save-excursion (org-get-next-sibling))
11534 (org-end-of-subtree t t)
11535 (point-max)))))
11536 (setq level 1)
11537 (if (not reversed)
11538 (goto-char (point-max))
11539 (goto-char (point-min))
11540 (or (outline-next-heading) (goto-char (point-max)))))
11541 (unless (bolp) (newline))
11542 (org-paste-subtree level nil nil t)
11543 (when org-log-refile
11544 (org-add-log-setup 'refile nil nil org-log-refile)
11545 (unless (eq org-log-refile 'note)
11546 (save-excursion (org-add-log-note))))
11547 (and org-auto-align-tags
11548 (let ((org-loop-over-headlines-in-active-region nil))
11549 (org-set-tags nil t)))
11550 (let ((bookmark-name (plist-get org-bookmark-names-plist
11551 :last-refile)))
11552 (when bookmark-name
11553 (with-demoted-errors
11554 (bookmark-set bookmark-name))))
11555 ;; If we are refiling for capture, make sure that the
11556 ;; last-capture pointers point here
11557 (when (bound-and-true-p org-capture-is-refiling)
11558 (let ((bookmark-name (plist-get org-bookmark-names-plist
11559 :last-capture-marker)))
11560 (when bookmark-name
11561 (with-demoted-errors
11562 (bookmark-set bookmark-name))))
11563 (move-marker org-capture-last-stored-marker (point)))
11564 (when (fboundp 'deactivate-mark) (deactivate-mark))
11565 (run-hooks 'org-after-refile-insert-hook)))
11566 (unless org-refile-keep
11567 (if regionp
11568 (delete-region (point) (+ (point) (- region-end region-start)))
11569 (org-preserve-local-variables
11570 (delete-region
11571 (and (org-back-to-heading t) (point))
11572 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11573 (when (featurep 'org-inlinetask)
11574 (org-inlinetask-remove-END-maybe))
11575 (setq org-markers-to-move nil)
11576 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11578 (defun org-refile-goto-last-stored ()
11579 "Go to the location where the last refile was stored."
11580 (interactive)
11581 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11582 (message "This is the location of the last refile"))
11584 (defun org-refile--get-location (refloc tbl)
11585 "When user refile to REFLOC, find the associated target in TBL.
11586 Also check `org-refile-target-table'."
11587 (car (delq
11589 (mapcar
11590 (lambda (r) (or (assoc r tbl)
11591 (assoc r org-refile-target-table)))
11592 (list (replace-regexp-in-string "/$" "" refloc)
11593 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11595 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11596 "Prompt the user for a refile location, using PROMPT.
11597 PROMPT should not be suffixed with a colon and a space, because
11598 this function appends the default value from
11599 `org-refile-history' automatically, if that is not empty."
11600 (let ((org-refile-targets org-refile-targets)
11601 (org-refile-use-outline-path org-refile-use-outline-path))
11602 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11603 (unless org-refile-target-table
11604 (user-error "No refile targets"))
11605 (let* ((cbuf (current-buffer))
11606 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11607 (cfunc (if (and org-refile-use-outline-path
11608 org-outline-path-complete-in-steps)
11609 #'org-olpath-completing-read
11610 #'completing-read))
11611 (extra (if org-refile-use-outline-path "/" ""))
11612 (cbnex (concat (buffer-name) extra))
11613 (filename (and cfn (expand-file-name cfn)))
11614 (tbl (mapcar
11615 (lambda (x)
11616 (if (and (not (member org-refile-use-outline-path
11617 '(file full-file-path)))
11618 (not (equal filename (nth 1 x))))
11619 (cons (concat (car x) extra " ("
11620 (file-name-nondirectory (nth 1 x)) ")")
11621 (cdr x))
11622 (cons (concat (car x) extra) (cdr x))))
11623 org-refile-target-table))
11624 (completion-ignore-case t)
11625 cdef
11626 (prompt (concat prompt
11627 (or (and (car org-refile-history)
11628 (concat " (default " (car org-refile-history) ")"))
11629 (and (assoc cbnex tbl) (setq cdef cbnex)
11630 (concat " (default " cbnex ")"))) ": "))
11631 pa answ parent-target child parent old-hist)
11632 (setq old-hist org-refile-history)
11633 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11634 nil 'org-refile-history (or cdef (car org-refile-history))))
11635 (if (setq pa (org-refile--get-location answ tbl))
11636 (progn
11637 (org-refile-check-position pa)
11638 (when (or (not org-refile-history)
11639 (not (eq old-hist org-refile-history))
11640 (not (equal (car pa) (car org-refile-history))))
11641 (setq org-refile-history
11642 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11643 org-refile-history
11644 (cdr org-refile-history))))
11645 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11646 (pop org-refile-history)))
11648 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11649 (progn
11650 (setq parent (match-string 1 answ)
11651 child (match-string 2 answ))
11652 (setq parent-target (org-refile--get-location parent tbl))
11653 (when (and parent-target
11654 (or (eq new-nodes t)
11655 (and (eq new-nodes 'confirm)
11656 (y-or-n-p (format "Create new node \"%s\"? "
11657 child)))))
11658 (org-refile-new-child parent-target child)))
11659 (user-error "Invalid target location")))))
11661 (declare-function org-string-nw-p "org-macs" (s))
11662 (defun org-refile-check-position (refile-pointer)
11663 "Check if the refile pointer matches the headline to which it points."
11664 (let* ((file (nth 1 refile-pointer))
11665 (re (nth 2 refile-pointer))
11666 (pos (nth 3 refile-pointer))
11667 buffer)
11668 (if (and (not (markerp pos)) (not file))
11669 (user-error "Please indicate a target file in the refile path")
11670 (when (org-string-nw-p re)
11671 (setq buffer (if (markerp pos)
11672 (marker-buffer pos)
11673 (or (find-buffer-visiting file)
11674 (find-file-noselect file))))
11675 (with-current-buffer buffer
11676 (org-with-wide-buffer
11677 (goto-char pos)
11678 (beginning-of-line 1)
11679 (unless (looking-at-p re)
11680 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11682 (defun org-refile-new-child (parent-target child)
11683 "Use refile target PARENT-TARGET to add new CHILD below it."
11684 (unless parent-target
11685 (error "Cannot find parent for new node"))
11686 (let ((file (nth 1 parent-target))
11687 (pos (nth 3 parent-target))
11688 level)
11689 (with-current-buffer (or (find-buffer-visiting file)
11690 (find-file-noselect file))
11691 (org-with-wide-buffer
11692 (if pos
11693 (goto-char pos)
11694 (goto-char (point-max))
11695 (unless (bolp) (newline)))
11696 (when (looking-at org-outline-regexp)
11697 (setq level (funcall outline-level))
11698 (org-end-of-subtree t t))
11699 (org-back-over-empty-lines)
11700 (insert "\n" (make-string
11701 (if pos (org-get-valid-level level 1) 1) ?*)
11702 " " child "\n")
11703 (beginning-of-line 0)
11704 (list (concat (car parent-target) "/" child) file "" (point))))))
11706 (defun org-olpath-completing-read (prompt collection &rest args)
11707 "Read an outline path like a file name."
11708 (let ((thetable collection))
11709 (apply #'completing-read
11710 prompt
11711 (lambda (string predicate &optional flag)
11712 (cond
11713 ((eq flag nil) (try-completion string thetable))
11714 ((eq flag t)
11715 (let ((l (length string)))
11716 (mapcar (lambda (x)
11717 (let ((r (substring x l))
11718 (f (if (string-match " ([^)]*)$" x)
11719 (match-string 0 x)
11720 "")))
11721 (if (string-match "/" r)
11722 (concat string (substring r 0 (match-end 0)) f)
11723 x)))
11724 (all-completions string thetable predicate))))
11725 ;; Exact match?
11726 ((eq flag 'lambda) (assoc string thetable))))
11727 args)))
11729 ;;;; Dynamic blocks
11731 (defun org-find-dblock (name)
11732 "Find the first dynamic block with name NAME in the buffer.
11733 If not found, stay at current position and return nil."
11734 (let ((case-fold-search t) pos)
11735 (save-excursion
11736 (goto-char (point-min))
11737 (setq pos (and (re-search-forward
11738 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11739 (match-beginning 0))))
11740 (when pos (goto-char pos))
11741 pos))
11743 (defun org-create-dblock (plist)
11744 "Create a dynamic block section, with parameters taken from PLIST.
11745 PLIST must contain a :name entry which is used as the name of the block."
11746 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11747 (end-of-line 1)
11748 (newline))
11749 (let ((col (current-column))
11750 (name (plist-get plist :name)))
11751 (insert "#+BEGIN: " name)
11752 (while plist
11753 (if (eq (car plist) :name)
11754 (setq plist (cddr plist))
11755 (insert " " (prin1-to-string (pop plist)))))
11756 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11757 (beginning-of-line -2)))
11759 (defun org-prepare-dblock ()
11760 "Prepare dynamic block for refresh.
11761 This empties the block, puts the cursor at the insert position and returns
11762 the property list including an extra property :name with the block name."
11763 (unless (looking-at org-dblock-start-re)
11764 (user-error "Not at a dynamic block"))
11765 (let* ((begdel (1+ (match-end 0)))
11766 (name (org-no-properties (match-string 1)))
11767 (params (append (list :name name)
11768 (read (concat "(" (match-string 3) ")")))))
11769 (save-excursion
11770 (beginning-of-line 1)
11771 (skip-chars-forward " \t")
11772 (setq params (plist-put params :indentation-column (current-column))))
11773 (unless (re-search-forward org-dblock-end-re nil t)
11774 (error "Dynamic block not terminated"))
11775 (setq params
11776 (append params
11777 (list :content (buffer-substring
11778 begdel (match-beginning 0)))))
11779 (delete-region begdel (match-beginning 0))
11780 (goto-char begdel)
11781 (open-line 1)
11782 params))
11784 (defun org-map-dblocks (&optional command)
11785 "Apply COMMAND to all dynamic blocks in the current buffer.
11786 If COMMAND is not given, use `org-update-dblock'."
11787 (let ((cmd (or command 'org-update-dblock)))
11788 (save-excursion
11789 (goto-char (point-min))
11790 (while (re-search-forward org-dblock-start-re nil t)
11791 (goto-char (match-beginning 0))
11792 (save-excursion
11793 (condition-case nil
11794 (funcall cmd)
11795 (error (message "Error during update of dynamic block"))))
11796 (unless (re-search-forward org-dblock-end-re nil t)
11797 (error "Dynamic block not terminated"))))))
11799 (defun org-dblock-update (&optional arg)
11800 "User command for updating dynamic blocks.
11801 Update the dynamic block at point. With prefix ARG, update all dynamic
11802 blocks in the buffer."
11803 (interactive "P")
11804 (if arg
11805 (org-update-all-dblocks)
11806 (or (looking-at org-dblock-start-re)
11807 (org-beginning-of-dblock))
11808 (org-update-dblock)))
11810 (defun org-update-dblock ()
11811 "Update the dynamic block at point.
11812 This means to empty the block, parse for parameters and then call
11813 the correct writing function."
11814 (interactive)
11815 (save-excursion
11816 (let* ((win (selected-window))
11817 (pos (point))
11818 (line (org-current-line))
11819 (params (org-prepare-dblock))
11820 (name (plist-get params :name))
11821 (indent (plist-get params :indentation-column))
11822 (cmd (intern (concat "org-dblock-write:" name))))
11823 (message "Updating dynamic block `%s' at line %d..." name line)
11824 (funcall cmd params)
11825 (message "Updating dynamic block `%s' at line %d...done" name line)
11826 (goto-char pos)
11827 (when (and indent (> indent 0))
11828 (setq indent (make-string indent ?\ ))
11829 (save-excursion
11830 (select-window win)
11831 (org-beginning-of-dblock)
11832 (forward-line 1)
11833 (while (not (looking-at org-dblock-end-re))
11834 (insert indent)
11835 (beginning-of-line 2))
11836 (when (looking-at org-dblock-end-re)
11837 (and (looking-at "[ \t]+")
11838 (replace-match ""))
11839 (insert indent)))))))
11841 (defun org-beginning-of-dblock ()
11842 "Find the beginning of the dynamic block at point.
11843 Error if there is no such block at point."
11844 (let ((pos (point))
11845 beg)
11846 (end-of-line 1)
11847 (if (and (re-search-backward org-dblock-start-re nil t)
11848 (setq beg (match-beginning 0))
11849 (re-search-forward org-dblock-end-re nil t)
11850 (> (match-end 0) pos))
11851 (goto-char beg)
11852 (goto-char pos)
11853 (error "Not in a dynamic block"))))
11855 (defun org-update-all-dblocks ()
11856 "Update all dynamic blocks in the buffer.
11857 This function can be used in a hook."
11858 (interactive)
11859 (when (derived-mode-p 'org-mode)
11860 (org-map-dblocks 'org-update-dblock)))
11863 ;;;; Completion
11865 (declare-function org-export-backend-options "ox" (cl-x) t)
11866 (defun org-get-export-keywords ()
11867 "Return a list of all currently understood export keywords.
11868 Export keywords include options, block names, attributes and
11869 keywords relative to each registered export back-end."
11870 (let (keywords)
11871 (dolist (backend
11872 (bound-and-true-p org-export-registered-backends)
11873 (delq nil keywords))
11874 ;; Back-end name (for keywords, like #+LATEX:)
11875 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11876 (dolist (option-entry (org-export-backend-options backend))
11877 ;; Back-end options.
11878 (push (nth 1 option-entry) keywords)))))
11880 (defconst org-options-keywords
11881 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11882 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11883 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11884 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11885 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11887 (defcustom org-structure-template-alist
11888 '((?a . "export ascii")
11889 (?c . "center")
11890 (?C . "comment")
11891 (?e . "example")
11892 (?E . "export")
11893 (?h . "export html")
11894 (?l . "export latex")
11895 (?q . "quote")
11896 (?s . "src")
11897 (?v . "verse"))
11898 "Structure completion elements.
11899 This is an alist of characters and values. When
11900 `org-insert-structure-template' is called, an additional key is
11901 read. The key is first looked up in this alist, and the
11902 corresponding structure is inserted, with \"#+BEGIN_\" and
11903 \"#+END_\" added automatically."
11904 :group 'org-edit-structure
11905 :type '(repeat
11906 (cons (character :tag "Key")
11907 (string :tag "Template")))
11908 :package-version '(Org . "9.2"))
11910 (defun org-insert-structure-template (type)
11911 "Insert a block structure of the type #+begin_foo/#+end_foo.
11912 First read a character, which can be one of the keys in
11913 `org-structure-template-alist'. When it is <TAB>, prompt the
11914 user for a string to use. With an active region, wrap the region
11915 in the block. Otherwise, insert an empty block."
11916 (interactive
11917 (list
11918 (let* ((key (read-key "Key: "))
11919 (struct-string
11920 (or (cdr (assq key org-structure-template-alist))
11921 (and (= key ?\t)
11922 (read-string "Structure type: "))
11923 (user-error "`%c' has no structure definition" key))))
11924 struct-string)))
11925 (let* ((region? (use-region-p))
11926 (s (if region? (region-beginning) (point)))
11927 (e (copy-marker (if region? (region-end) (point)) t))
11928 column)
11929 (when (string-match-p
11930 (concat "\\`" (regexp-opt '("example" "export" "src")))
11931 type)
11932 (org-escape-code-in-region s e))
11933 (goto-char s)
11934 (setq column (current-indentation))
11935 (beginning-of-line)
11936 (indent-to column)
11937 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11938 (goto-char e)
11939 (if (bolp)
11940 (progn
11941 (skip-chars-backward " \n\t")
11942 (forward-line))
11943 (end-of-line)
11944 (insert "\n"))
11945 (indent-to column)
11946 (insert (format "#+end_%s\n"
11947 (car (split-string type))))
11948 (when (or (not region?)
11949 (string-match-p "src\\|\\`export\\'" type))
11950 (goto-char s)
11951 (end-of-line))
11952 (set-marker e nil)))
11954 ;;;; TODO, DEADLINE, Comments
11956 (defun org-toggle-comment ()
11957 "Change the COMMENT state of an entry."
11958 (interactive)
11959 (save-excursion
11960 (org-back-to-heading)
11961 (let ((case-fold-search nil))
11962 (looking-at org-complex-heading-regexp))
11963 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11964 (skip-chars-forward " \t")
11965 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11966 (if (org-in-commented-heading-p t)
11967 (delete-region (point)
11968 (progn (search-forward " " (line-end-position) 'move)
11969 (skip-chars-forward " \t")
11970 (point)))
11971 (insert org-comment-string)
11972 (unless (eolp) (insert " ")))))
11974 (defvar org-last-todo-state-is-todo nil
11975 "This is non-nil when the last TODO state change led to a TODO state.
11976 If the last change removed the TODO tag or switched to DONE, then
11977 this is nil.")
11979 (defvar org-setting-tags nil) ; dynamically skipped
11981 (defvar org-todo-setup-filter-hook nil
11982 "Hook for functions that pre-filter todo specs.
11983 Each function takes a todo spec and returns either nil or the spec
11984 transformed into canonical form." )
11986 (defvar org-todo-get-default-hook nil
11987 "Hook for functions that get a default item for todo.
11988 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11989 nil or a string to be used for the todo mark." )
11991 (defvar org-agenda-headline-snapshot-before-repeat)
11993 (defun org-current-effective-time ()
11994 "Return current time adjusted for `org-extend-today-until' variable."
11995 (let* ((ct (org-current-time))
11996 (dct (decode-time ct))
11997 (ct1
11998 (cond
11999 (org-use-last-clock-out-time-as-effective-time
12000 (or (org-clock-get-last-clock-out-time) ct))
12001 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12002 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12003 (t ct))))
12004 ct1))
12006 (defun org-todo-yesterday (&optional arg)
12007 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12008 (interactive "P")
12009 (if (eq major-mode 'org-agenda-mode)
12010 (apply 'org-agenda-todo-yesterday arg)
12011 (let* ((org-use-effective-time t)
12012 (hour (nth 2 (decode-time (org-current-time))))
12013 (org-extend-today-until (1+ hour)))
12014 (org-todo arg))))
12016 (defvar org-block-entry-blocking ""
12017 "First entry preventing the TODO state change.")
12019 (defun org-cancel-repeater ()
12020 "Cancel a repeater by setting its numeric value to zero."
12021 (interactive)
12022 (save-excursion
12023 (org-back-to-heading t)
12024 (let ((bound1 (point))
12025 (bound0 (save-excursion (outline-next-heading) (point))))
12026 (when (and (re-search-forward
12027 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12028 org-deadline-time-regexp "\\)\\|\\("
12029 org-ts-regexp "\\)")
12030 bound0 t)
12031 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12032 bound1 t))
12033 (replace-match "0" t nil nil 1)))))
12035 (defvar org-state)
12036 (defvar org-blocked-by-checkboxes)
12037 (defun org-todo (&optional arg)
12038 "Change the TODO state of an item.
12040 The state of an item is given by a keyword at the start of the heading,
12041 like
12042 *** TODO Write paper
12043 *** DONE Call mom
12045 The different keywords are specified in the variable `org-todo-keywords'.
12046 By default the available states are \"TODO\" and \"DONE\". So, for this
12047 example: when the item starts with TODO, it is changed to DONE.
12048 When it starts with DONE, the DONE is removed. And when neither TODO nor
12049 DONE are present, add TODO at the beginning of the heading.
12051 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12052 state.
12053 With numeric prefix ARG, switch to that state.
12054 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12055 next set of TODO \
12056 keywords (nextset).
12057 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12058 prefix, circumvent any state blocking.
12059 With a numeric prefix arg of 0, inhibit note taking for the change.
12060 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12062 When called through ELisp, arg is also interpreted in the following way:
12063 `none' -> empty state
12064 \"\" -> switch to empty state
12065 `done' -> switch to DONE
12066 `nextset' -> switch to the next set of keywords
12067 `previousset' -> switch to the previous set of keywords
12068 \"WAITING\" -> switch to the specified keyword, but only if it
12069 really is a member of `org-todo-keywords'."
12070 (interactive "P")
12071 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12072 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12073 'region-start-level 'region))
12074 org-loop-over-headlines-in-active-region)
12075 (org-map-entries
12076 `(org-todo ,arg)
12077 org-loop-over-headlines-in-active-region
12078 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12079 (when (equal arg '(16)) (setq arg 'nextset))
12080 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12081 (let ((org-blocker-hook org-blocker-hook)
12082 commentp
12083 case-fold-search)
12084 (when (equal arg '(64))
12085 (setq arg nil org-blocker-hook nil))
12086 (when (and org-blocker-hook
12087 (or org-inhibit-blocking
12088 (org-entry-get nil "NOBLOCKING")))
12089 (setq org-blocker-hook nil))
12090 (save-excursion
12091 (catch 'exit
12092 (org-back-to-heading t)
12093 (when (org-in-commented-heading-p t)
12094 (org-toggle-comment)
12095 (setq commentp t))
12096 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12097 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12098 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12099 (let* ((match-data (match-data))
12100 (startpos (copy-marker (line-beginning-position)))
12101 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12102 (org-log-done org-log-done)
12103 (org-log-repeat org-log-repeat)
12104 (org-todo-log-states org-todo-log-states)
12105 (org-inhibit-logging
12106 (if (equal arg 0)
12107 (progn (setq arg nil) 'note) org-inhibit-logging))
12108 (this (match-string 1))
12109 (hl-pos (match-beginning 0))
12110 (head (org-get-todo-sequence-head this))
12111 (ass (assoc head org-todo-kwd-alist))
12112 (interpret (nth 1 ass))
12113 (done-word (nth 3 ass))
12114 (final-done-word (nth 4 ass))
12115 (org-last-state (or this ""))
12116 (completion-ignore-case t)
12117 (member (member this org-todo-keywords-1))
12118 (tail (cdr member))
12119 (org-state (cond
12120 ((and org-todo-key-trigger
12121 (or (and (equal arg '(4))
12122 (eq org-use-fast-todo-selection 'prefix))
12123 (and (not arg) org-use-fast-todo-selection
12124 (not (eq org-use-fast-todo-selection
12125 'prefix)))))
12126 ;; Use fast selection.
12127 (org-fast-todo-selection))
12128 ((and (equal arg '(4))
12129 (or (not org-use-fast-todo-selection)
12130 (not org-todo-key-trigger)))
12131 ;; Read a state with completion.
12132 (completing-read
12133 "State: " (mapcar #'list org-todo-keywords-1)
12134 nil t))
12135 ((eq arg 'right)
12136 (if this
12137 (if tail (car tail) nil)
12138 (car org-todo-keywords-1)))
12139 ((eq arg 'left)
12140 (unless (equal member org-todo-keywords-1)
12141 (if this
12142 (nth (- (length org-todo-keywords-1)
12143 (length tail) 2)
12144 org-todo-keywords-1)
12145 (org-last org-todo-keywords-1))))
12146 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12147 (setq arg nil))) ;hack to fall back to cycling
12148 (arg
12149 ;; User or caller requests a specific state.
12150 (cond
12151 ((equal arg "") nil)
12152 ((eq arg 'none) nil)
12153 ((eq arg 'done) (or done-word (car org-done-keywords)))
12154 ((eq arg 'nextset)
12155 (or (car (cdr (member head org-todo-heads)))
12156 (car org-todo-heads)))
12157 ((eq arg 'previousset)
12158 (let ((org-todo-heads (reverse org-todo-heads)))
12159 (or (car (cdr (member head org-todo-heads)))
12160 (car org-todo-heads))))
12161 ((car (member arg org-todo-keywords-1)))
12162 ((stringp arg)
12163 (user-error "State `%s' not valid in this file" arg))
12164 ((nth (1- (prefix-numeric-value arg))
12165 org-todo-keywords-1))))
12166 ((null member) (or head (car org-todo-keywords-1)))
12167 ((equal this final-done-word) nil) ;-> make empty
12168 ((null tail) nil) ;-> first entry
12169 ((memq interpret '(type priority))
12170 (if (eq this-command last-command)
12171 (car tail)
12172 (if (> (length tail) 0)
12173 (or done-word (car org-done-keywords))
12174 nil)))
12176 (car tail))))
12177 (org-state (or
12178 (run-hook-with-args-until-success
12179 'org-todo-get-default-hook org-state org-last-state)
12180 org-state))
12181 (next (if org-state (concat " " org-state " ") " "))
12182 (change-plist (list :type 'todo-state-change :from this :to org-state
12183 :position startpos))
12184 dolog now-done-p)
12185 (when org-blocker-hook
12186 (let (org-blocked-by-checkboxes block-reason)
12187 (setq org-last-todo-state-is-todo
12188 (not (member this org-done-keywords)))
12189 (unless (save-excursion
12190 (save-match-data
12191 (org-with-wide-buffer
12192 (run-hook-with-args-until-failure
12193 'org-blocker-hook change-plist))))
12194 (setq block-reason (if org-blocked-by-checkboxes
12195 "contained checkboxes"
12196 (format "\"%s\"" org-block-entry-blocking)))
12197 (if (called-interactively-p 'interactive)
12198 (user-error "TODO state change from %s to %s blocked (by %s)"
12199 this org-state block-reason)
12200 ;; Fail silently.
12201 (message "TODO state change from %s to %s blocked (by %s)"
12202 this org-state block-reason)
12203 (throw 'exit nil)))))
12204 (store-match-data match-data)
12205 (replace-match next t t)
12206 (cond ((equal this org-state)
12207 (message "TODO state was already %s" (org-trim next)))
12208 ((not (pos-visible-in-window-p hl-pos))
12209 (message "TODO state changed to %s" (org-trim next))))
12210 (unless head
12211 (setq head (org-get-todo-sequence-head org-state)
12212 ass (assoc head org-todo-kwd-alist)
12213 interpret (nth 1 ass)
12214 done-word (nth 3 ass)
12215 final-done-word (nth 4 ass)))
12216 (when (memq arg '(nextset previousset))
12217 (message "Keyword-Set %d/%d: %s"
12218 (- (length org-todo-sets) -1
12219 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12220 (length org-todo-sets)
12221 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12222 (setq org-last-todo-state-is-todo
12223 (not (member org-state org-done-keywords)))
12224 (setq now-done-p (and (member org-state org-done-keywords)
12225 (not (member this org-done-keywords))))
12226 (and logging (org-local-logging logging))
12227 (when (and (or org-todo-log-states org-log-done)
12228 (not (eq org-inhibit-logging t))
12229 (not (memq arg '(nextset previousset))))
12230 ;; We need to look at recording a time and note.
12231 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12232 (nth 2 (assoc this org-todo-log-states))))
12233 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12234 (setq dolog 'time))
12235 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12236 (and org-state
12237 (member org-state org-not-done-keywords)
12238 (not (member this org-not-done-keywords))))
12239 ;; This is now a todo state and was not one before
12240 ;; If there was a CLOSED time stamp, get rid of it.
12241 (org-add-planning-info nil nil 'closed))
12242 (when (and now-done-p org-log-done)
12243 ;; It is now done, and it was not done before.
12244 (org-add-planning-info 'closed (org-current-effective-time))
12245 (when (and (not dolog) (eq 'note org-log-done))
12246 (org-add-log-setup 'done org-state this 'note)))
12247 (when (and org-state dolog)
12248 ;; This is a non-nil state, and we need to log it.
12249 (org-add-log-setup 'state org-state this dolog)))
12250 ;; Fixup tag positioning.
12251 (org-todo-trigger-tag-changes org-state)
12252 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12253 (when org-provide-todo-statistics
12254 (org-update-parent-todo-statistics))
12255 (run-hooks 'org-after-todo-state-change-hook)
12256 (when (and arg (not (member org-state org-done-keywords)))
12257 (setq head (org-get-todo-sequence-head org-state)))
12258 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12259 ;; Do we need to trigger a repeat?
12260 (when now-done-p
12261 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12262 ;; This is for the agenda, take a snapshot of the headline.
12263 (save-match-data
12264 (setq org-agenda-headline-snapshot-before-repeat
12265 (org-get-heading))))
12266 (org-auto-repeat-maybe org-state))
12267 ;; Fixup cursor location if close to the keyword.
12268 (when (and (outline-on-heading-p)
12269 (not (bolp))
12270 (save-excursion (beginning-of-line 1)
12271 (looking-at org-todo-line-regexp))
12272 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12273 (goto-char (or (match-end 2) (match-end 1)))
12274 (and (looking-at " ") (just-one-space)))
12275 (when org-trigger-hook
12276 (save-excursion
12277 (run-hook-with-args 'org-trigger-hook change-plist)))
12278 (when commentp (org-toggle-comment))))))))
12280 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12281 "Block turning an entry into a TODO, using the hierarchy.
12282 This checks whether the current task should be blocked from state
12283 changes. Such blocking occurs when:
12285 1. The task has children which are not all in a completed state.
12287 2. A task has a parent with the property :ORDERED:, and there
12288 are siblings prior to the current task with incomplete
12289 status.
12291 3. The parent of the task is blocked because it has siblings that should
12292 be done first, or is child of a block grandparent TODO entry."
12294 (if (not org-enforce-todo-dependencies)
12295 t ; if locally turned off don't block
12296 (catch 'dont-block
12297 ;; If this is not a todo state change, or if this entry is already DONE,
12298 ;; do not block
12299 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12300 (member (plist-get change-plist :from)
12301 (cons 'done org-done-keywords))
12302 (member (plist-get change-plist :to)
12303 (cons 'todo org-not-done-keywords))
12304 (not (plist-get change-plist :to)))
12305 (throw 'dont-block t))
12306 ;; If this task has children, and any are undone, it's blocked
12307 (save-excursion
12308 (org-back-to-heading t)
12309 (let ((this-level (funcall outline-level)))
12310 (outline-next-heading)
12311 (let ((child-level (funcall outline-level)))
12312 (while (and (not (eobp))
12313 (> child-level this-level))
12314 ;; this todo has children, check whether they are all
12315 ;; completed
12316 (when (and (not (org-entry-is-done-p))
12317 (org-entry-is-todo-p))
12318 (setq org-block-entry-blocking (org-get-heading))
12319 (throw 'dont-block nil))
12320 (outline-next-heading)
12321 (setq child-level (funcall outline-level))))))
12322 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12323 ;; any previous siblings are undone, it's blocked
12324 (save-excursion
12325 (org-back-to-heading t)
12326 (let* ((pos (point))
12327 (parent-pos (and (org-up-heading-safe) (point)))
12328 (case-fold-search nil))
12329 (unless parent-pos (throw 'dont-block t)) ; no parent
12330 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12331 (forward-line 1)
12332 (re-search-forward org-not-done-heading-regexp pos t))
12333 (setq org-block-entry-blocking (match-string 0))
12334 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12335 ;; Search further up the hierarchy, to see if an ancestor is blocked
12336 (while t
12337 (goto-char parent-pos)
12338 (unless (looking-at org-not-done-heading-regexp)
12339 (throw 'dont-block t)) ; do not block, parent is not a TODO
12340 (setq pos (point))
12341 (setq parent-pos (and (org-up-heading-safe) (point)))
12342 (unless parent-pos (throw 'dont-block t)) ; no parent
12343 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12344 (forward-line 1)
12345 (re-search-forward org-not-done-heading-regexp pos t)
12346 (setq org-block-entry-blocking (org-get-heading)))
12347 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12349 (defcustom org-track-ordered-property-with-tag nil
12350 "Should the ORDERED property also be shown as a tag?
12351 The ORDERED property decides if an entry should require subtasks to be
12352 completed in sequence. Since a property is not very visible, setting
12353 this option means that toggling the ORDERED property with the command
12354 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12355 not relevant for the behavior, but it makes things more visible.
12357 Note that toggling the tag with tags commands will not change the property
12358 and therefore not influence behavior!
12360 This can be t, meaning the tag ORDERED should be used, It can also be a
12361 string to select a different tag for this task."
12362 :group 'org-todo
12363 :type '(choice
12364 (const :tag "No tracking" nil)
12365 (const :tag "Track with ORDERED tag" t)
12366 (string :tag "Use other tag")))
12368 (defun org-toggle-ordered-property ()
12369 "Toggle the ORDERED property of the current entry.
12370 For better visibility, you can track the value of this property with a tag.
12371 See variable `org-track-ordered-property-with-tag'."
12372 (interactive)
12373 (let* ((t1 org-track-ordered-property-with-tag)
12374 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12375 (save-excursion
12376 (org-back-to-heading)
12377 (if (org-entry-get nil "ORDERED")
12378 (progn
12379 (org-delete-property "ORDERED")
12380 (and tag (org-toggle-tag tag 'off))
12381 (message "Subtasks can be completed in arbitrary order"))
12382 (org-entry-put nil "ORDERED" "t")
12383 (and tag (org-toggle-tag tag 'on))
12384 (message "Subtasks must be completed in sequence")))))
12386 (defun org-block-todo-from-checkboxes (change-plist)
12387 "Block turning an entry into a TODO, using checkboxes.
12388 This checks whether the current task should be blocked from state
12389 changes because there are unchecked boxes in this entry."
12390 (if (not org-enforce-todo-checkbox-dependencies)
12391 t ; if locally turned off don't block
12392 (catch 'dont-block
12393 ;; If this is not a todo state change, or if this entry is already DONE,
12394 ;; do not block
12395 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12396 (member (plist-get change-plist :from)
12397 (cons 'done org-done-keywords))
12398 (member (plist-get change-plist :to)
12399 (cons 'todo org-not-done-keywords))
12400 (not (plist-get change-plist :to)))
12401 (throw 'dont-block t))
12402 ;; If this task has checkboxes that are not checked, it's blocked
12403 (save-excursion
12404 (org-back-to-heading t)
12405 (let ((beg (point)) end)
12406 (outline-next-heading)
12407 (setq end (point))
12408 (goto-char beg)
12409 (when (org-list-search-forward
12410 (concat (org-item-beginning-re)
12411 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12412 "\\[[- ]\\]")
12413 end t)
12414 (when (boundp 'org-blocked-by-checkboxes)
12415 (setq org-blocked-by-checkboxes t))
12416 (throw 'dont-block nil))))
12417 t))) ; do not block
12419 (defun org-entry-blocked-p ()
12420 "Non-nil if entry at point is blocked."
12421 (and (not (org-entry-get nil "NOBLOCKING"))
12422 (member (org-entry-get nil "TODO") org-not-done-keywords)
12423 (not (run-hook-with-args-until-failure
12424 'org-blocker-hook
12425 (list :type 'todo-state-change
12426 :position (point)
12427 :from 'todo
12428 :to 'done)))))
12430 (defun org-update-statistics-cookies (all)
12431 "Update the statistics cookie, either from TODO or from checkboxes.
12432 This should be called with the cursor in a line with a statistics
12433 cookie. When called with a \\[universal-argument] prefix, update
12434 all statistics cookies in the buffer."
12435 (interactive "P")
12436 (if all
12437 (progn
12438 (org-update-checkbox-count 'all)
12439 (org-map-entries 'org-update-parent-todo-statistics))
12440 (if (not (org-at-heading-p))
12441 (org-update-checkbox-count)
12442 (let ((pos (point-marker))
12443 end l1 l2)
12444 (ignore-errors (org-back-to-heading t))
12445 (if (not (org-at-heading-p))
12446 (org-update-checkbox-count)
12447 (setq l1 (org-outline-level))
12448 (setq end (save-excursion
12449 (outline-next-heading)
12450 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12451 (point)))
12452 (if (and (save-excursion
12453 (re-search-forward
12454 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12455 (not (save-excursion (re-search-forward
12456 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12457 (org-update-checkbox-count)
12458 (if (and l2 (> l2 l1))
12459 (progn
12460 (goto-char end)
12461 (org-update-parent-todo-statistics))
12462 (goto-char pos)
12463 (beginning-of-line 1)
12464 (while (re-search-forward
12465 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12466 (point-at-eol) t)
12467 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12468 (goto-char pos)
12469 (move-marker pos nil)))))
12471 (defvar org-entry-property-inherited-from) ;; defined below
12472 (defun org-update-parent-todo-statistics ()
12473 "Update any statistics cookie in the parent of the current headline.
12474 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12475 the entire subtree and this will travel up the hierarchy and update
12476 statistics everywhere."
12477 (let* ((prop (save-excursion (org-up-heading-safe)
12478 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12479 (recursive (or (not org-hierarchical-todo-statistics)
12480 (and prop (string-match "\\<recursive\\>" prop))))
12481 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12483 (first t)
12484 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12485 level ltoggle l1 new ndel
12486 (cnt-all 0) (cnt-done 0) is-percent kwd
12487 checkbox-beg cookie-present)
12488 (catch 'exit
12489 (save-excursion
12490 (beginning-of-line 1)
12491 (setq ltoggle (funcall outline-level))
12492 ;; Three situations are to consider:
12494 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12495 ;; to the top-level ancestor on the headline;
12497 ;; 2. If parent has "recursive" property, repeat up to the
12498 ;; headline setting that property, taking inheritance into
12499 ;; account;
12501 ;; 3. Else, move up to direct parent and proceed only once.
12502 (while (and (setq level (org-up-heading-safe))
12503 (or recursive first)
12504 (>= (point) lim))
12505 (setq first nil cookie-present nil)
12506 (unless (and level
12507 (not (string-match
12508 "\\<checkbox\\>"
12509 (downcase (or (org-entry-get nil "COOKIE_DATA")
12510 "")))))
12511 (throw 'exit nil))
12512 (while (re-search-forward box-re (point-at-eol) t)
12513 (setq cnt-all 0 cnt-done 0 cookie-present t)
12514 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12515 (save-match-data
12516 (unless (outline-next-heading) (throw 'exit nil))
12517 (while (and (looking-at org-complex-heading-regexp)
12518 (> (setq l1 (length (match-string 1))) level))
12519 (setq kwd (and (or recursive (= l1 ltoggle))
12520 (match-string 2)))
12521 (if (or (eq org-provide-todo-statistics 'all-headlines)
12522 (and (eq org-provide-todo-statistics t)
12523 (or (member kwd org-done-keywords)))
12524 (and (listp org-provide-todo-statistics)
12525 (stringp (car org-provide-todo-statistics))
12526 (or (member kwd org-provide-todo-statistics)
12527 (member kwd org-done-keywords)))
12528 (and (listp org-provide-todo-statistics)
12529 (listp (car org-provide-todo-statistics))
12530 (or (member kwd (car org-provide-todo-statistics))
12531 (and (member kwd org-done-keywords)
12532 (member kwd (cadr org-provide-todo-statistics))))))
12533 (setq cnt-all (1+ cnt-all))
12534 (and (eq org-provide-todo-statistics t)
12536 (setq cnt-all (1+ cnt-all))))
12537 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12538 (member kwd org-done-keywords))
12539 (and (listp org-provide-todo-statistics)
12540 (listp (car org-provide-todo-statistics))
12541 (member kwd org-done-keywords)
12542 (member kwd (cadr org-provide-todo-statistics)))
12543 (and (listp org-provide-todo-statistics)
12544 (stringp (car org-provide-todo-statistics))
12545 (member kwd org-done-keywords)))
12546 (setq cnt-done (1+ cnt-done)))
12547 (outline-next-heading)))
12548 (setq new
12549 (if is-percent
12550 (format "[%d%%]" (floor (* 100.0 cnt-done)
12551 (max 1 cnt-all)))
12552 (format "[%d/%d]" cnt-done cnt-all))
12553 ndel (- (match-end 0) checkbox-beg))
12554 (goto-char checkbox-beg)
12555 (insert new)
12556 (delete-region (point) (+ (point) ndel))
12557 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12558 (when cookie-present
12559 (run-hook-with-args 'org-after-todo-statistics-hook
12560 cnt-done (- cnt-all cnt-done))))))
12561 (run-hooks 'org-todo-statistics-hook)))
12563 (defvar org-after-todo-statistics-hook nil
12564 "Hook that is called after a TODO statistics cookie has been updated.
12565 Each function is called with two arguments: the number of not-done entries
12566 and the number of done entries.
12568 For example, the following function, when added to this hook, will switch
12569 an entry to DONE when all children are done, and back to TODO when new
12570 entries are set to a TODO status. Note that this hook is only called
12571 when there is a statistics cookie in the headline!
12573 (defun org-summary-todo (n-done n-not-done)
12574 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12575 (let (org-log-done org-log-states) ; turn off logging
12576 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12579 (defvar org-todo-statistics-hook nil
12580 "Hook that is run whenever Org thinks TODO statistics should be updated.
12581 This hook runs even if there is no statistics cookie present, in which case
12582 `org-after-todo-statistics-hook' would not run.")
12584 (defun org-todo-trigger-tag-changes (state)
12585 "Apply the changes defined in `org-todo-state-tags-triggers'."
12586 (let ((l org-todo-state-tags-triggers)
12587 changes)
12588 (when (or (not state) (equal state ""))
12589 (setq changes (append changes (cdr (assoc "" l)))))
12590 (when (and (stringp state) (> (length state) 0))
12591 (setq changes (append changes (cdr (assoc state l)))))
12592 (when (member state org-not-done-keywords)
12593 (setq changes (append changes (cdr (assq 'todo l)))))
12594 (when (member state org-done-keywords)
12595 (setq changes (append changes (cdr (assq 'done l)))))
12596 (dolist (c changes)
12597 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12599 (defun org-local-logging (value)
12600 "Get logging settings from a property VALUE."
12601 ;; Directly set the variables, they are already local.
12602 (setq org-log-done nil
12603 org-log-repeat nil
12604 org-todo-log-states nil)
12605 (dolist (w (split-string value))
12606 (let (a)
12607 (cond
12608 ((setq a (assoc w org-startup-options))
12609 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12610 (set (nth 1 a) (nth 2 a))))
12611 ((setq a (org-extract-log-state-settings w))
12612 (and (member (car a) org-todo-keywords-1)
12613 (push a org-todo-log-states)))))))
12615 (defun org-get-todo-sequence-head (kwd)
12616 "Return the head of the TODO sequence to which KWD belongs.
12617 If KWD is not set, check if there is a text property remembering the
12618 right sequence."
12619 (let (p)
12620 (cond
12621 ((not kwd)
12622 (or (get-text-property (point-at-bol) 'org-todo-head)
12623 (progn
12624 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12625 nil (point-at-eol)))
12626 (get-text-property p 'org-todo-head))))
12627 ((not (member kwd org-todo-keywords-1))
12628 (car org-todo-keywords-1))
12629 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12631 (defun org-fast-todo-selection ()
12632 "Fast TODO keyword selection with single keys.
12633 Returns the new TODO keyword, or nil if no state change should occur."
12634 (let* ((fulltable org-todo-key-alist)
12635 (done-keywords org-done-keywords) ;; needed for the faces.
12636 (maxlen (apply 'max (mapcar
12637 (lambda (x)
12638 (if (stringp (car x)) (string-width (car x)) 0))
12639 fulltable)))
12640 (expert nil)
12641 (fwidth (+ maxlen 3 1 3))
12642 (ncol (/ (- (window-width) 4) fwidth))
12643 tg cnt e c tbl
12644 groups ingroup)
12645 (save-excursion
12646 (save-window-excursion
12647 (if expert
12648 (set-buffer (get-buffer-create " *Org todo*"))
12649 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12650 (erase-buffer)
12651 (setq-local org-done-keywords done-keywords)
12652 (setq tbl fulltable cnt 0)
12653 (while (setq e (pop tbl))
12654 (cond
12655 ((equal e '(:startgroup))
12656 (push '() groups) (setq ingroup t)
12657 (unless (= cnt 0)
12658 (setq cnt 0)
12659 (insert "\n"))
12660 (insert "{ "))
12661 ((equal e '(:endgroup))
12662 (setq ingroup nil cnt 0)
12663 (insert "}\n"))
12664 ((equal e '(:newline))
12665 (unless (= cnt 0)
12666 (setq cnt 0)
12667 (insert "\n")
12668 (setq e (car tbl))
12669 (while (equal (car tbl) '(:newline))
12670 (insert "\n")
12671 (setq tbl (cdr tbl)))))
12673 (setq tg (car e) c (cdr e))
12674 (when ingroup (push tg (car groups)))
12675 (setq tg (org-add-props tg nil 'face
12676 (org-get-todo-face tg)))
12677 (when (and (= cnt 0) (not ingroup)) (insert " "))
12678 (insert "[" c "] " tg (make-string
12679 (- fwidth 4 (length tg)) ?\ ))
12680 (when (= (setq cnt (1+ cnt)) ncol)
12681 (insert "\n")
12682 (when ingroup (insert " "))
12683 (setq cnt 0)))))
12684 (insert "\n")
12685 (goto-char (point-min))
12686 (unless expert (org-fit-window-to-buffer))
12687 (message "[a-z..]:Set [SPC]:clear")
12688 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12689 (cond
12690 ((or (= c ?\C-g)
12691 (and (= c ?q) (not (rassoc c fulltable))))
12692 (setq quit-flag t))
12693 ((= c ?\ ) nil)
12694 ((setq e (rassoc c fulltable) tg (car e))
12696 (t (setq quit-flag t)))))))
12698 (defun org-entry-is-todo-p ()
12699 (member (org-get-todo-state) org-not-done-keywords))
12701 (defun org-entry-is-done-p ()
12702 (member (org-get-todo-state) org-done-keywords))
12704 (defun org-get-todo-state ()
12705 "Return the TODO keyword of the current subtree."
12706 (save-excursion
12707 (org-back-to-heading t)
12708 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12709 (match-end 2)
12710 (match-string 2))))
12712 (defun org-at-date-range-p (&optional inactive-ok)
12713 "Non-nil if point is inside a date range.
12715 When optional argument INACTIVE-OK is non-nil, also consider
12716 inactive time ranges.
12718 When this function returns a non-nil value, match data is set
12719 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12720 on INACTIVE-OK."
12721 (interactive)
12722 (save-excursion
12723 (catch 'exit
12724 (let ((pos (point)))
12725 (skip-chars-backward "^[<\r\n")
12726 (skip-chars-backward "<[")
12727 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12728 (>= (match-end 0) pos)
12729 (throw 'exit t))
12730 (skip-chars-backward "^<[\r\n")
12731 (skip-chars-backward "<[")
12732 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12733 (>= (match-end 0) pos)
12734 (throw 'exit t)))
12735 nil)))
12737 (defun org-get-repeat (&optional timestamp)
12738 "Check if there is a time-stamp with repeater in this entry.
12740 Return the repeater, as a string, or nil. Also return nil when
12741 this function is called before first heading.
12743 When optional argument TIMESTAMP is a string, extract the
12744 repeater from there instead."
12745 (save-match-data
12746 (cond (timestamp
12747 (and (string-match org-repeat-re timestamp)
12748 (match-string-no-properties 1 timestamp)))
12749 ((org-before-first-heading-p) nil)
12751 (save-excursion
12752 (org-back-to-heading t)
12753 (let ((end (org-entry-end-position)))
12754 (catch :repeat
12755 (while (re-search-forward org-repeat-re end t)
12756 (when (save-match-data (org-at-timestamp-p 'agenda))
12757 (throw :repeat (match-string-no-properties 1)))))))))))
12759 (defvar org-last-changed-timestamp)
12760 (defvar org-last-inserted-timestamp)
12761 (defvar org-log-post-message)
12762 (defvar org-log-note-purpose)
12763 (defvar org-log-note-how nil)
12764 (defvar org-log-note-extra)
12765 (defun org-auto-repeat-maybe (done-word)
12766 "Check if the current headline contains a repeated time-stamp.
12768 If yes, set TODO state back to what it was and change the base date
12769 of repeating deadline/scheduled time stamps to new date.
12771 This function is run automatically after each state change to a DONE state."
12772 (let* ((repeat (org-get-repeat))
12773 (aa (assoc org-last-state org-todo-kwd-alist))
12774 (interpret (nth 1 aa))
12775 (head (nth 2 aa))
12776 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12777 (msg "Entry repeats: ")
12778 (org-log-done nil)
12779 (org-todo-log-states nil)
12780 (end (copy-marker (org-entry-end-position))))
12781 (unwind-protect
12782 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12783 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12784 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12785 org-todo-repeat-to-state)))
12786 (org-todo (cond
12787 ((and to-state (member to-state org-todo-keywords-1))
12788 to-state)
12789 ((eq interpret 'type) org-last-state)
12790 (head)
12791 (t 'none))))
12792 (org-back-to-heading t)
12793 (org-add-planning-info nil nil 'closed)
12794 ;; When `org-log-repeat' is non-nil or entry contains
12795 ;; a clock, set LAST_REPEAT property.
12796 (when (or org-log-repeat
12797 (catch :clock
12798 (save-excursion
12799 (while (re-search-forward org-clock-line-re end t)
12800 (when (org-at-clock-log-p) (throw :clock t))))))
12801 (org-entry-put nil "LAST_REPEAT" (format-time-string
12802 (org-time-stamp-format t t)
12803 (current-time))))
12804 (when org-log-repeat
12805 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12806 (memq 'org-add-log-note post-command-hook))
12807 ;; We are already setup for some record.
12808 (when (eq org-log-repeat 'note)
12809 ;; Make sure we take a note, not only a time stamp.
12810 (setq org-log-note-how 'note))
12811 ;; Set up for taking a record.
12812 (org-add-log-setup 'state
12813 (or done-word (car org-done-keywords))
12814 org-last-state
12815 org-log-repeat)))
12816 (let ((planning-re (regexp-opt
12817 (list org-scheduled-string org-deadline-string))))
12818 (while (re-search-forward org-ts-regexp end t)
12819 (let* ((ts (match-string 0))
12820 (planning? (org-at-planning-p))
12821 (type (if (not planning?) "Plain:"
12822 (save-excursion
12823 (re-search-backward
12824 planning-re (line-beginning-position) t)
12825 (match-string 0)))))
12826 (cond
12827 ;; Ignore fake time-stamps (e.g., within comments).
12828 ((not (org-at-timestamp-p 'agenda)))
12829 ;; Time-stamps without a repeater are usually
12830 ;; skipped. However, a SCHEDULED time-stamp without
12831 ;; one is removed, as they are no longer relevant.
12832 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12833 ts))
12834 (when (equal type org-scheduled-string)
12835 (org-remove-timestamp-with-keyword type)))
12837 (let ((n (string-to-number (match-string 2 ts)))
12838 (what (match-string 3 ts)))
12839 (when (equal what "w") (setq n (* n 7) what "d"))
12840 (when (and (equal what "h")
12841 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12842 ts)))
12843 (user-error
12844 "Cannot repeat in Repeat in %d hour(s) because no hour \
12845 has been set"
12847 ;; Preparation, see if we need to modify the start
12848 ;; date for the change.
12849 (when (match-end 1)
12850 (let ((time (save-match-data
12851 (org-time-string-to-time ts))))
12852 (cond
12853 ((equal (match-string 1 ts) ".")
12854 ;; Shift starting date to today
12855 (org-timestamp-change
12856 (- (org-today) (time-to-days time))
12857 'day))
12858 ((equal (match-string 1 ts) "+")
12859 (let ((nshiftmax 10)
12860 (nshift 0))
12861 (while (or (= nshift 0)
12862 (not (time-less-p (current-time) time)))
12863 (when (= (cl-incf nshift) nshiftmax)
12864 (or (y-or-n-p
12865 (format "%d repeater intervals were not \
12866 enough to shift date past today. Continue? "
12867 nshift))
12868 (user-error "Abort")))
12869 (org-timestamp-change n (cdr (assoc what whata)))
12870 (org-in-regexp org-ts-regexp3)
12871 (setq ts (match-string 1))
12872 (setq time
12873 (save-match-data
12874 (org-time-string-to-time ts)))))
12875 (org-timestamp-change (- n) (cdr (assoc what whata)))
12876 ;; Rematch, so that we have everything in place
12877 ;; for the real shift.
12878 (org-in-regexp org-ts-regexp3)
12879 (setq ts (match-string 1))
12880 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12881 ts)))))
12882 (save-excursion
12883 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12884 (setq msg
12885 (concat
12886 msg type " " org-last-changed-timestamp " "))))))))
12887 (setq org-log-post-message msg)
12888 (message "%s" msg))
12889 (set-marker end nil))))
12891 (defun org-show-todo-tree (arg)
12892 "Make a compact tree which shows all headlines marked with TODO.
12893 The tree will show the lines where the regexp matches, and all higher
12894 headlines above the match.
12895 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12896 With a numeric prefix N, construct a sparse tree for the Nth element
12897 of `org-todo-keywords-1'."
12898 (interactive "P")
12899 (let ((case-fold-search nil)
12900 (kwd-re
12901 (cond ((null arg) org-not-done-regexp)
12902 ((equal arg '(4))
12903 (let ((kwd
12904 (completing-read "Keyword (or KWD1|KWD2|...): "
12905 (mapcar #'list org-todo-keywords-1))))
12906 (concat "\\("
12907 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12908 "\\)\\>")))
12909 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12910 (regexp-quote (nth (1- (prefix-numeric-value arg))
12911 org-todo-keywords-1)))
12912 (t (user-error "Invalid prefix argument: %s" arg)))))
12913 (message "%d TODO entries found"
12914 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12916 (defun org--deadline-or-schedule (arg type time)
12917 "Insert DEADLINE or SCHEDULE information in current entry.
12918 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12919 `org-schedule' for information about ARG and TIME arguments."
12920 (let* ((deadline? (eq type 'deadline))
12921 (keyword (if deadline? org-deadline-string org-scheduled-string))
12922 (log (if deadline? org-log-redeadline org-log-reschedule))
12923 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12924 (old-date-time (and old-date (org-time-string-to-time old-date)))
12925 ;; Save repeater cookie from either TIME or current scheduled
12926 ;; time stamp. We are going to insert it back at the end of
12927 ;; the process.
12928 (repeater (or (and (org-string-nw-p time)
12929 ;; We use `org-repeat-re' because we need
12930 ;; to tell the difference between a real
12931 ;; repeater and a time delta, e.g. "+2d".
12932 (string-match org-repeat-re time)
12933 (match-string 1 time))
12934 (and (org-string-nw-p old-date)
12935 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12936 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12937 old-date)
12938 (match-string 1 old-date)))))
12939 (pcase arg
12940 (`(4)
12941 (when (and old-date log)
12942 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12943 nil old-date log))
12944 (org-remove-timestamp-with-keyword keyword)
12945 (message (if deadline? "Item no longer has a deadline."
12946 "Item is no longer scheduled.")))
12947 (`(16)
12948 (save-excursion
12949 (org-back-to-heading t)
12950 (let ((regexp (if deadline? org-deadline-time-regexp
12951 org-scheduled-time-regexp)))
12952 (if (not (re-search-forward regexp (line-end-position 2) t))
12953 (user-error (if deadline? "No deadline information to update"
12954 "No scheduled information to update"))
12955 (let* ((rpl0 (match-string 1))
12956 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12957 (msg (if deadline? "Warn starting from" "Delay until")))
12958 (replace-match
12959 (concat keyword
12960 " <" rpl
12961 (format " -%dd"
12962 (abs (- (time-to-days
12963 (save-match-data
12964 (org-read-date
12965 nil t nil msg old-date-time)))
12966 (time-to-days old-date-time))))
12967 ">") t t))))))
12969 (org-add-planning-info type time 'closed)
12970 (when (and old-date
12972 (not (equal old-date org-last-inserted-timestamp)))
12973 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12974 org-last-inserted-timestamp
12975 old-date
12976 log))
12977 (when repeater
12978 (save-excursion
12979 (org-back-to-heading t)
12980 (when (re-search-forward
12981 (concat keyword " " org-last-inserted-timestamp)
12982 (line-end-position 2)
12984 (goto-char (1- (match-end 0)))
12985 (insert " " repeater)
12986 (setq org-last-inserted-timestamp
12987 (concat (substring org-last-inserted-timestamp 0 -1)
12988 " " repeater
12989 (substring org-last-inserted-timestamp -1))))))
12990 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12991 org-last-inserted-timestamp)))))
12993 (defun org-deadline (arg &optional time)
12994 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12995 With one universal prefix argument, remove any deadline from the item.
12996 With two universal prefix arguments, prompt for a warning delay.
12997 With argument TIME, set the deadline at the corresponding date. TIME
12998 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12999 (interactive "P")
13000 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13001 (org-map-entries
13002 (lambda () (org--deadline-or-schedule arg 'deadline time))
13004 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13005 'region-start-level
13006 'region)
13007 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13008 (org--deadline-or-schedule arg 'deadline time)))
13010 (defun org-schedule (arg &optional time)
13011 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13012 With one universal prefix argument, remove any scheduling date from the item.
13013 With two universal prefix arguments, prompt for a delay cookie.
13014 With argument TIME, scheduled at the corresponding date. TIME can
13015 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13016 (interactive "P")
13017 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13018 (org-map-entries
13019 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13021 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13022 'region-start-level
13023 'region)
13024 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13025 (org--deadline-or-schedule arg 'scheduled time)))
13027 (defun org-get-scheduled-time (pom &optional inherit)
13028 "Get the scheduled time as a time tuple, of a format suitable
13029 for calling org-schedule with, or if there is no scheduling,
13030 returns nil."
13031 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13032 (when time
13033 (apply 'encode-time (org-parse-time-string time)))))
13035 (defun org-get-deadline-time (pom &optional inherit)
13036 "Get the deadline as a time tuple, of a format suitable for
13037 calling org-deadline with, or if there is no scheduling, returns
13038 nil."
13039 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13040 (when time
13041 (apply 'encode-time (org-parse-time-string time)))))
13043 (defun org-remove-timestamp-with-keyword (keyword)
13044 "Remove all time stamps with KEYWORD in the current entry."
13045 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13046 beg)
13047 (save-excursion
13048 (org-back-to-heading t)
13049 (setq beg (point))
13050 (outline-next-heading)
13051 (while (re-search-backward re beg t)
13052 (replace-match "")
13053 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13054 (equal (char-before) ?\ ))
13055 (backward-delete-char 1)
13056 (when (string-match "^[ \t]*$" (buffer-substring
13057 (point-at-bol) (point-at-eol)))
13058 (delete-region (point-at-bol)
13059 (min (point-max) (1+ (point-at-eol))))))))))
13061 (defvar org-time-was-given) ; dynamically scoped parameter
13062 (defvar org-end-time-was-given) ; dynamically scoped parameter
13064 (defun org-at-planning-p ()
13065 "Non-nil when point is on a planning info line."
13066 ;; This is as accurate and faster than `org-element-at-point' since
13067 ;; planning info location is fixed in the section.
13068 (org-with-wide-buffer
13069 (beginning-of-line)
13070 (and (looking-at-p org-planning-line-re)
13071 (eq (point)
13072 (ignore-errors
13073 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13074 (org-back-to-heading t)
13075 (org-with-limited-levels (org-back-to-heading t)))
13076 (line-beginning-position 2))))))
13078 (defun org-add-planning-info (what &optional time &rest remove)
13079 "Insert new timestamp with keyword in the planning line.
13080 WHAT indicates what kind of time stamp to add. It is a symbol
13081 among `closed', `deadline', `scheduled' and nil. TIME indicates
13082 the time to use. If none is given, the user is prompted for
13083 a date. REMOVE indicates what kind of entries to remove. An old
13084 WHAT entry will also be removed."
13085 (let (org-time-was-given org-end-time-was-given default-time default-input)
13086 (catch 'exit
13087 (when (and (memq what '(scheduled deadline))
13088 (or (not time)
13089 (and (stringp time)
13090 (string-match "^[-+]+[0-9]" time))))
13091 ;; Try to get a default date/time from existing timestamp
13092 (save-excursion
13093 (org-back-to-heading t)
13094 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13095 (when (re-search-forward (if (eq what 'scheduled)
13096 org-scheduled-time-regexp
13097 org-deadline-time-regexp)
13098 end t)
13099 (setq ts (match-string 1)
13100 default-time (apply 'encode-time (org-parse-time-string ts))
13101 default-input (and ts (org-get-compact-tod ts)))))))
13102 (when what
13103 (setq time
13104 (if (stringp time)
13105 ;; This is a string (relative or absolute), set
13106 ;; proper date.
13107 (apply #'encode-time
13108 (org-read-date-analyze
13109 time default-time (decode-time default-time)))
13110 ;; If necessary, get the time from the user
13111 (or time (org-read-date nil 'to-time nil nil
13112 default-time default-input)))))
13114 (org-with-wide-buffer
13115 (org-back-to-heading t)
13116 (forward-line)
13117 (unless (bolp) (insert "\n"))
13118 (cond ((looking-at-p org-planning-line-re)
13119 ;; Move to current indentation.
13120 (skip-chars-forward " \t")
13121 ;; Check if we have to remove something.
13122 (dolist (type (if what (cons what remove) remove))
13123 (save-excursion
13124 (when (re-search-forward
13125 (cl-case type
13126 (closed org-closed-time-regexp)
13127 (deadline org-deadline-time-regexp)
13128 (scheduled org-scheduled-time-regexp)
13129 (otherwise
13130 (error "Invalid planning type: %s" type)))
13131 (line-end-position) t)
13132 ;; Delete until next keyword or end of line.
13133 (delete-region
13134 (match-beginning 0)
13135 (if (re-search-forward org-keyword-time-not-clock-regexp
13136 (line-end-position)
13138 (match-beginning 0)
13139 (line-end-position))))))
13140 ;; If there is nothing more to add and no more keyword
13141 ;; is left, remove the line completely.
13142 (if (and (looking-at-p "[ \t]*$") (not what))
13143 (delete-region (line-beginning-position)
13144 (line-beginning-position 2))
13145 ;; If we removed last keyword, do not leave trailing
13146 ;; white space at the end of line.
13147 (let ((p (point)))
13148 (save-excursion
13149 (end-of-line)
13150 (unless (= (skip-chars-backward " \t" p) 0)
13151 (delete-region (point) (line-end-position)))))))
13152 ((not what) (throw 'exit nil)) ; Nothing to do.
13153 (t (insert-before-markers "\n")
13154 (backward-char 1)
13155 (when org-adapt-indentation
13156 (indent-to-column (1+ (org-outline-level))))))
13157 (when what
13158 ;; Insert planning keyword.
13159 (insert (cl-case what
13160 (closed org-closed-string)
13161 (deadline org-deadline-string)
13162 (scheduled org-scheduled-string)
13163 (otherwise (error "Invalid planning type: %s" what)))
13164 " ")
13165 ;; Insert associated timestamp.
13166 (let ((ts (org-insert-time-stamp
13167 time
13168 (or org-time-was-given
13169 (and (eq what 'closed) org-log-done-with-time))
13170 (eq what 'closed)
13171 nil nil (list org-end-time-was-given))))
13172 (unless (eolp) (insert " "))
13173 ts))))))
13175 (defvar org-log-note-marker (make-marker)
13176 "Marker pointing at the entry where the note is to be inserted.")
13177 (defvar org-log-note-purpose nil)
13178 (defvar org-log-note-state nil)
13179 (defvar org-log-note-previous-state nil)
13180 (defvar org-log-note-extra nil)
13181 (defvar org-log-note-window-configuration nil)
13182 (defvar org-log-note-return-to (make-marker))
13183 (defvar org-log-note-effective-time nil
13184 "Remembered current time so that dynamically scoped
13185 `org-extend-today-until' affects timestamps in state change log")
13187 (defvar org-log-post-message nil
13188 "Message to be displayed after a log note has been stored.
13189 The auto-repeater uses this.")
13191 (defun org-add-note ()
13192 "Add a note to the current entry.
13193 This is done in the same way as adding a state change note."
13194 (interactive)
13195 (org-add-log-setup 'note))
13197 (defun org-log-beginning (&optional create)
13198 "Return expected start of log notes in current entry.
13199 When optional argument CREATE is non-nil, the function creates
13200 a drawer to store notes, if necessary. Returned position ignores
13201 narrowing."
13202 (org-with-wide-buffer
13203 (let ((drawer (org-log-into-drawer)))
13204 (cond
13205 (drawer
13206 (org-end-of-meta-data)
13207 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13208 (end (if (org-at-heading-p) (point)
13209 (save-excursion (outline-next-heading) (point))))
13210 (case-fold-search t))
13211 (catch 'exit
13212 ;; Try to find existing drawer.
13213 (while (re-search-forward regexp end t)
13214 (let ((element (org-element-at-point)))
13215 (when (eq (org-element-type element) 'drawer)
13216 (let ((cend (org-element-property :contents-end element)))
13217 (when (and (not org-log-states-order-reversed) cend)
13218 (goto-char cend)))
13219 (throw 'exit nil))))
13220 ;; No drawer found. Create one, if permitted.
13221 (when create
13222 (unless (bolp) (insert "\n"))
13223 (let ((beg (point)))
13224 (insert ":" drawer ":\n:END:\n")
13225 (org-indent-region beg (point)))
13226 (end-of-line -1)))))
13228 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13229 (skip-chars-forward " \t\n")
13230 (beginning-of-line)
13231 (unless org-log-states-order-reversed
13232 (org-skip-over-state-notes)
13233 (skip-chars-backward " \t\n")
13234 (forward-line)))))
13235 (if (bolp) (point) (line-beginning-position 2))))
13237 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13238 "Set up the post command hook to take a note.
13239 If this is about to TODO state change, the new state is expected in STATE.
13240 HOW is an indicator what kind of note should be created.
13241 EXTRA is additional text that will be inserted into the notes buffer."
13242 (move-marker org-log-note-marker (point))
13243 (setq org-log-note-purpose purpose
13244 org-log-note-state state
13245 org-log-note-previous-state prev-state
13246 org-log-note-how how
13247 org-log-note-extra extra
13248 org-log-note-effective-time (org-current-effective-time))
13249 (add-hook 'post-command-hook 'org-add-log-note 'append))
13251 (defun org-skip-over-state-notes ()
13252 "Skip past the list of State notes in an entry."
13253 (when (ignore-errors (goto-char (org-in-item-p)))
13254 (let* ((struct (org-list-struct))
13255 (prevs (org-list-prevs-alist struct))
13256 (regexp
13257 (concat "[ \t]*- +"
13258 (replace-regexp-in-string
13259 " +" " +"
13260 (org-replace-escapes
13261 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13262 `(("%d" . ,org-ts-regexp-inactive)
13263 ("%D" . ,org-ts-regexp)
13264 ("%s" . "\"\\S-+\"")
13265 ("%S" . "\"\\S-+\"")
13266 ("%t" . ,org-ts-regexp-inactive)
13267 ("%T" . ,org-ts-regexp)
13268 ("%u" . ".*?")
13269 ("%U" . ".*?")))))))
13270 (while (looking-at-p regexp)
13271 (goto-char (or (org-list-get-next-item (point) struct prevs)
13272 (org-list-get-item-end (point) struct)))))))
13274 (defun org-add-log-note (&optional _purpose)
13275 "Pop up a window for taking a note, and add this note later."
13276 (remove-hook 'post-command-hook 'org-add-log-note)
13277 (setq org-log-note-window-configuration (current-window-configuration))
13278 (delete-other-windows)
13279 (move-marker org-log-note-return-to (point))
13280 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13281 (goto-char org-log-note-marker)
13282 (org-switch-to-buffer-other-window "*Org Note*")
13283 (erase-buffer)
13284 (if (memq org-log-note-how '(time state))
13285 (org-store-log-note)
13286 (let ((org-inhibit-startup t)) (org-mode))
13287 (insert (format "# Insert note for %s.
13288 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13289 (cond
13290 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13291 ((eq org-log-note-purpose 'done) "closed todo item")
13292 ((eq org-log-note-purpose 'state)
13293 (format "state change from \"%s\" to \"%s\""
13294 (or org-log-note-previous-state "")
13295 (or org-log-note-state "")))
13296 ((eq org-log-note-purpose 'reschedule)
13297 "rescheduling")
13298 ((eq org-log-note-purpose 'delschedule)
13299 "no longer scheduled")
13300 ((eq org-log-note-purpose 'redeadline)
13301 "changing deadline")
13302 ((eq org-log-note-purpose 'deldeadline)
13303 "removing deadline")
13304 ((eq org-log-note-purpose 'refile)
13305 "refiling")
13306 ((eq org-log-note-purpose 'note)
13307 "this entry")
13308 (t (error "This should not happen")))))
13309 (when org-log-note-extra (insert org-log-note-extra))
13310 (setq-local org-finish-function 'org-store-log-note)
13311 (run-hooks 'org-log-buffer-setup-hook)))
13313 (defvar org-note-abort nil) ; dynamically scoped
13314 (defun org-store-log-note ()
13315 "Finish taking a log note, and insert it to where it belongs."
13316 (let ((txt (prog1 (buffer-string)
13317 (kill-buffer)))
13318 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13319 lines)
13320 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13321 (setq txt (replace-match "" t t txt)))
13322 (when (string-match "\\s-+\\'" txt)
13323 (setq txt (replace-match "" t t txt)))
13324 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13325 (when (org-string-nw-p note)
13326 (setq note
13327 (org-replace-escapes
13328 note
13329 (list (cons "%u" (user-login-name))
13330 (cons "%U" user-full-name)
13331 (cons "%t" (format-time-string
13332 (org-time-stamp-format 'long 'inactive)
13333 org-log-note-effective-time))
13334 (cons "%T" (format-time-string
13335 (org-time-stamp-format 'long nil)
13336 org-log-note-effective-time))
13337 (cons "%d" (format-time-string
13338 (org-time-stamp-format nil 'inactive)
13339 org-log-note-effective-time))
13340 (cons "%D" (format-time-string
13341 (org-time-stamp-format nil nil)
13342 org-log-note-effective-time))
13343 (cons "%s" (cond
13344 ((not org-log-note-state) "")
13345 ((string-match-p org-ts-regexp
13346 org-log-note-state)
13347 (format "\"[%s]\""
13348 (substring org-log-note-state 1 -1)))
13349 (t (format "\"%s\"" org-log-note-state))))
13350 (cons "%S"
13351 (cond
13352 ((not org-log-note-previous-state) "")
13353 ((string-match-p org-ts-regexp
13354 org-log-note-previous-state)
13355 (format "\"[%s]\""
13356 (substring
13357 org-log-note-previous-state 1 -1)))
13358 (t (format "\"%s\""
13359 org-log-note-previous-state)))))))
13360 (when lines (setq note (concat note " \\\\")))
13361 (push note lines))
13362 (when (and lines (not org-note-abort))
13363 (with-current-buffer (marker-buffer org-log-note-marker)
13364 (org-with-wide-buffer
13365 ;; Find location for the new note.
13366 (goto-char org-log-note-marker)
13367 (set-marker org-log-note-marker nil)
13368 ;; Note associated to a clock is to be located right after
13369 ;; the clock. Do not move point.
13370 (unless (eq org-log-note-purpose 'clock-out)
13371 (goto-char (org-log-beginning t)))
13372 ;; Make sure point is at the beginning of an empty line.
13373 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13374 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13375 ;; In an existing list, add a new item at the top level.
13376 ;; Otherwise, indent line like a regular one.
13377 (let ((itemp (org-in-item-p)))
13378 (if itemp
13379 (indent-line-to
13380 (let ((struct (save-excursion
13381 (goto-char itemp) (org-list-struct))))
13382 (org-list-get-ind (org-list-get-top-point struct) struct)))
13383 (org-indent-line)))
13384 (insert (org-list-bullet-string "-") (pop lines))
13385 (let ((ind (org-list-item-body-column (line-beginning-position))))
13386 (dolist (line lines)
13387 (insert "\n")
13388 (indent-line-to ind)
13389 (insert line)))
13390 (message "Note stored")
13391 (org-back-to-heading t)
13392 (org-cycle-hide-drawers 'children))
13393 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13394 ;; from within `org-add-log-note' because `buffer-undo-list'
13395 ;; is then modified outside of `org-with-remote-undo'.
13396 (when (eq this-command 'org-agenda-todo)
13397 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13398 ;; Don't add undo information when called from `org-agenda-todo'.
13399 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13400 (set-window-configuration org-log-note-window-configuration)
13401 (with-current-buffer (marker-buffer org-log-note-return-to)
13402 (goto-char org-log-note-return-to))
13403 (move-marker org-log-note-return-to nil)
13404 (when org-log-post-message (message "%s" org-log-post-message))))
13406 (defun org-remove-empty-drawer-at (pos)
13407 "Remove an empty drawer at position POS.
13408 POS may also be a marker."
13409 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13410 (org-with-wide-buffer
13411 (goto-char pos)
13412 (let ((drawer (org-element-at-point)))
13413 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13414 (not (org-element-property :contents-begin drawer)))
13415 (delete-region (org-element-property :begin drawer)
13416 (progn (goto-char (org-element-property :end drawer))
13417 (skip-chars-backward " \r\t\n")
13418 (forward-line)
13419 (point))))))))
13421 (defvar org-ts-type nil)
13422 (defun org-sparse-tree (&optional arg type)
13423 "Create a sparse tree, prompt for the details.
13424 This command can create sparse trees. You first need to select the type
13425 of match used to create the tree:
13427 t Show all TODO entries.
13428 T Show entries with a specific TODO keyword.
13429 m Show entries selected by a tags/property match.
13430 p Enter a property name and its value (both with completion on existing
13431 names/values) and show entries with that property.
13432 r Show entries matching a regular expression (`/' can be used as well).
13433 b Show deadlines and scheduled items before a date.
13434 a Show deadlines and scheduled items after a date.
13435 d Show deadlines due within `org-deadline-warning-days'.
13436 D Show deadlines and scheduled items between a date range."
13437 (interactive "P")
13438 (setq type (or type org-sparse-tree-default-date-type))
13439 (setq org-ts-type type)
13440 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13441 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13442 \[c]ycle through date types: %s"
13443 (cl-case type
13444 (all "all timestamps")
13445 (scheduled "only scheduled")
13446 (deadline "only deadline")
13447 (active "only active timestamps")
13448 (inactive "only inactive timestamps")
13449 (closed "with a closed time-stamp")
13450 (otherwise "scheduled/deadline")))
13451 (let ((answer (read-char-exclusive)))
13452 (cl-case answer
13454 (org-sparse-tree
13456 (cadr
13457 (memq type '(nil all scheduled deadline active inactive closed)))))
13458 (?d (call-interactively 'org-check-deadlines))
13459 (?b (call-interactively 'org-check-before-date))
13460 (?a (call-interactively 'org-check-after-date))
13461 (?D (call-interactively 'org-check-dates-range))
13462 (?t (call-interactively 'org-show-todo-tree))
13463 (?T (org-show-todo-tree '(4)))
13464 (?m (call-interactively 'org-match-sparse-tree))
13465 ((?p ?P)
13466 (let* ((kwd (completing-read
13467 "Property: " (mapcar #'list (org-buffer-property-keys))))
13468 (value (completing-read
13469 "Value: " (mapcar #'list (org-property-values kwd)))))
13470 (unless (string-match "\\`{.*}\\'" value)
13471 (setq value (concat "\"" value "\"")))
13472 (org-match-sparse-tree arg (concat kwd "=" value))))
13473 ((?r ?R ?/) (call-interactively 'org-occur))
13474 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13476 (defvar-local org-occur-highlights nil
13477 "List of overlays used for occur matches.")
13478 (defvar-local org-occur-parameters nil
13479 "Parameters of the active org-occur calls.
13480 This is a list, each call to org-occur pushes as cons cell,
13481 containing the regular expression and the callback, onto the list.
13482 The list can contain several entries if `org-occur' has been called
13483 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13484 will only contain one set of parameters. When the highlights are
13485 removed (for example with `C-c C-c', or with the next edit (depending
13486 on `org-remove-highlights-with-change'), this variable is emptied
13487 as well.")
13489 (defun org-occur (regexp &optional keep-previous callback)
13490 "Make a compact tree which shows all matches of REGEXP.
13492 The tree will show the lines where the regexp matches, and any other context
13493 defined in `org-show-context-detail', which see.
13495 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13496 done by a previous call to `org-occur' will be kept, to allow stacking of
13497 calls to this command.
13499 Optional argument CALLBACK can be a function of no argument. In this case,
13500 it is called with point at the end of the match, match data being set
13501 accordingly. Current match is shown only if the return value is non-nil.
13502 The function must neither move point nor alter narrowing."
13503 (interactive "sRegexp: \nP")
13504 (when (equal regexp "")
13505 (user-error "Regexp cannot be empty"))
13506 (unless keep-previous
13507 (org-remove-occur-highlights nil nil t))
13508 (push (cons regexp callback) org-occur-parameters)
13509 (let ((cnt 0))
13510 (save-excursion
13511 (goto-char (point-min))
13512 (when (or (not keep-previous) ; do not want to keep
13513 (not org-occur-highlights)) ; no previous matches
13514 ;; hide everything
13515 (org-overview))
13516 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13517 (isearch-no-upper-case-p regexp t)
13518 org-occur-case-fold-search)))
13519 (while (re-search-forward regexp nil t)
13520 (when (or (not callback)
13521 (save-match-data (funcall callback)))
13522 (setq cnt (1+ cnt))
13523 (when org-highlight-sparse-tree-matches
13524 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13525 (org-show-context 'occur-tree)))))
13526 (when org-remove-highlights-with-change
13527 (add-hook 'before-change-functions 'org-remove-occur-highlights
13528 nil 'local))
13529 (unless org-sparse-tree-open-archived-trees
13530 (org-hide-archived-subtrees (point-min) (point-max)))
13531 (run-hooks 'org-occur-hook)
13532 (when (called-interactively-p 'interactive)
13533 (message "%d match(es) for regexp %s" cnt regexp))
13534 cnt))
13536 (defun org-occur-next-match (&optional n _reset)
13537 "Function for `next-error-function' to find sparse tree matches.
13538 N is the number of matches to move, when negative move backwards.
13539 This function always goes back to the starting point when no
13540 match is found."
13541 (let* ((limit (if (< n 0) (point-min) (point-max)))
13542 (search-func (if (< n 0)
13543 'previous-single-char-property-change
13544 'next-single-char-property-change))
13545 (n (abs n))
13546 (pos (point))
13548 (catch 'exit
13549 (while (setq p1 (funcall search-func (point) 'org-type))
13550 (when (equal p1 limit)
13551 (goto-char pos)
13552 (user-error "No more matches"))
13553 (when (equal (get-char-property p1 'org-type) 'org-occur)
13554 (setq n (1- n))
13555 (when (= n 0)
13556 (goto-char p1)
13557 (throw 'exit (point))))
13558 (goto-char p1))
13559 (goto-char p1)
13560 (user-error "No more matches"))))
13562 (defun org-show-context (&optional key)
13563 "Make sure point and context are visible.
13564 Optional argument KEY, when non-nil, is a symbol. See
13565 `org-show-context-detail' for allowed values and how much is to
13566 be shown."
13567 (org-show-set-visibility
13568 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13569 ((cdr (assq key org-show-context-detail)))
13570 (t (cdr (assq 'default org-show-context-detail))))))
13572 (defun org-show-set-visibility (detail)
13573 "Set visibility around point according to DETAIL.
13574 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13575 `tree', `canonical' or t. See `org-show-context-detail' for more
13576 information."
13577 ;; Show current heading and possibly its entry, following headline
13578 ;; or all children.
13579 (if (and (org-at-heading-p) (not (eq detail 'local)))
13580 (org-flag-heading nil)
13581 (org-show-entry)
13582 ;; If point is hidden within a drawer or a block, make sure to
13583 ;; expose it.
13584 (dolist (o (overlays-at (point)))
13585 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13586 (delete-overlay o)))
13587 (unless (org-before-first-heading-p)
13588 (org-with-limited-levels
13589 (cl-case detail
13590 ((tree canonical t) (org-show-children))
13591 ((nil minimal ancestors))
13592 (t (save-excursion
13593 (outline-next-heading)
13594 (org-flag-heading nil)))))))
13595 ;; Show all siblings.
13596 (when (eq detail 'lineage) (org-show-siblings))
13597 ;; Show ancestors, possibly with their children.
13598 (when (memq detail '(ancestors lineage tree canonical t))
13599 (save-excursion
13600 (while (org-up-heading-safe)
13601 (org-flag-heading nil)
13602 (when (memq detail '(canonical t)) (org-show-entry))
13603 (when (memq detail '(tree canonical t)) (org-show-children))))))
13605 (defvar org-reveal-start-hook nil
13606 "Hook run before revealing a location.")
13608 (defun org-reveal (&optional siblings)
13609 "Show current entry, hierarchy above it, and the following headline.
13611 This can be used to show a consistent set of context around
13612 locations exposed with `org-show-context'.
13614 With optional argument SIBLINGS, on each level of the hierarchy all
13615 siblings are shown. This repairs the tree structure to what it would
13616 look like when opened with hierarchical calls to `org-cycle'.
13618 With a \\[universal-argument] \\[universal-argument] prefix, \
13619 go to the parent and show the entire tree."
13620 (interactive "P")
13621 (run-hooks 'org-reveal-start-hook)
13622 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13623 ((equal siblings '(16))
13624 (save-excursion
13625 (when (org-up-heading-safe)
13626 (org-show-subtree)
13627 (run-hook-with-args 'org-cycle-hook 'subtree))))
13628 (t (org-show-set-visibility 'lineage))))
13630 (defun org-highlight-new-match (beg end)
13631 "Highlight from BEG to END and mark the highlight is an occur headline."
13632 (let ((ov (make-overlay beg end)))
13633 (overlay-put ov 'face 'secondary-selection)
13634 (overlay-put ov 'org-type 'org-occur)
13635 (push ov org-occur-highlights)))
13637 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13638 "Remove the occur highlights from the buffer.
13639 BEG and END are ignored. If NOREMOVE is nil, remove this function
13640 from the `before-change-functions' in the current buffer."
13641 (interactive)
13642 (unless org-inhibit-highlight-removal
13643 (mapc #'delete-overlay org-occur-highlights)
13644 (setq org-occur-highlights nil)
13645 (setq org-occur-parameters nil)
13646 (unless noremove
13647 (remove-hook 'before-change-functions
13648 'org-remove-occur-highlights 'local))))
13650 ;;;; Priorities
13652 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13653 "Regular expression matching the priority indicator.")
13655 (defvar org-remove-priority-next-time nil)
13657 (defun org-priority-up ()
13658 "Increase the priority of the current item."
13659 (interactive)
13660 (org-priority 'up))
13662 (defun org-priority-down ()
13663 "Decrease the priority of the current item."
13664 (interactive)
13665 (org-priority 'down))
13667 (defun org-priority (&optional action _show)
13668 "Change the priority of an item.
13669 ACTION can be `set', `up', `down', or a character."
13670 (interactive "P")
13671 (if (equal action '(4))
13672 (org-show-priority)
13673 (unless org-enable-priority-commands
13674 (user-error "Priority commands are disabled"))
13675 (setq action (or action 'set))
13676 (let (current new news have remove)
13677 (save-excursion
13678 (org-back-to-heading t)
13679 (when (looking-at org-priority-regexp)
13680 (setq current (string-to-char (match-string 2))
13681 have t))
13682 (cond
13683 ((eq action 'remove)
13684 (setq remove t new ?\ ))
13685 ((or (eq action 'set)
13686 (integerp action))
13687 (if (not (eq action 'set))
13688 (setq new action)
13689 (message "Priority %c-%c, SPC to remove: "
13690 org-highest-priority org-lowest-priority)
13691 (save-match-data
13692 (setq new (read-char-exclusive))))
13693 (when (and (= (upcase org-highest-priority) org-highest-priority)
13694 (= (upcase org-lowest-priority) org-lowest-priority))
13695 (setq new (upcase new)))
13696 (cond ((equal new ?\ ) (setq remove t))
13697 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13698 (user-error "Priority must be between `%c' and `%c'"
13699 org-highest-priority org-lowest-priority))))
13700 ((eq action 'up)
13701 (setq new (if have
13702 (1- current) ; normal cycling
13703 ;; last priority was empty
13704 (if (eq last-command this-command)
13705 org-lowest-priority ; wrap around empty to lowest
13706 ;; default
13707 (if org-priority-start-cycle-with-default
13708 org-default-priority
13709 (1- org-default-priority))))))
13710 ((eq action 'down)
13711 (setq new (if have
13712 (1+ current) ; normal cycling
13713 ;; last priority was empty
13714 (if (eq last-command this-command)
13715 org-highest-priority ; wrap around empty to highest
13716 ;; default
13717 (if org-priority-start-cycle-with-default
13718 org-default-priority
13719 (1+ org-default-priority))))))
13720 (t (user-error "Invalid action")))
13721 (when (or (< (upcase new) org-highest-priority)
13722 (> (upcase new) org-lowest-priority))
13723 (if (and (memq action '(up down))
13724 (not have) (not (eq last-command this-command)))
13725 ;; `new' is from default priority
13726 (error
13727 "The default can not be set, see `org-default-priority' why")
13728 ;; normal cycling: `new' is beyond highest/lowest priority
13729 ;; and is wrapped around to the empty priority
13730 (setq remove t)))
13731 (setq news (format "%c" new))
13732 (if have
13733 (if remove
13734 (replace-match "" t t nil 1)
13735 (replace-match news t t nil 2))
13736 (if remove
13737 (user-error "No priority cookie found in line")
13738 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13739 (if (match-end 2)
13740 (progn
13741 (goto-char (match-end 2))
13742 (insert " [#" news "]"))
13743 (goto-char (match-beginning 3))
13744 (insert "[#" news "] "))))
13745 (org-set-tags nil 'align))
13746 (if remove
13747 (message "Priority removed")
13748 (message "Priority of current item set to %s" news)))))
13750 (defun org-show-priority ()
13751 "Show the priority of the current item.
13752 This priority is composed of the main priority given with the [#A] cookies,
13753 and by additional input from the age of a schedules or deadline entry."
13754 (interactive)
13755 (let ((pri (if (eq major-mode 'org-agenda-mode)
13756 (org-get-at-bol 'priority)
13757 (save-excursion
13758 (save-match-data
13759 (beginning-of-line)
13760 (and (looking-at org-heading-regexp)
13761 (org-get-priority (match-string 0))))))))
13762 (message "Priority is %d" (if pri pri -1000))))
13764 (defun org-get-priority (s)
13765 "Find priority cookie and return priority."
13766 (save-match-data
13767 (if (functionp org-get-priority-function)
13768 (funcall org-get-priority-function)
13769 (if (not (string-match org-priority-regexp s))
13770 (* 1000 (- org-lowest-priority org-default-priority))
13771 (* 1000 (- org-lowest-priority
13772 (string-to-char (match-string 2 s))))))))
13774 ;;;; Tags
13776 (defvar org-agenda-archives-mode)
13777 (defvar org-map-continue-from nil
13778 "Position from where mapping should continue.
13779 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13781 (defvar org-scanner-tags nil
13782 "The current tag list while the tags scanner is running.")
13784 (defvar org-trust-scanner-tags nil
13785 "Should `org-get-tags-at' use the tags for the scanner.
13786 This is for internal dynamical scoping only.
13787 When this is non-nil, the function `org-get-tags-at' will return the value
13788 of `org-scanner-tags' instead of building the list by itself. This
13789 can lead to large speed-ups when the tags scanner is used in a file with
13790 many entries, and when the list of tags is retrieved, for example to
13791 obtain a list of properties. Building the tags list for each entry in such
13792 a file becomes an N^2 operation - but with this variable set, it scales
13793 as N.")
13795 (defvar org--matcher-tags-todo-only nil)
13797 (defun org-scan-tags (action matcher todo-only &optional start-level)
13798 "Scan headline tags with inheritance and produce output ACTION.
13800 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13801 or `agenda' to produce an entry list for an agenda view. It can also be
13802 a Lisp form or a function that should be called at each matched headline, in
13803 this case the return value is a list of all return values from these calls.
13805 MATCHER is a function accepting three arguments, returning
13806 a non-nil value whenever a given set of tags qualifies a headline
13807 for inclusion. See `org-make-tags-matcher' for more information.
13808 As a special case, it can also be set to t (respectively nil) in
13809 order to match all (respectively none) headline.
13811 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13812 included in the output.
13814 START-LEVEL can be a string with asterisks, reducing the scope to
13815 headlines matching this string."
13816 (require 'org-agenda)
13817 (let* ((re (concat "^"
13818 (if start-level
13819 ;; Get the correct level to match
13820 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13821 org-outline-regexp)
13822 " *\\(\\<\\("
13823 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13824 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13825 (props (list 'face 'default
13826 'done-face 'org-agenda-done
13827 'undone-face 'default
13828 'mouse-face 'highlight
13829 'org-not-done-regexp org-not-done-regexp
13830 'org-todo-regexp org-todo-regexp
13831 'org-complex-heading-regexp org-complex-heading-regexp
13832 'help-echo
13833 (format "mouse-2 or RET jump to org file %s"
13834 (abbreviate-file-name
13835 (or (buffer-file-name (buffer-base-buffer))
13836 (buffer-name (buffer-base-buffer)))))))
13837 (org-map-continue-from nil)
13838 lspos tags tags-list
13839 (tags-alist (list (cons 0 org-file-tags)))
13840 (llast 0) rtn rtn1 level category i txt
13841 todo marker entry priority
13842 ts-date ts-date-type ts-date-pair)
13843 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13844 (setq action (list 'lambda nil action)))
13845 (save-excursion
13846 (goto-char (point-min))
13847 (when (eq action 'sparse-tree)
13848 (org-overview)
13849 (org-remove-occur-highlights))
13850 (while (let (case-fold-search)
13851 (re-search-forward re nil t))
13852 (setq org-map-continue-from nil)
13853 (catch :skip
13854 (setq todo
13855 ;; TODO: is the 1-2 difference a bug?
13856 (when (match-end 1) (match-string-no-properties 2))
13857 tags (when (match-end 4) (match-string-no-properties 4)))
13858 (goto-char (setq lspos (match-beginning 0)))
13859 (setq level (org-reduced-level (org-outline-level))
13860 category (org-get-category))
13861 (when (eq action 'agenda)
13862 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13863 ts-date (car ts-date-pair)
13864 ts-date-type (cdr ts-date-pair)))
13865 (setq i llast llast level)
13866 ;; remove tag lists from same and sublevels
13867 (while (>= i level)
13868 (when (setq entry (assoc i tags-alist))
13869 (setq tags-alist (delete entry tags-alist)))
13870 (setq i (1- i)))
13871 ;; add the next tags
13872 (when tags
13873 (setq tags (org-split-string tags ":")
13874 tags-alist
13875 (cons (cons level tags) tags-alist)))
13876 ;; compile tags for current headline
13877 (setq tags-list
13878 (if org-use-tag-inheritance
13879 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13880 tags)
13881 org-scanner-tags tags-list)
13882 (when org-use-tag-inheritance
13883 (setcdr (car tags-alist)
13884 (mapcar (lambda (x)
13885 (setq x (copy-sequence x))
13886 (org-add-prop-inherited x))
13887 (cdar tags-alist))))
13888 (when (and tags org-use-tag-inheritance
13889 (or (not (eq t org-use-tag-inheritance))
13890 org-tags-exclude-from-inheritance))
13891 ;; Selective inheritance, remove uninherited ones.
13892 (setcdr (car tags-alist)
13893 (org-remove-uninherited-tags (cdar tags-alist))))
13894 (when (and
13896 ;; eval matcher only when the todo condition is OK
13897 (and (or (not todo-only) (member todo org-todo-keywords-1))
13898 (if (functionp matcher)
13899 (let ((case-fold-search t) (org-trust-scanner-tags t))
13900 (funcall matcher todo tags-list level))
13901 matcher))
13903 ;; Call the skipper, but return t if it does not
13904 ;; skip, so that the `and' form continues evaluating.
13905 (progn
13906 (unless (eq action 'sparse-tree) (org-agenda-skip))
13909 ;; Check if timestamps are deselecting this entry
13910 (or (not todo-only)
13911 (and (member todo org-todo-keywords-1)
13912 (or (not org-agenda-tags-todo-honor-ignore-options)
13913 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13915 ;; select this headline
13916 (cond
13917 ((eq action 'sparse-tree)
13918 (and org-highlight-sparse-tree-matches
13919 (org-get-heading) (match-end 0)
13920 (org-highlight-new-match
13921 (match-beginning 1) (match-end 1)))
13922 (org-show-context 'tags-tree))
13923 ((eq action 'agenda)
13924 (setq txt (org-agenda-format-item
13926 (concat
13927 (if (eq org-tags-match-list-sublevels 'indented)
13928 (make-string (1- level) ?.) "")
13929 (org-get-heading))
13930 (make-string level ?\s)
13931 category
13932 tags-list)
13933 priority (org-get-priority txt))
13934 (goto-char lspos)
13935 (setq marker (org-agenda-new-marker))
13936 (org-add-props txt props
13937 'org-marker marker 'org-hd-marker marker 'org-category category
13938 'todo-state todo
13939 'ts-date ts-date
13940 'priority priority
13941 'type (concat "tagsmatch" ts-date-type))
13942 (push txt rtn))
13943 ((functionp action)
13944 (setq org-map-continue-from nil)
13945 (save-excursion
13946 (setq rtn1 (funcall action))
13947 (push rtn1 rtn)))
13948 (t (user-error "Invalid action")))
13950 ;; if we are to skip sublevels, jump to end of subtree
13951 (unless org-tags-match-list-sublevels
13952 (org-end-of-subtree t)
13953 (backward-char 1))))
13954 ;; Get the correct position from where to continue
13955 (if org-map-continue-from
13956 (goto-char org-map-continue-from)
13957 (and (= (point) lspos) (end-of-line 1)))))
13958 (when (and (eq action 'sparse-tree)
13959 (not org-sparse-tree-open-archived-trees))
13960 (org-hide-archived-subtrees (point-min) (point-max)))
13961 (nreverse rtn)))
13963 (defun org-remove-uninherited-tags (tags)
13964 "Remove all tags that are not inherited from the list TAGS."
13965 (cond
13966 ((eq org-use-tag-inheritance t)
13967 (if org-tags-exclude-from-inheritance
13968 (org-delete-all org-tags-exclude-from-inheritance tags)
13969 tags))
13970 ((not org-use-tag-inheritance) nil)
13971 ((stringp org-use-tag-inheritance)
13972 (delq nil (mapcar
13973 (lambda (x)
13974 (if (and (string-match org-use-tag-inheritance x)
13975 (not (member x org-tags-exclude-from-inheritance)))
13976 x nil))
13977 tags)))
13978 ((listp org-use-tag-inheritance)
13979 (delq nil (mapcar
13980 (lambda (x)
13981 (if (member x org-use-tag-inheritance) x nil))
13982 tags)))))
13984 (defun org-match-sparse-tree (&optional todo-only match)
13985 "Create a sparse tree according to tags string MATCH.
13987 MATCH is a string with match syntax. It can contain a selection
13988 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13989 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13990 those. See the manual for details.
13992 If optional argument TODO-ONLY is non-nil, only select lines that
13993 are also TODO tasks."
13994 (interactive "P")
13995 (org-agenda-prepare-buffers (list (current-buffer)))
13996 (let ((org--matcher-tags-todo-only todo-only))
13997 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13998 org--matcher-tags-todo-only)))
14000 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14002 (defvar org-cached-props nil)
14003 (defun org-cached-entry-get (pom property)
14004 (if (or (eq t org-use-property-inheritance)
14005 (and (stringp org-use-property-inheritance)
14006 (let ((case-fold-search t))
14007 (string-match-p org-use-property-inheritance property)))
14008 (and (listp org-use-property-inheritance)
14009 (member-ignore-case property org-use-property-inheritance)))
14010 ;; Caching is not possible, check it directly.
14011 (org-entry-get pom property 'inherit)
14012 ;; Get all properties, so we can do complicated checks easily.
14013 (cdr (assoc-string property
14014 (or org-cached-props
14015 (setq org-cached-props (org-entry-properties pom)))
14016 t))))
14018 (defun org-global-tags-completion-table (&optional files)
14019 "Return the list of all tags in all agenda buffer/files.
14020 Optional FILES argument is a list of files which can be used
14021 instead of the agenda files."
14022 (save-excursion
14023 (org-uniquify
14024 (delq nil
14025 (apply #'append
14026 (mapcar
14027 (lambda (file)
14028 (set-buffer (find-file-noselect file))
14029 (mapcar (lambda (x)
14030 (and (stringp (car-safe x))
14031 (list (car-safe x))))
14032 (or org-current-tag-alist (org-get-buffer-tags))))
14033 (if (car-safe files) files
14034 (org-agenda-files))))))))
14036 (defun org-make-tags-matcher (match)
14037 "Create the TAGS/TODO matcher form for the selection string MATCH.
14039 Returns a cons of the selection string MATCH and a function
14040 implementing the matcher.
14042 The matcher is to be called at an Org entry, with point on the
14043 headline, and returns non-nil if the entry matches the selection
14044 string MATCH. It must be called with three arguments: the TODO
14045 keyword at the entry (or nil if none), the list of all tags at
14046 the entry including inherited ones and the reduced level of the
14047 headline. Additionally, the category of the entry, if any, must
14048 be specified as the text property `org-category' on the headline.
14050 This function sets the variable `org--matcher-tags-todo-only' to
14051 a non-nil value if the matcher restricts matching to TODO
14052 entries, otherwise it is not touched.
14054 See also `org-scan-tags'."
14055 (unless match
14056 ;; Get a new match request, with completion against the global
14057 ;; tags table and the local tags in current buffer.
14058 (let ((org-last-tags-completion-table
14059 (org-uniquify
14060 (delq nil (append (org-get-buffer-tags)
14061 (org-global-tags-completion-table))))))
14062 (setq match
14063 (completing-read
14064 "Match: "
14065 'org-tags-completion-function nil nil nil 'org-tags-history))))
14067 (let ((match0 match)
14068 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14069 (start 0)
14070 tagsmatch todomatch tagsmatcher todomatcher)
14072 ;; Expand group tags.
14073 (setq match (org-tags-expand match))
14075 ;; Check if there is a TODO part of this match, which would be the
14076 ;; part after a "/". To make sure that this slash is not part of
14077 ;; a property value to be matched against, we also check that
14078 ;; there is no / after that slash. First, find the last slash.
14079 (let ((s 0))
14080 (while (string-match "/+" match s)
14081 (setq start (match-beginning 0))
14082 (setq s (match-end 0))))
14083 (if (and (string-match "/+" match start)
14084 (not (string-match-p "\"" match start)))
14085 ;; Match contains also a TODO-matching request.
14086 (progn
14087 (setq tagsmatch (substring match 0 (match-beginning 0)))
14088 (setq todomatch (substring match (match-end 0)))
14089 (when (string-prefix-p "!" todomatch)
14090 (setq org--matcher-tags-todo-only t)
14091 (setq todomatch (substring todomatch 1)))
14092 (when (string-match "\\`\\s-*\\'" todomatch)
14093 (setq todomatch nil)))
14094 ;; Only matching tags.
14095 (setq tagsmatch match)
14096 (setq todomatch nil))
14098 ;; Make the tags matcher.
14099 (when (org-string-nw-p tagsmatch)
14100 (let ((orlist nil)
14101 (orterms (org-split-string tagsmatch "|"))
14102 term)
14103 (while (setq term (pop orterms))
14104 (while (and (equal (substring term -1) "\\") orterms)
14105 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14106 (while (string-match re term)
14107 (let* ((rest (substring term (match-end 0)))
14108 (minus (and (match-end 1)
14109 (equal (match-string 1 term) "-")))
14110 (tag (save-match-data
14111 (replace-regexp-in-string
14112 "\\\\-" "-" (match-string 2 term))))
14113 (regexp (eq (string-to-char tag) ?{))
14114 (levelp (match-end 4))
14115 (propp (match-end 5))
14117 (cond
14118 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14119 (levelp
14120 `(,(org-op-to-function (match-string 3 term))
14121 level
14122 ,(string-to-number (match-string 4 term))))
14123 (propp
14124 (let* ((gv (pcase (upcase (match-string 5 term))
14125 ("CATEGORY"
14126 '(get-text-property (point) 'org-category))
14127 ("TODO" 'todo)
14128 (p `(org-cached-entry-get nil ,p))))
14129 (pv (match-string 7 term))
14130 (regexp (eq (string-to-char pv) ?{))
14131 (strp (eq (string-to-char pv) ?\"))
14132 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14133 (po (org-op-to-function (match-string 6 term)
14134 (if timep 'time strp))))
14135 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14136 (when timep (setq pv (org-matcher-time pv)))
14137 (cond ((and regexp (eq po 'org<>))
14138 `(not (string-match ,pv (or ,gv ""))))
14139 (regexp `(string-match ,pv (or ,gv "")))
14140 (strp `(,po (or ,gv "") ,pv))
14142 `(,po
14143 (string-to-number (or ,gv ""))
14144 ,(string-to-number pv))))))
14145 (t `(member ,tag tags-list)))))
14146 (push (if minus `(not ,mm) mm) tagsmatcher)
14147 (setq term rest)))
14148 (push `(and ,@tagsmatcher) orlist)
14149 (setq tagsmatcher nil))
14150 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14152 ;; Make the TODO matcher.
14153 (when (org-string-nw-p todomatch)
14154 (let ((orlist nil))
14155 (dolist (term (org-split-string todomatch "|"))
14156 (while (string-match re term)
14157 (let* ((minus (and (match-end 1)
14158 (equal (match-string 1 term) "-")))
14159 (kwd (match-string 2 term))
14160 (regexp (eq (string-to-char kwd) ?{))
14161 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14162 `(equal todo ,kwd))))
14163 (push (if minus `(not ,mm) mm) todomatcher))
14164 (setq term (substring term (match-end 0))))
14165 (push (if (> (length todomatcher) 1)
14166 (cons 'and todomatcher)
14167 (car todomatcher))
14168 orlist)
14169 (setq todomatcher nil))
14170 (setq todomatcher (cons 'or orlist))))
14172 ;; Return the string and function of the matcher. If no
14173 ;; tags-specific or todo-specific matcher exists, match
14174 ;; everything.
14175 (let ((matcher (if (and tagsmatcher todomatcher)
14176 `(and ,tagsmatcher ,todomatcher)
14177 (or tagsmatcher todomatcher t))))
14178 (when org--matcher-tags-todo-only
14179 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14180 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14182 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14183 "Expand group tags in MATCH.
14185 This replaces every group tag in MATCH with a regexp tag search.
14186 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14187 will be replaced like this:
14189 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14190 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14191 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14193 Replacing by a regexp preserves the structure of the match.
14194 E.g., this expansion
14196 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14198 will match anything tagged with \"Lab\" and \"Home\", or tagged
14199 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14201 A group tag in MATCH can contain regular expressions of its own.
14202 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14203 will be replaced like this:
14205 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14207 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14208 assumed to be a single group tag, and the function will return
14209 the list of tags in this group.
14211 When DOWNCASE is non-nil, expand downcased TAGS."
14212 (if org-group-tags
14213 (let* ((case-fold-search t)
14214 (stable org-mode-syntax-table)
14215 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14216 (taggroups (if downcased
14217 (mapcar (lambda (tg) (mapcar #'downcase tg))
14218 taggroups)
14219 taggroups))
14220 (taggroups-keys (mapcar #'car taggroups))
14221 (return-match (if downcased (downcase match) match))
14222 (count 0)
14223 (work-already-expanded tags-already-expanded)
14224 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14225 ;; @ and _ are allowed as word-components in tags.
14226 (modify-syntax-entry ?@ "w" stable)
14227 (modify-syntax-entry ?_ "w" stable)
14228 ;; Temporarily replace regexp-expressions in the match-expression.
14229 (while (string-match "{.+?}" return-match)
14230 (cl-incf count)
14231 (push (match-string 0 return-match) regexps-in-match)
14232 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14233 (while (and taggroups-keys
14234 (with-syntax-table stable
14235 (string-match
14236 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14237 (regexp-opt taggroups-keys) "\\>\\)")
14238 return-match)))
14239 (let* ((dir (match-string 1 return-match))
14240 (tag (match-string 2 return-match))
14241 (tag (if downcased (downcase tag) tag)))
14242 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14243 (member tag work-already-expanded))
14244 (setq tags-in-group (assoc tag taggroups))
14245 (push tag work-already-expanded)
14246 ;; Recursively expand each tag in the group, if the tag hasn't
14247 ;; already been expanded. Restore the match-data after all recursive calls.
14248 (save-match-data
14249 (let (tags-expanded)
14250 (dolist (x (cdr tags-in-group))
14251 (if (and (member x taggroups-keys)
14252 (not (member x work-already-expanded)))
14253 (setq tags-expanded
14254 (delete-dups
14255 (append
14256 (org-tags-expand x t downcased
14257 work-already-expanded)
14258 tags-expanded)))
14259 (setq tags-expanded
14260 (append (list x) tags-expanded)))
14261 (setq work-already-expanded
14262 (delete-dups
14263 (append tags-expanded
14264 work-already-expanded))))
14265 (setq tags-in-group
14266 (delete-dups (cons (car tags-in-group)
14267 tags-expanded)))))
14268 ;; Filter tag-regexps from tags.
14269 (setq regexp-in-group-escaped
14270 (delq nil (mapcar (lambda (x)
14271 (if (stringp x)
14272 (and (equal "{" (substring x 0 1))
14273 (equal "}" (substring x -1))
14276 tags-in-group))
14277 regexp-in-group
14278 (mapcar (lambda (x)
14279 (substring x 1 -1))
14280 regexp-in-group-escaped)
14281 tags-in-group
14282 (delq nil (mapcar (lambda (x)
14283 (if (stringp x)
14284 (and (not (equal "{" (substring x 0 1)))
14285 (not (equal "}" (substring x -1)))
14288 tags-in-group)))
14289 ;; If single-as-list, do no more in the while-loop.
14290 (if (not single-as-list)
14291 (progn
14292 (when regexp-in-group
14293 (setq regexp-in-group
14294 (concat "\\|"
14295 (mapconcat 'identity regexp-in-group
14296 "\\|"))))
14297 (setq tags-in-group
14298 (concat dir
14299 "{\\<"
14300 (regexp-opt tags-in-group)
14301 "\\>"
14302 regexp-in-group
14303 "}"))
14304 (when (stringp tags-in-group)
14305 (org-add-props tags-in-group '(grouptag t)))
14306 (setq return-match
14307 (replace-match tags-in-group t t return-match)))
14308 (setq tags-in-group
14309 (append regexp-in-group-escaped tags-in-group))))
14310 (setq taggroups-keys (delete tag taggroups-keys))))
14311 ;; Add the regular expressions back into the match-expression again.
14312 (while regexps-in-match
14313 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14314 (pop regexps-in-match)
14315 return-match t t))
14316 (cl-decf count))
14317 (if single-as-list
14318 (if tags-in-group tags-in-group (list return-match))
14319 return-match))
14320 (if single-as-list
14321 (list (if downcased (downcase match) match))
14322 match)))
14324 (defun org-op-to-function (op &optional stringp)
14325 "Turn an operator into the appropriate function."
14326 (setq op
14327 (cond
14328 ((equal op "<" ) '(< string< org-time<))
14329 ((equal op ">" ) '(> org-string> org-time>))
14330 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14331 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14332 ((member op '("=" "==")) '(= string= org-time=))
14333 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14334 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14336 (defun org<> (a b) (not (= a b)))
14337 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14338 (defun org-string>= (a b) (not (string< a b)))
14339 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14340 (defun org-string<> (a b) (not (string= a b)))
14341 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14342 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14343 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14344 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14345 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14346 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14347 (defun org-2ft (s)
14348 "Convert S to a floating point time.
14349 If S is already a number, just return it. If it is a string, parse
14350 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14351 (cond
14352 ((numberp s) s)
14353 ((stringp s)
14354 (condition-case nil
14355 (float-time (apply #'encode-time (org-parse-time-string s)))
14356 (error 0.)))
14357 (t 0.)))
14359 (defun org-time-today ()
14360 "Time in seconds today at 0:00.
14361 Returns the float number of seconds since the beginning of the
14362 epoch to the beginning of today (00:00)."
14363 (float-time (apply 'encode-time
14364 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14366 (defun org-matcher-time (s)
14367 "Interpret a time comparison value."
14368 (save-match-data
14369 (cond
14370 ((string= s "<now>") (float-time))
14371 ((string= s "<today>") (org-time-today))
14372 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14373 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14374 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14375 (+ (org-time-today)
14376 (* (string-to-number (match-string 1 s))
14377 (cdr (assoc (match-string 2 s)
14378 '(("d" . 86400.0) ("w" . 604800.0)
14379 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14380 (t (org-2ft s)))))
14382 (defun org-match-any-p (re list)
14383 "Does re match any element of list?"
14384 (setq list (mapcar (lambda (x) (string-match re x)) list))
14385 (delq nil list))
14387 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14388 (defvar org-tags-overlay (make-overlay 1 1))
14389 (delete-overlay org-tags-overlay)
14391 (defun org-get-local-tags-at (&optional pos)
14392 "Get a list of tags defined in the current headline."
14393 (org-get-tags-at pos 'local))
14395 (defun org-get-local-tags ()
14396 "Get a list of tags defined in the current headline."
14397 (org-get-tags-at nil 'local))
14399 (defun org-get-tags-at (&optional pos local)
14400 "Get a list of all headline tags applicable at POS.
14401 POS defaults to point. If tags are inherited, the list contains
14402 the targets in the same sequence as the headlines appear, i.e.
14403 the tags of the current headline come last.
14404 When LOCAL is non-nil, only return tags from the current headline,
14405 ignore inherited ones."
14406 (interactive)
14407 (if (and org-trust-scanner-tags
14408 (or (not pos) (equal pos (point)))
14409 (not local))
14410 org-scanner-tags
14411 (let (tags ltags lastpos parent)
14412 (save-excursion
14413 (save-restriction
14414 (widen)
14415 (goto-char (or pos (point)))
14416 (save-match-data
14417 (catch 'done
14418 (condition-case nil
14419 (progn
14420 (org-back-to-heading t)
14421 (while (not (equal lastpos (point)))
14422 (setq lastpos (point))
14423 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14424 (setq ltags (org-split-string
14425 (match-string-no-properties 1) ":"))
14426 (when parent
14427 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14428 (setq tags (append
14429 (if parent
14430 (org-remove-uninherited-tags ltags)
14431 ltags)
14432 tags)))
14433 (or org-use-tag-inheritance (throw 'done t))
14434 (when local (throw 'done t))
14435 (or (org-up-heading-safe) (error nil))
14436 (setq parent t)))
14437 (error nil)))))
14438 (if local
14439 tags
14440 (reverse (delete-dups
14441 (reverse (append
14442 (org-remove-uninherited-tags
14443 org-file-tags)
14444 tags)))))))))
14446 (defun org-add-prop-inherited (s)
14447 (add-text-properties 0 (length s) '(inherited t) s)
14450 (defun org-toggle-tag (tag &optional onoff)
14451 "Toggle the tag TAG for the current line.
14452 If ONOFF is `on' or `off', don't toggle but set to this state."
14453 (save-excursion
14454 (org-back-to-heading t)
14455 (let ((current
14456 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14457 (line-end-position) t)
14458 (let ((tags (match-string 1)))
14459 ;; Clear current tags.
14460 (replace-match "")
14461 ;; Reverse the tags list so any new tag is appended to
14462 ;; the current list of tags.
14463 (nreverse (org-split-string tags ":")))))
14464 res)
14465 (pcase onoff
14466 (`off (setq current (delete tag current)))
14467 ((or `on (guard (not (member tag current))))
14468 (setq res t)
14469 (cl-pushnew tag current :test #'equal))
14470 (_ (setq current (delete tag current))))
14471 (end-of-line)
14472 (if current
14473 (progn
14474 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14475 (org-set-tags nil t))
14476 (delete-horizontal-space))
14477 (run-hooks 'org-after-tags-change-hook)
14478 res)))
14480 (defun org--align-tags-here (to-col)
14481 "Align tags on the current headline to TO-COL.
14482 Assume point is on a headline."
14483 (let ((pos (point)))
14484 (beginning-of-line)
14485 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14486 (>= pos (match-beginning 2)))
14487 ;; No tags or point within tags: do not align.
14488 (goto-char pos)
14489 (goto-char (match-beginning 1))
14490 (let ((shift (max (- (if (>= to-col 0) to-col
14491 (- (abs to-col) (string-width (match-string 2))))
14492 (current-column))
14493 1)))
14494 (replace-match (make-string shift ?\s) nil nil nil 1)
14495 ;; Preserve initial position, if possible. In any case, stop
14496 ;; before tags.
14497 (when (< pos (point)) (goto-char pos))))))
14499 (defun org-set-tags-command (&optional arg just-align)
14500 "Call the set-tags command for the current entry."
14501 (interactive "P")
14502 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14503 (org-set-tags arg just-align)
14504 (save-excursion
14505 (unless (and (org-region-active-p)
14506 org-loop-over-headlines-in-active-region)
14507 (org-back-to-heading t))
14508 (org-set-tags arg just-align))))
14510 (defun org-set-tags-to (data)
14511 "Set the tags of the current entry to DATA, replacing the current tags.
14512 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14513 If DATA is nil or the empty string, any tags will be removed."
14514 (interactive "sTags: ")
14515 (setq data
14516 (cond
14517 ((eq data nil) "")
14518 ((equal data "") "")
14519 ((stringp data)
14520 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14521 ":"))
14522 ((listp data)
14523 (concat ":" (mapconcat 'identity data ":") ":"))))
14524 (when data
14525 (save-excursion
14526 (org-back-to-heading t)
14527 (when (let ((case-fold-search nil))
14528 (looking-at org-complex-heading-regexp))
14529 (if (match-end 5)
14530 (progn
14531 (goto-char (match-beginning 5))
14532 (insert data)
14533 (delete-region (point) (point-at-eol))
14534 (org-set-tags nil 'align))
14535 (goto-char (point-at-eol))
14536 (insert " " data)
14537 (org-set-tags nil 'align)))
14538 (beginning-of-line 1)
14539 (when (looking-at ".*?\\([ \t]+\\)$")
14540 (delete-region (match-beginning 1) (match-end 1))))))
14542 (defun org-align-all-tags ()
14543 "Align the tags in all headings."
14544 (interactive)
14545 (save-excursion
14546 (or (ignore-errors (org-back-to-heading t))
14547 (outline-next-heading))
14548 (if (org-at-heading-p)
14549 (org-set-tags t)
14550 (message "No headings"))))
14552 (defvar org-indent-indentation-per-level)
14553 (defun org-set-tags (&optional arg just-align)
14554 "Set the tags for the current headline.
14555 With prefix ARG, realign all tags in headings in the current buffer.
14556 When JUST-ALIGN is non-nil, only align tags."
14557 (interactive "P")
14558 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14559 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14560 'region-start-level
14561 'region))
14562 org-loop-over-headlines-in-active-region)
14563 (org-map-entries
14564 ;; We don't use ARG and JUST-ALIGN here because these args
14565 ;; are not useful when looping over headlines.
14566 #'org-set-tags
14567 org-loop-over-headlines-in-active-region
14569 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14570 (let ((org-setting-tags t))
14571 (if arg
14572 (save-excursion
14573 (goto-char (point-min))
14574 (while (re-search-forward org-outline-regexp-bol nil t)
14575 (org-set-tags nil t)
14576 (end-of-line))
14577 (message "All tags realigned to column %d" org-tags-column))
14578 (let* ((current (org-get-tags-string))
14579 (tags
14580 (if just-align current
14581 ;; Get a new set of tags from the user.
14582 (save-excursion
14583 (let* ((seen)
14584 (table
14585 (setq
14586 org-last-tags-completion-table
14587 ;; Uniquify tags in alists, yet preserve
14588 ;; structure (i.e., keywords).
14589 (delq nil
14590 (mapcar
14591 (lambda (pair)
14592 (let ((head (car pair)))
14593 (cond ((symbolp head) pair)
14594 ((member head seen) nil)
14595 (t (push head seen)
14596 pair))))
14597 (append
14598 (or org-current-tag-alist
14599 (org-get-buffer-tags))
14600 (and
14601 org-complete-tags-always-offer-all-agenda-tags
14602 (org-global-tags-completion-table
14603 (org-agenda-files))))))))
14604 (current-tags (org-split-string current ":"))
14605 (inherited-tags
14606 (nreverse (nthcdr (length current-tags)
14607 (nreverse (org-get-tags-at))))))
14608 (replace-regexp-in-string
14609 "\\([-+&]+\\|,\\)"
14611 (if (or (eq t org-use-fast-tag-selection)
14612 (and org-use-fast-tag-selection
14613 (delq nil (mapcar #'cdr table))))
14614 (org-fast-tag-selection
14615 current-tags inherited-tags table
14616 (and org-fast-tag-selection-include-todo
14617 org-todo-key-alist))
14618 (let ((org-add-colon-after-tag-completion
14619 (< 1 (length table))))
14620 (org-trim
14621 (completing-read
14622 "Tags: "
14623 #'org-tags-completion-function
14624 nil nil current 'org-tags-history))))))))))
14626 (when org-tags-sort-function
14627 (setq tags
14628 (mapconcat
14629 #'identity
14630 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14631 org-tags-sort-function)
14632 ":")))
14634 (if (or (string= ":" tags)
14635 (string= "::" tags))
14636 (setq tags ""))
14637 (if (not (org-string-nw-p tags)) (setq tags "")
14638 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14639 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14641 ;; Insert new tags at the correct column.
14642 (unless (equal current tags)
14643 (save-excursion
14644 (beginning-of-line)
14645 (let ((case-fold-search nil))
14646 (looking-at org-complex-heading-regexp))
14647 ;; Remove current tags, if any.
14648 (when (match-end 5) (replace-match "" nil nil nil 5))
14649 ;; Insert new tags, if any. Otherwise, remove trailing
14650 ;; white spaces.
14651 (end-of-line)
14652 (if (not (equal tags ""))
14653 ;; When text is being inserted on an invisible
14654 ;; region boundary, it can be inadvertently sucked
14655 ;; into invisibility.
14656 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14657 (skip-chars-backward " \t")
14658 (delete-region (point) (line-end-position)))))
14659 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14660 ;; is on.
14661 (unless (equal tags "")
14662 (let* ((level (save-excursion
14663 (beginning-of-line)
14664 (skip-chars-forward "\\*")))
14665 (offset (if (bound-and-true-p org-indent-mode)
14666 (* (1- org-indent-indentation-per-level)
14667 (1- level))
14669 (tags-column
14670 (+ org-tags-column
14671 (if (> org-tags-column 0) (- offset) offset))))
14672 (org--align-tags-here tags-column))))
14673 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14675 (defun org-change-tag-in-region (beg end tag off)
14676 "Add or remove TAG for each entry in the region.
14677 This works in the agenda, and also in an Org buffer."
14678 (interactive
14679 (list (region-beginning) (region-end)
14680 (let ((org-last-tags-completion-table
14681 (if (derived-mode-p 'org-mode)
14682 (org-uniquify
14683 (delq nil (append (org-get-buffer-tags)
14684 (org-global-tags-completion-table))))
14685 (org-global-tags-completion-table))))
14686 (completing-read
14687 "Tag: " 'org-tags-completion-function nil nil nil
14688 'org-tags-history))
14689 (progn
14690 (message "[s]et or [r]emove? ")
14691 (equal (read-char-exclusive) ?r))))
14692 (when (fboundp 'deactivate-mark) (deactivate-mark))
14693 (let ((agendap (equal major-mode 'org-agenda-mode))
14694 l1 l2 m buf pos newhead (cnt 0))
14695 (goto-char end)
14696 (setq l2 (1- (org-current-line)))
14697 (goto-char beg)
14698 (setq l1 (org-current-line))
14699 (cl-loop for l from l1 to l2 do
14700 (org-goto-line l)
14701 (setq m (get-text-property (point) 'org-hd-marker))
14702 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14703 (and agendap m))
14704 (setq buf (if agendap (marker-buffer m) (current-buffer))
14705 pos (if agendap m (point)))
14706 (with-current-buffer buf
14707 (save-excursion
14708 (save-restriction
14709 (goto-char pos)
14710 (setq cnt (1+ cnt))
14711 (org-toggle-tag tag (if off 'off 'on))
14712 (setq newhead (org-get-heading)))))
14713 (and agendap (org-agenda-change-all-lines newhead m))))
14714 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14716 (defun org-tags-completion-function (string _predicate &optional flag)
14717 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14718 (confirm (lambda (x) (stringp (car x)))))
14719 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14720 (setq s1 (match-string 1 string)
14721 s2 (match-string 2 string))
14722 (setq s1 "" s2 string))
14723 (cond
14724 ((eq flag nil)
14725 ;; try completion
14726 (setq rtn (try-completion s2 ctable confirm))
14727 (when (stringp rtn)
14728 (setq rtn
14729 (concat s1 s2 (substring rtn (length s2))
14730 (if (and org-add-colon-after-tag-completion
14731 (assoc rtn ctable))
14732 ":" ""))))
14733 rtn)
14734 ((eq flag t)
14735 ;; all-completions
14736 (all-completions s2 ctable confirm))
14737 ((eq flag 'lambda)
14738 ;; exact match?
14739 (assoc s2 ctable)))))
14741 (defun org-fast-tag-insert (kwd tags face &optional end)
14742 "Insert KDW, and the TAGS, the latter with face FACE.
14743 Also insert END."
14744 (insert (format "%-12s" (concat kwd ":"))
14745 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14746 (or end "")))
14748 (defun org-fast-tag-show-exit (flag)
14749 (save-excursion
14750 (org-goto-line 3)
14751 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14752 (replace-match ""))
14753 (when flag
14754 (end-of-line 1)
14755 (org-move-to-column (- (window-width) 19) t)
14756 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14758 (defun org-set-current-tags-overlay (current prefix)
14759 "Add an overlay to CURRENT tag with PREFIX."
14760 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14761 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14762 (org-overlay-display org-tags-overlay (concat prefix s))))
14764 (defvar org-last-tag-selection-key nil)
14765 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14766 "Fast tag selection with single keys.
14767 CURRENT is the current list of tags in the headline, INHERITED is the
14768 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14769 possibly with grouping information. TODO-TABLE is a similar table with
14770 TODO keywords, should these have keys assigned to them.
14771 If the keys are nil, a-z are automatically assigned.
14772 Returns the new tags string, or nil to not change the current settings."
14773 (let* ((fulltable (append table todo-table))
14774 (maxlen (apply 'max (mapcar
14775 (lambda (x)
14776 (if (stringp (car x)) (string-width (car x)) 0))
14777 fulltable)))
14778 (buf (current-buffer))
14779 (expert (eq org-fast-tag-selection-single-key 'expert))
14780 (buffer-tags nil)
14781 (fwidth (+ maxlen 3 1 3))
14782 (ncol (/ (- (window-width) 4) fwidth))
14783 (i-face 'org-done)
14784 (c-face 'org-todo)
14785 tg cnt e c char c1 c2 ntable tbl rtn
14786 ov-start ov-end ov-prefix
14787 (exit-after-next org-fast-tag-selection-single-key)
14788 (done-keywords org-done-keywords)
14789 groups ingroup intaggroup)
14790 (save-excursion
14791 (beginning-of-line 1)
14792 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14793 (setq ov-start (match-beginning 1)
14794 ov-end (match-end 1)
14795 ov-prefix "")
14796 (setq ov-start (1- (point-at-eol))
14797 ov-end (1+ ov-start))
14798 (skip-chars-forward "^\n\r")
14799 (setq ov-prefix
14800 (concat
14801 (buffer-substring (1- (point)) (point))
14802 (if (> (current-column) org-tags-column)
14804 (make-string (- org-tags-column (current-column)) ?\ ))))))
14805 (move-overlay org-tags-overlay ov-start ov-end)
14806 (save-window-excursion
14807 (if expert
14808 (set-buffer (get-buffer-create " *Org tags*"))
14809 (delete-other-windows)
14810 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14811 (org-switch-to-buffer-other-window " *Org tags*"))
14812 (erase-buffer)
14813 (setq-local org-done-keywords done-keywords)
14814 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14815 (org-fast-tag-insert "Current" current c-face "\n\n")
14816 (org-fast-tag-show-exit exit-after-next)
14817 (org-set-current-tags-overlay current ov-prefix)
14818 (setq tbl fulltable char ?a cnt 0)
14819 (while (setq e (pop tbl))
14820 (cond
14821 ((eq (car e) :startgroup)
14822 (push '() groups) (setq ingroup t)
14823 (unless (zerop cnt)
14824 (setq cnt 0)
14825 (insert "\n"))
14826 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14827 ((eq (car e) :endgroup)
14828 (setq ingroup nil cnt 0)
14829 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14830 ((eq (car e) :startgrouptag)
14831 (setq intaggroup t)
14832 (unless (zerop cnt)
14833 (setq cnt 0)
14834 (insert "\n"))
14835 (insert "[ "))
14836 ((eq (car e) :endgrouptag)
14837 (setq intaggroup nil cnt 0)
14838 (insert "]\n"))
14839 ((equal e '(:newline))
14840 (unless (zerop cnt)
14841 (setq cnt 0)
14842 (insert "\n")
14843 (setq e (car tbl))
14844 (while (equal (car tbl) '(:newline))
14845 (insert "\n")
14846 (setq tbl (cdr tbl)))))
14847 ((equal e '(:grouptags)) (insert " : "))
14849 (setq tg (copy-sequence (car e)) c2 nil)
14850 (if (cdr e)
14851 (setq c (cdr e))
14852 ;; automatically assign a character.
14853 (setq c1 (string-to-char
14854 (downcase (substring
14855 tg (if (= (string-to-char tg) ?@) 1 0)))))
14856 (if (or (rassoc c1 ntable) (rassoc c1 table))
14857 (while (or (rassoc char ntable) (rassoc char table))
14858 (setq char (1+ char)))
14859 (setq c2 c1))
14860 (setq c (or c2 char)))
14861 (when ingroup (push tg (car groups)))
14862 (setq tg (org-add-props tg nil 'face
14863 (cond
14864 ((not (assoc tg table))
14865 (org-get-todo-face tg))
14866 ((member tg current) c-face)
14867 ((member tg inherited) i-face))))
14868 (when (equal (caar tbl) :grouptags)
14869 (org-add-props tg nil 'face 'org-tag-group))
14870 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14871 (insert "[" c "] " tg (make-string
14872 (- fwidth 4 (length tg)) ?\ ))
14873 (push (cons tg c) ntable)
14874 (when (= (cl-incf cnt) ncol)
14875 (insert "\n")
14876 (when (or ingroup intaggroup) (insert " "))
14877 (setq cnt 0)))))
14878 (setq ntable (nreverse ntable))
14879 (insert "\n")
14880 (goto-char (point-min))
14881 (unless expert (org-fit-window-to-buffer))
14882 (setq rtn
14883 (catch 'exit
14884 (while t
14885 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14886 (if (not groups) "no " "")
14887 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14888 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14889 (setq org-last-tag-selection-key c)
14890 (cond
14891 ((= c ?\r) (throw 'exit t))
14892 ((= c ?!)
14893 (setq groups (not groups))
14894 (goto-char (point-min))
14895 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14896 ((= c ?\C-c)
14897 (if (not expert)
14898 (org-fast-tag-show-exit
14899 (setq exit-after-next (not exit-after-next)))
14900 (setq expert nil)
14901 (delete-other-windows)
14902 (set-window-buffer (split-window-vertically) " *Org tags*")
14903 (org-switch-to-buffer-other-window " *Org tags*")
14904 (org-fit-window-to-buffer)))
14905 ((or (= c ?\C-g)
14906 (and (= c ?q) (not (rassoc c ntable))))
14907 (delete-overlay org-tags-overlay)
14908 (setq quit-flag t))
14909 ((= c ?\ )
14910 (setq current nil)
14911 (when exit-after-next (setq exit-after-next 'now)))
14912 ((= c ?\t)
14913 (condition-case nil
14914 (setq tg (completing-read
14915 "Tag: "
14916 (or buffer-tags
14917 (with-current-buffer buf
14918 (setq buffer-tags
14919 (org-get-buffer-tags))))))
14920 (quit (setq tg "")))
14921 (when (string-match "\\S-" tg)
14922 (cl-pushnew (list tg) buffer-tags :test #'equal)
14923 (if (member tg current)
14924 (setq current (delete tg current))
14925 (push tg current)))
14926 (when exit-after-next (setq exit-after-next 'now)))
14927 ((setq e (rassoc c todo-table) tg (car e))
14928 (with-current-buffer buf
14929 (save-excursion (org-todo tg)))
14930 (when exit-after-next (setq exit-after-next 'now)))
14931 ((setq e (rassoc c ntable) tg (car e))
14932 (if (member tg current)
14933 (setq current (delete tg current))
14934 (cl-loop for g in groups do
14935 (when (member tg g)
14936 (dolist (x g) (setq current (delete x current)))))
14937 (push tg current))
14938 (when exit-after-next (setq exit-after-next 'now))))
14940 ;; Create a sorted list
14941 (setq current
14942 (sort current
14943 (lambda (a b)
14944 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14945 (when (eq exit-after-next 'now) (throw 'exit t))
14946 (goto-char (point-min))
14947 (beginning-of-line 2)
14948 (delete-region (point) (point-at-eol))
14949 (org-fast-tag-insert "Current" current c-face)
14950 (org-set-current-tags-overlay current ov-prefix)
14951 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14952 (setq tg (match-string 1))
14953 (add-text-properties
14954 (match-beginning 1) (match-end 1)
14955 (list 'face
14956 (cond
14957 ((member tg current) c-face)
14958 ((member tg inherited) i-face)
14959 (t (get-text-property (match-beginning 1) 'face))))))
14960 (goto-char (point-min)))))
14961 (delete-overlay org-tags-overlay)
14962 (if rtn
14963 (mapconcat 'identity current ":")
14964 nil))))
14966 (defun org-get-tags-string ()
14967 "Get the TAGS string in the current headline."
14968 (unless (org-at-heading-p t)
14969 (user-error "Not on a heading"))
14970 (save-excursion
14971 (beginning-of-line 1)
14972 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14973 (match-string-no-properties 1)
14974 "")))
14976 (defun org-get-tags ()
14977 "Get the list of tags specified in the current headline."
14978 (org-split-string (org-get-tags-string) ":"))
14980 (defun org-get-buffer-tags ()
14981 "Get a table of all tags used in the buffer, for completion."
14982 (org-with-wide-buffer
14983 (goto-char (point-min))
14984 (let ((tag-re (concat org-outline-regexp-bol
14985 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14986 tags)
14987 (while (re-search-forward tag-re nil t)
14988 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14989 (push tag tags)))
14990 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14992 ;;;; The mapping API
14994 (defvar org-agenda-skip-comment-trees)
14995 (defvar org-agenda-skip-function)
14996 (defun org-map-entries (func &optional match scope &rest skip)
14997 "Call FUNC at each headline selected by MATCH in SCOPE.
14999 FUNC is a function or a lisp form. The function will be called without
15000 arguments, with the cursor positioned at the beginning of the headline.
15001 The return values of all calls to the function will be collected and
15002 returned as a list.
15004 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15005 does not need to preserve point. After evaluation, the cursor will be
15006 moved to the end of the line (presumably of the headline of the
15007 processed entry) and search continues from there. Under some
15008 circumstances, this may not produce the wanted results. For example,
15009 if you have removed (e.g. archived) the current (sub)tree it could
15010 mean that the next entry will be skipped entirely. In such cases, you
15011 can specify the position from where search should continue by making
15012 FUNC set the variable `org-map-continue-from' to the desired buffer
15013 position.
15015 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15016 Only headlines that are matched by this query will be considered during
15017 the iteration. When MATCH is nil or t, all headlines will be
15018 visited by the iteration.
15020 SCOPE determines the scope of this command. It can be any of:
15022 nil The current buffer, respecting the restriction if any
15023 tree The subtree started with the entry at point
15024 region The entries within the active region, if any
15025 region-start-level
15026 The entries within the active region, but only those at
15027 the same level than the first one.
15028 file The current buffer, without restriction
15029 file-with-archives
15030 The current buffer, and any archives associated with it
15031 agenda All agenda files
15032 agenda-with-archives
15033 All agenda files with any archive files associated with them
15034 \(file1 file2 ...)
15035 If this is a list, all files in the list will be scanned
15037 The remaining args are treated as settings for the skipping facilities of
15038 the scanner. The following items can be given here:
15040 archive skip trees with the archive tag
15041 comment skip trees with the COMMENT keyword
15042 function or Emacs Lisp form:
15043 will be used as value for `org-agenda-skip-function', so
15044 whenever the function returns a position, FUNC will not be
15045 called for that entry and search will continue from the
15046 position returned
15048 If your function needs to retrieve the tags including inherited tags
15049 at the *current* entry, you can use the value of the variable
15050 `org-scanner-tags' which will be much faster than getting the value
15051 with `org-get-tags-at'. If your function gets properties with
15052 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15053 to t around the call to `org-entry-properties' to get the same speedup.
15054 Note that if your function moves around to retrieve tags and properties at
15055 a *different* entry, you cannot use these techniques."
15056 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15057 (not (org-region-active-p)))
15058 (let* ((org-agenda-archives-mode nil) ; just to make sure
15059 (org-agenda-skip-archived-trees (memq 'archive skip))
15060 (org-agenda-skip-comment-trees (memq 'comment skip))
15061 (org-agenda-skip-function
15062 (car (org-delete-all '(comment archive) skip)))
15063 (org-tags-match-list-sublevels t)
15064 (start-level (eq scope 'region-start-level))
15065 matcher res
15066 org-todo-keywords-for-agenda
15067 org-done-keywords-for-agenda
15068 org-todo-keyword-alist-for-agenda
15069 org-tag-alist-for-agenda
15070 org--matcher-tags-todo-only)
15072 (cond
15073 ((eq match t) (setq matcher t))
15074 ((eq match nil) (setq matcher t))
15075 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15077 (save-excursion
15078 (save-restriction
15079 (cond ((eq scope 'tree)
15080 (org-back-to-heading t)
15081 (org-narrow-to-subtree)
15082 (setq scope nil))
15083 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15084 (org-region-active-p))
15085 ;; If needed, set start-level to a string like "2"
15086 (when start-level
15087 (save-excursion
15088 (goto-char (region-beginning))
15089 (unless (org-at-heading-p) (outline-next-heading))
15090 (setq start-level (org-current-level))))
15091 (narrow-to-region (region-beginning)
15092 (save-excursion
15093 (goto-char (region-end))
15094 (unless (and (bolp) (org-at-heading-p))
15095 (outline-next-heading))
15096 (point)))
15097 (setq scope nil)))
15099 (if (not scope)
15100 (progn
15101 (org-agenda-prepare-buffers
15102 (and buffer-file-name (list buffer-file-name)))
15103 (setq res
15104 (org-scan-tags
15105 func matcher org--matcher-tags-todo-only start-level)))
15106 ;; Get the right scope
15107 (cond
15108 ((and scope (listp scope) (symbolp (car scope)))
15109 (setq scope (eval scope)))
15110 ((eq scope 'agenda)
15111 (setq scope (org-agenda-files t)))
15112 ((eq scope 'agenda-with-archives)
15113 (setq scope (org-agenda-files t))
15114 (setq scope (org-add-archive-files scope)))
15115 ((eq scope 'file)
15116 (setq scope (and buffer-file-name (list buffer-file-name))))
15117 ((eq scope 'file-with-archives)
15118 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15119 (org-agenda-prepare-buffers scope)
15120 (dolist (file scope)
15121 (with-current-buffer (org-find-base-buffer-visiting file)
15122 (org-with-wide-buffer
15123 (goto-char (point-min))
15124 (setq res
15125 (append
15127 (org-scan-tags
15128 func matcher org--matcher-tags-todo-only)))))))))
15129 res)))
15131 ;;; Properties API
15133 (defconst org-special-properties
15134 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15135 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15136 "The special properties valid in Org mode.
15137 These are properties that are not defined in the property drawer,
15138 but in some other way.")
15140 (defconst org-default-properties
15141 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15142 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15143 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15144 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15145 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15146 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15147 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15148 "Some properties that are used by Org mode for various purposes.
15149 Being in this list makes sure that they are offered for completion.")
15151 (defun org--valid-property-p (property)
15152 "Non nil when string PROPERTY is a valid property name."
15153 (not
15154 (or (equal property "")
15155 (string-match-p "\\s-" property))))
15157 (defun org--update-property-plist (key val props)
15158 "Associate KEY to VAL in alist PROPS.
15159 Modifications are made by side-effect. Return new alist."
15160 (let* ((appending (string= (substring key -1) "+"))
15161 (key (if appending (substring key 0 -1) key))
15162 (old (assoc-string key props t)))
15163 (if (not old) (cons (cons key val) props)
15164 (setcdr old (if appending (concat (cdr old) " " val) val))
15165 props)))
15167 (defun org-get-property-block (&optional beg force)
15168 "Return the (beg . end) range of the body of the property drawer.
15169 BEG is the beginning of the current subtree, or of the part
15170 before the first headline. If it is not given, it will be found.
15171 If the drawer does not exist, create it if FORCE is non-nil, or
15172 return nil."
15173 (org-with-wide-buffer
15174 (when beg (goto-char beg))
15175 (unless (org-before-first-heading-p)
15176 (let ((beg (cond (beg)
15177 ((or (not (featurep 'org-inlinetask))
15178 (org-inlinetask-in-task-p))
15179 (org-back-to-heading t))
15180 (t (org-with-limited-levels (org-back-to-heading t))))))
15181 (forward-line)
15182 (when (looking-at-p org-planning-line-re) (forward-line))
15183 (cond ((looking-at org-property-drawer-re)
15184 (forward-line)
15185 (cons (point) (progn (goto-char (match-end 0))
15186 (line-beginning-position))))
15187 (force
15188 (goto-char beg)
15189 (org-insert-property-drawer)
15190 (let ((pos (save-excursion (search-forward ":END:")
15191 (line-beginning-position))))
15192 (cons pos pos))))))))
15194 (defun org-at-property-p ()
15195 "Non-nil when point is inside a property drawer.
15196 See `org-property-re' for match data, if applicable."
15197 (save-excursion
15198 (beginning-of-line)
15199 (and (looking-at org-property-re)
15200 (let ((property-drawer (save-match-data (org-get-property-block))))
15201 (and property-drawer
15202 (>= (point) (car property-drawer))
15203 (< (point) (cdr property-drawer)))))))
15205 (defun org-property-action ()
15206 "Do an action on properties."
15207 (interactive)
15208 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15209 (let ((c (read-char-exclusive)))
15210 (cl-case c
15211 (?s (call-interactively #'org-set-property))
15212 (?d (call-interactively #'org-delete-property))
15213 (?D (call-interactively #'org-delete-property-globally))
15214 (?c (call-interactively #'org-compute-property-at-point))
15215 (otherwise (user-error "No such property action %c" c)))))
15217 (defun org-inc-effort ()
15218 "Increment the value of the effort property in the current entry."
15219 (interactive)
15220 (org-set-effort nil t))
15222 (defvar org-clock-effort) ; Defined in org-clock.el.
15223 (defvar org-clock-current-task) ; Defined in org-clock.el.
15224 (defun org-set-effort (&optional value increment)
15225 "Set the effort property of the current entry.
15226 With numerical prefix arg, use the nth allowed value, 0 stands for the
15227 10th allowed value.
15229 When INCREMENT is non-nil, set the property to the next allowed value."
15230 (interactive "P")
15231 (when (equal value 0) (setq value 10))
15232 (let* ((completion-ignore-case t)
15233 (prop org-effort-property)
15234 (cur (org-entry-get nil prop))
15235 (allowed (org-property-get-allowed-values nil prop 'table))
15236 (existing (mapcar 'list (org-property-values prop)))
15237 (heading (nth 4 (org-heading-components)))
15239 (val (cond
15240 ((stringp value) value)
15241 ((and allowed (integerp value))
15242 (or (car (nth (1- value) allowed))
15243 (car (org-last allowed))))
15244 ((and allowed increment)
15245 (or (cl-caadr (member (list cur) allowed))
15246 (user-error "Allowed effort values are not set")))
15247 (allowed
15248 (message "Select 1-9,0, [RET%s]: %s"
15249 (if cur (concat "=" cur) "")
15250 (mapconcat 'car allowed " "))
15251 (setq rpl (read-char-exclusive))
15252 (if (equal rpl ?\r)
15254 (setq rpl (- rpl ?0))
15255 (when (equal rpl 0) (setq rpl 10))
15256 (if (and (> rpl 0) (<= rpl (length allowed)))
15257 (car (nth (1- rpl) allowed))
15258 (org-completing-read "Effort: " allowed nil))))
15260 (org-completing-read
15261 (concat "Effort" (and cur (string-match "\\S-" cur)
15262 (concat " [" cur "]"))
15263 ": ")
15264 existing nil nil "" nil cur)))))
15265 (unless (equal (org-entry-get nil prop) val)
15266 (org-entry-put nil prop val))
15267 (org-refresh-property
15268 '((effort . identity)
15269 (effort-minutes . org-duration-to-minutes))
15270 val)
15271 (when (equal heading (bound-and-true-p org-clock-current-task))
15272 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15273 (org-clock-update-mode-line))
15274 (message "%s is now %s" prop val)))
15276 (defun org-entry-properties (&optional pom which)
15277 "Get all properties of the current entry.
15279 When POM is a buffer position, get all properties from the entry
15280 there instead.
15282 This includes the TODO keyword, the tags, time strings for
15283 deadline, scheduled, and clocking, and any additional properties
15284 defined in the entry.
15286 If WHICH is nil or `all', get all properties. If WHICH is
15287 `special' or `standard', only get that subclass. If WHICH is
15288 a string, only get that property.
15290 Return value is an alist. Keys are properties, as upcased
15291 strings."
15292 (org-with-point-at pom
15293 (when (and (derived-mode-p 'org-mode)
15294 (ignore-errors (org-back-to-heading t)))
15295 (catch 'exit
15296 (let* ((beg (point))
15297 (specific (and (stringp which) (upcase which)))
15298 (which (cond ((not specific) which)
15299 ((member specific org-special-properties) 'special)
15300 (t 'standard)))
15301 props)
15302 ;; Get the special properties, like TODO and TAGS.
15303 (when (memq which '(nil all special))
15304 (when (or (not specific) (string= specific "CLOCKSUM"))
15305 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15306 (when clocksum
15307 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15308 props)))
15309 (when specific (throw 'exit props)))
15310 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15311 (let ((clocksumt (get-text-property (point)
15312 :org-clock-minutes-today)))
15313 (when clocksumt
15314 (push (cons "CLOCKSUM_T"
15315 (org-duration-from-minutes clocksumt))
15316 props)))
15317 (when specific (throw 'exit props)))
15318 (when (or (not specific) (string= specific "ITEM"))
15319 (let ((case-fold-search nil))
15320 (when (looking-at org-complex-heading-regexp)
15321 (push (cons "ITEM"
15322 (let ((title (match-string-no-properties 4)))
15323 (if (org-string-nw-p title)
15324 (org-remove-tabs title)
15325 "")))
15326 props)))
15327 (when specific (throw 'exit props)))
15328 (when (or (not specific) (string= specific "TODO"))
15329 (let ((case-fold-search nil))
15330 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15331 (push (cons "TODO" (match-string-no-properties 2)) props)))
15332 (when specific (throw 'exit props)))
15333 (when (or (not specific) (string= specific "PRIORITY"))
15334 (push (cons "PRIORITY"
15335 (if (looking-at org-priority-regexp)
15336 (match-string-no-properties 2)
15337 (char-to-string org-default-priority)))
15338 props)
15339 (when specific (throw 'exit props)))
15340 (when (or (not specific) (string= specific "FILE"))
15341 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15342 props)
15343 (when specific (throw 'exit props)))
15344 (when (or (not specific) (string= specific "TAGS"))
15345 (let ((value (org-string-nw-p (org-get-tags-string))))
15346 (when value (push (cons "TAGS" value) props)))
15347 (when specific (throw 'exit props)))
15348 (when (or (not specific) (string= specific "ALLTAGS"))
15349 (let ((value (org-get-tags-at)))
15350 (when value
15351 (push (cons "ALLTAGS"
15352 (format ":%s:" (mapconcat #'identity value ":")))
15353 props)))
15354 (when specific (throw 'exit props)))
15355 (when (or (not specific) (string= specific "BLOCKED"))
15356 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15357 (when specific (throw 'exit props)))
15358 (when (or (not specific)
15359 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15360 (forward-line)
15361 (when (looking-at-p org-planning-line-re)
15362 (end-of-line)
15363 (let ((bol (line-beginning-position))
15364 ;; Backward compatibility: time keywords used to
15365 ;; be configurable (before 8.3). Make sure we
15366 ;; get the correct keyword.
15367 (key-assoc `(("CLOSED" . ,org-closed-string)
15368 ("DEADLINE" . ,org-deadline-string)
15369 ("SCHEDULED" . ,org-scheduled-string))))
15370 (dolist (pair (if specific (list (assoc specific key-assoc))
15371 key-assoc))
15372 (save-excursion
15373 (when (search-backward (cdr pair) bol t)
15374 (goto-char (match-end 0))
15375 (skip-chars-forward " \t")
15376 (and (looking-at org-ts-regexp-both)
15377 (push (cons (car pair)
15378 (match-string-no-properties 0))
15379 props)))))))
15380 (when specific (throw 'exit props)))
15381 (when (or (not specific)
15382 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15383 (let ((find-ts
15384 (lambda (end ts)
15385 ;; Fix next time-stamp before END. TS is the
15386 ;; list of time-stamps found so far.
15387 (let ((ts ts)
15388 (regexp (cond
15389 ((string= specific "TIMESTAMP")
15390 org-ts-regexp)
15391 ((string= specific "TIMESTAMP_IA")
15392 org-ts-regexp-inactive)
15393 ((assoc "TIMESTAMP_IA" ts)
15394 org-ts-regexp)
15395 ((assoc "TIMESTAMP" ts)
15396 org-ts-regexp-inactive)
15397 (t org-ts-regexp-both))))
15398 (catch 'next
15399 (while (re-search-forward regexp end t)
15400 (backward-char)
15401 (let ((object (org-element-context)))
15402 ;; Accept to match timestamps in node
15403 ;; properties, too.
15404 (when (memq (org-element-type object)
15405 '(node-property timestamp))
15406 (let ((type
15407 (org-element-property :type object)))
15408 (cond
15409 ((and (memq type '(active active-range))
15410 (not (equal specific "TIMESTAMP_IA")))
15411 (unless (assoc "TIMESTAMP" ts)
15412 (push (cons "TIMESTAMP"
15413 (org-element-property
15414 :raw-value object))
15416 (when specific (throw 'exit ts))))
15417 ((and (memq type '(inactive inactive-range))
15418 (not (string= specific "TIMESTAMP")))
15419 (unless (assoc "TIMESTAMP_IA" ts)
15420 (push (cons "TIMESTAMP_IA"
15421 (org-element-property
15422 :raw-value object))
15424 (when specific (throw 'exit ts))))))
15425 ;; Both timestamp types are found,
15426 ;; move to next part.
15427 (when (= (length ts) 2) (throw 'next ts)))))
15428 ts)))))
15429 (goto-char beg)
15430 ;; First look for timestamps within headline.
15431 (let ((ts (funcall find-ts (line-end-position) nil)))
15432 (if (= (length ts) 2) (setq props (nconc ts props))
15433 ;; Then find timestamps in the section, skipping
15434 ;; planning line.
15435 (let ((end (save-excursion (outline-next-heading))))
15436 (forward-line)
15437 (when (looking-at-p org-planning-line-re) (forward-line))
15438 (setq props (nconc (funcall find-ts end ts) props))))))))
15439 ;; Get the standard properties, like :PROP:.
15440 (when (memq which '(nil all standard))
15441 ;; If we are looking after a specific property, delegate
15442 ;; to `org-entry-get', which is faster. However, make an
15443 ;; exception for "CATEGORY", since it can be also set
15444 ;; through keywords (i.e. #+CATEGORY).
15445 (if (and specific (not (equal specific "CATEGORY")))
15446 (let ((value (org-entry-get beg specific nil t)))
15447 (throw 'exit (and value (list (cons specific value)))))
15448 (let ((range (org-get-property-block beg)))
15449 (when range
15450 (let ((end (cdr range)) seen-base)
15451 (goto-char (car range))
15452 ;; Unlike to `org--update-property-plist', we
15453 ;; handle the case where base values is found
15454 ;; after its extension. We also forbid standard
15455 ;; properties to be named as special properties.
15456 (while (re-search-forward org-property-re end t)
15457 (let* ((key (upcase (match-string-no-properties 2)))
15458 (extendp (string-match-p "\\+\\'" key))
15459 (key-base (if extendp (substring key 0 -1) key))
15460 (value (match-string-no-properties 3)))
15461 (cond
15462 ((member-ignore-case key-base org-special-properties))
15463 (extendp
15464 (setq props
15465 (org--update-property-plist key value props)))
15466 ((member key seen-base))
15467 (t (push key seen-base)
15468 (let ((p (assoc-string key props t)))
15469 (if p (setcdr p (concat value " " (cdr p)))
15470 (push (cons key value) props))))))))))))
15471 (unless (assoc "CATEGORY" props)
15472 (push (cons "CATEGORY" (org-get-category beg)) props)
15473 (when (string= specific "CATEGORY") (throw 'exit props)))
15474 ;; Return value.
15475 props)))))
15477 (defun org--property-local-values (property literal-nil)
15478 "Return value for PROPERTY in current entry.
15479 Value is a list whose car is the base value for PROPERTY and cdr
15480 a list of accumulated values. Return nil if neither is found in
15481 the entry. Also return nil when PROPERTY is set to \"nil\",
15482 unless LITERAL-NIL is non-nil."
15483 (let ((range (org-get-property-block)))
15484 (when range
15485 (goto-char (car range))
15486 (let* ((case-fold-search t)
15487 (end (cdr range))
15488 (value
15489 ;; Base value.
15490 (save-excursion
15491 (let ((v (and (re-search-forward
15492 (org-re-property property nil t) end t)
15493 (match-string-no-properties 3))))
15494 (list (if literal-nil v (org-not-nil v)))))))
15495 ;; Find additional values.
15496 (let* ((property+ (org-re-property (concat property "+") nil t)))
15497 (while (re-search-forward property+ end t)
15498 (push (match-string-no-properties 3) value)))
15499 ;; Return final values.
15500 (and (not (equal value '(nil))) (nreverse value))))))
15502 (defun org--property-global-value (property literal-nil)
15503 "Return value for PROPERTY in current buffer.
15504 Return value is a string. Return nil if property is not set
15505 globally. Also return nil when PROPERTY is set to \"nil\",
15506 unless LITERAL-NIL is non-nil."
15507 (let ((global
15508 (cdr (or (assoc-string property org-file-properties t)
15509 (assoc-string property org-global-properties t)
15510 (assoc-string property org-global-properties-fixed t)))))
15511 (if literal-nil global (org-not-nil global))))
15513 (defun org-entry-get (pom property &optional inherit literal-nil)
15514 "Get value of PROPERTY for entry or content at point-or-marker POM.
15516 If INHERIT is non-nil and the entry does not have the property,
15517 then also check higher levels of the hierarchy. If INHERIT is
15518 the symbol `selective', use inheritance only if the setting in
15519 `org-use-property-inheritance' selects PROPERTY for inheritance.
15521 If the property is present but empty, the return value is the
15522 empty string. If the property is not present at all, nil is
15523 returned. In any other case, return the value as a string.
15524 Search is case-insensitive.
15526 If LITERAL-NIL is set, return the string value \"nil\" as
15527 a string, do not interpret it as the list atom nil. This is used
15528 for inheritance when a \"nil\" value can supersede a non-nil
15529 value higher up the hierarchy."
15530 (org-with-point-at pom
15531 (cond
15532 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15533 ;; We need a special property. Use `org-entry-properties' to
15534 ;; retrieve it, but specify the wanted property.
15535 (cdr (assoc-string property (org-entry-properties nil property))))
15536 ((and inherit
15537 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15538 (org-entry-get-with-inheritance property literal-nil))
15540 (let* ((local (org--property-local-values property literal-nil))
15541 (value (and local (mapconcat #'identity (delq nil local) " "))))
15542 (if literal-nil value (org-not-nil value)))))))
15544 (defun org-property-or-variable-value (var &optional inherit)
15545 "Check if there is a property fixing the value of VAR.
15546 If yes, return this value. If not, return the current value of the variable."
15547 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15548 (if (and prop (stringp prop) (string-match "\\S-" prop))
15549 (read prop)
15550 (symbol-value var))))
15552 (defun org-entry-delete (pom property)
15553 "Delete PROPERTY from entry at point-or-marker POM.
15554 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15555 non-nil when a property was removed."
15556 (org-with-point-at pom
15557 (pcase (org-get-property-block)
15558 (`(,begin . ,origin)
15559 (let* ((end (copy-marker origin))
15560 (re (org-re-property
15561 (concat (regexp-quote property) "\\+?") t t)))
15562 (goto-char begin)
15563 (while (re-search-forward re end t)
15564 (delete-region (match-beginning 0) (line-beginning-position 2)))
15565 ;; If drawer is empty, remove it altogether.
15566 (when (= begin end)
15567 (delete-region (line-beginning-position 0)
15568 (line-beginning-position 2)))
15569 ;; Return non-nil if some property was removed.
15570 (prog1 (/= end origin) (set-marker end nil))))
15571 (_ nil))))
15573 ;; Multi-values properties are properties that contain multiple values
15574 ;; These values are assumed to be single words, separated by whitespace.
15575 (defun org-entry-add-to-multivalued-property (pom property value)
15576 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15577 (let* ((old (org-entry-get pom property))
15578 (values (and old (split-string old))))
15579 (setq value (org-entry-protect-space value))
15580 (unless (member value values)
15581 (setq values (append values (list value)))
15582 (org-entry-put pom property (mapconcat #'identity values " ")))))
15584 (defun org-entry-remove-from-multivalued-property (pom property value)
15585 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15586 (let* ((old (org-entry-get pom property))
15587 (values (and old (split-string old))))
15588 (setq value (org-entry-protect-space value))
15589 (when (member value values)
15590 (setq values (delete value values))
15591 (org-entry-put pom property (mapconcat #'identity values " ")))))
15593 (defun org-entry-member-in-multivalued-property (pom property value)
15594 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15595 (let* ((old (org-entry-get pom property))
15596 (values (and old (split-string old))))
15597 (setq value (org-entry-protect-space value))
15598 (member value values)))
15600 (defun org-entry-get-multivalued-property (pom property)
15601 "Return a list of values in a multivalued property."
15602 (let* ((value (org-entry-get pom property))
15603 (values (and value (split-string value))))
15604 (mapcar #'org-entry-restore-space values)))
15606 (defun org-entry-put-multivalued-property (pom property &rest values)
15607 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15608 VALUES should be a list of strings. Spaces will be protected."
15609 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15610 (let* ((value (org-entry-get pom property))
15611 (values (and value (split-string value))))
15612 (mapcar #'org-entry-restore-space values)))
15614 (defun org-entry-protect-space (s)
15615 "Protect spaces and newline in string S."
15616 (while (string-match " " s)
15617 (setq s (replace-match "%20" t t s)))
15618 (while (string-match "\n" s)
15619 (setq s (replace-match "%0A" t t s)))
15622 (defun org-entry-restore-space (s)
15623 "Restore spaces and newline in string S."
15624 (while (string-match "%20" s)
15625 (setq s (replace-match " " t t s)))
15626 (while (string-match "%0A" s)
15627 (setq s (replace-match "\n" t t s)))
15630 (defvar org-entry-property-inherited-from (make-marker)
15631 "Marker pointing to the entry from where a property was inherited.
15632 Each call to `org-entry-get-with-inheritance' will set this marker to the
15633 location of the entry where the inheritance search matched. If there was
15634 no match, the marker will point nowhere.
15635 Note that also `org-entry-get' calls this function, if the INHERIT flag
15636 is set.")
15638 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15639 "Get PROPERTY of entry or content at point, search higher levels if needed.
15640 The search will stop at the first ancestor which has the property defined.
15641 If the value found is \"nil\", return nil to show that the property
15642 should be considered as undefined (this is the meaning of nil here).
15643 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15644 (move-marker org-entry-property-inherited-from nil)
15645 (org-with-wide-buffer
15646 (let (value)
15647 (catch 'exit
15648 (while t
15649 (let ((v (org--property-local-values property literal-nil)))
15650 (when v
15651 (setq value
15652 (concat (mapconcat #'identity (delq nil v) " ")
15653 (and value " ")
15654 value)))
15655 (cond
15656 ((car v)
15657 (org-back-to-heading t)
15658 (move-marker org-entry-property-inherited-from (point))
15659 (throw 'exit nil))
15660 ((org-up-heading-safe))
15662 (let ((global (org--property-global-value property literal-nil)))
15663 (cond ((not global))
15664 (value (setq value (concat global " " value)))
15665 (t (setq value global))))
15666 (throw 'exit nil))))))
15667 (if literal-nil value (org-not-nil value)))))
15669 (defvar org-property-changed-functions nil
15670 "Hook called when the value of a property has changed.
15671 Each hook function should accept two arguments, the name of the property
15672 and the new value.")
15674 (defun org-entry-put (pom property value)
15675 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15677 If the value is nil, it is converted to the empty string. If it
15678 is not a string, an error is raised. Also raise an error on
15679 invalid property names.
15681 PROPERTY can be any regular property (see
15682 `org-special-properties'). It can also be \"TODO\",
15683 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15685 For the last two properties, VALUE may have any of the special
15686 values \"earlier\" and \"later\". The function then increases or
15687 decreases scheduled or deadline date by one day."
15688 (cond ((null value) (setq value ""))
15689 ((not (stringp value)) (error "Properties values should be strings"))
15690 ((not (org--valid-property-p property))
15691 (user-error "Invalid property name: \"%s\"" property)))
15692 (org-with-point-at pom
15693 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15694 (org-back-to-heading t)
15695 (org-with-limited-levels (org-back-to-heading t)))
15696 (let ((beg (point)))
15697 (cond
15698 ((equal property "TODO")
15699 (cond ((not (org-string-nw-p value)) (setq value 'none))
15700 ((not (member value org-todo-keywords-1))
15701 (user-error "\"%s\" is not a valid TODO state" value)))
15702 (org-todo value)
15703 (org-set-tags nil 'align))
15704 ((equal property "PRIORITY")
15705 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15706 (org-set-tags nil 'align))
15707 ((equal property "SCHEDULED")
15708 (forward-line)
15709 (if (and (looking-at-p org-planning-line-re)
15710 (re-search-forward
15711 org-scheduled-time-regexp (line-end-position) t))
15712 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15713 ((string= value "later") (org-timestamp-change 1 'day))
15714 ((string= value "") (org-schedule '(4)))
15715 (t (org-schedule nil value)))
15716 (if (member value '("earlier" "later" ""))
15717 (call-interactively #'org-schedule)
15718 (org-schedule nil value))))
15719 ((equal property "DEADLINE")
15720 (forward-line)
15721 (if (and (looking-at-p org-planning-line-re)
15722 (re-search-forward
15723 org-deadline-time-regexp (line-end-position) t))
15724 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15725 ((string= value "later") (org-timestamp-change 1 'day))
15726 ((string= value "") (org-deadline '(4)))
15727 (t (org-deadline nil value)))
15728 (if (member value '("earlier" "later" ""))
15729 (call-interactively #'org-deadline)
15730 (org-deadline nil value))))
15731 ((member property org-special-properties)
15732 (error "The %s property cannot be set with `org-entry-put'" property))
15734 (let* ((range (org-get-property-block beg 'force))
15735 (end (cdr range))
15736 (case-fold-search t))
15737 (goto-char (car range))
15738 (if (re-search-forward (org-re-property property nil t) end t)
15739 (progn (delete-region (match-beginning 0) (match-end 0))
15740 (goto-char (match-beginning 0)))
15741 (goto-char end)
15742 (insert "\n")
15743 (backward-char))
15744 (insert ":" property ":")
15745 (when value (insert " " value))
15746 (org-indent-line)))))
15747 (run-hook-with-args 'org-property-changed-functions property value)))
15749 (defun org-buffer-property-keys (&optional specials defaults columns)
15750 "Get all property keys in the current buffer.
15752 When SPECIALS is non-nil, also list the special properties that
15753 reflect things like tags and TODO state.
15755 When DEFAULTS is non-nil, also include properties that has
15756 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15757 DESCRIPTION, LOCATION, and LOGGING and others.
15759 When COLUMNS in non-nil, also include property names given in
15760 COLUMN formats in the current buffer."
15761 (let ((case-fold-search t)
15762 (props (append
15763 (and specials org-special-properties)
15764 (and defaults (cons org-effort-property org-default-properties))
15765 nil)))
15766 (org-with-wide-buffer
15767 (goto-char (point-min))
15768 (while (re-search-forward org-property-start-re nil t)
15769 (catch :skip
15770 (let ((range (org-get-property-block)))
15771 (unless range (throw :skip nil))
15772 (goto-char (car range))
15773 (let ((begin (car range))
15774 (end (cdr range)))
15775 ;; Make sure that found property block is not located
15776 ;; before current point, as it would generate an infloop.
15777 ;; It can happen, for example, in the following
15778 ;; situation:
15780 ;; * Headline
15781 ;; :PROPERTIES:
15782 ;; ...
15783 ;; :END:
15784 ;; *************** Inlinetask
15785 ;; #+BEGIN_EXAMPLE
15786 ;; :PROPERTIES:
15787 ;; #+END_EXAMPLE
15789 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15790 (while (< (point) end)
15791 (let ((p (progn (looking-at org-property-re)
15792 (match-string-no-properties 2))))
15793 ;; Only add true property name, not extension symbol.
15794 (push (if (not (string-match-p "\\+\\'" p)) p
15795 (substring p 0 -1))
15796 props))
15797 (forward-line))))
15798 (outline-next-heading)))
15799 (when columns
15800 (goto-char (point-min))
15801 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15802 (let ((element (org-element-at-point)))
15803 (when (memq (org-element-type element) '(keyword node-property))
15804 (let ((value (org-element-property :value element))
15805 (start 0))
15806 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15807 \\(?:{[^}]+}\\)?"
15808 value start)
15809 (setq start (match-end 0))
15810 (let ((p (match-string-no-properties 1 value)))
15811 (unless (member-ignore-case p org-special-properties)
15812 (push p props))))))))))
15813 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15815 (defun org-property-values (key)
15816 "List all non-nil values of property KEY in current buffer."
15817 (org-with-wide-buffer
15818 (goto-char (point-min))
15819 (let ((case-fold-search t)
15820 (re (org-re-property key))
15821 values)
15822 (while (re-search-forward re nil t)
15823 (push (org-entry-get (point) key) values))
15824 (delete-dups values))))
15826 (defun org-insert-property-drawer ()
15827 "Insert a property drawer into the current entry."
15828 (org-with-wide-buffer
15829 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15830 (org-back-to-heading t)
15831 (org-with-limited-levels (org-back-to-heading t)))
15832 (forward-line)
15833 (when (looking-at-p org-planning-line-re) (forward-line))
15834 (unless (looking-at-p org-property-drawer-re)
15835 ;; Make sure we start editing a line from current entry, not from
15836 ;; next one. It prevents extending text properties or overlays
15837 ;; belonging to the latter.
15838 (when (bolp) (backward-char))
15839 (let ((begin (1+ (point)))
15840 (inhibit-read-only t))
15841 (insert "\n:PROPERTIES:\n:END:")
15842 (when (eobp) (insert "\n"))
15843 (org-indent-region begin (point))))))
15845 (defun org-insert-drawer (&optional arg drawer)
15846 "Insert a drawer at point.
15848 When optional argument ARG is non-nil, insert a property drawer.
15850 Optional argument DRAWER, when non-nil, is a string representing
15851 drawer's name. Otherwise, the user is prompted for a name.
15853 If a region is active, insert the drawer around that region
15854 instead.
15856 Point is left between drawer's boundaries."
15857 (interactive "P")
15858 (let* ((drawer (if arg "PROPERTIES"
15859 (or drawer (read-from-minibuffer "Drawer: ")))))
15860 (cond
15861 ;; With C-u, fall back on `org-insert-property-drawer'
15862 (arg (org-insert-property-drawer))
15863 ;; Check validity of suggested drawer's name.
15864 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15865 (user-error "Invalid drawer name"))
15866 ;; With an active region, insert a drawer at point.
15867 ((not (org-region-active-p))
15868 (progn
15869 (unless (bolp) (insert "\n"))
15870 (insert (format ":%s:\n\n:END:\n" drawer))
15871 (forward-line -2)))
15872 ;; Otherwise, insert the drawer at point
15874 (let ((rbeg (region-beginning))
15875 (rend (copy-marker (region-end))))
15876 (unwind-protect
15877 (progn
15878 (goto-char rbeg)
15879 (beginning-of-line)
15880 (when (save-excursion
15881 (re-search-forward org-outline-regexp-bol rend t))
15882 (user-error "Drawers cannot contain headlines"))
15883 ;; Position point at the beginning of the first
15884 ;; non-blank line in region. Insert drawer's opening
15885 ;; there, then indent it.
15886 (org-skip-whitespace)
15887 (beginning-of-line)
15888 (insert ":" drawer ":\n")
15889 (forward-line -1)
15890 (indent-for-tab-command)
15891 ;; Move point to the beginning of the first blank line
15892 ;; after the last non-blank line in region. Insert
15893 ;; drawer's closing, then indent it.
15894 (goto-char rend)
15895 (skip-chars-backward " \r\t\n")
15896 (insert "\n:END:")
15897 (deactivate-mark t)
15898 (indent-for-tab-command)
15899 (unless (eolp) (insert "\n")))
15900 ;; Clear marker, whatever the outcome of insertion is.
15901 (set-marker rend nil)))))))
15903 (defvar org-property-set-functions-alist nil
15904 "Property set function alist.
15905 Each entry should have the following format:
15907 (PROPERTY . READ-FUNCTION)
15909 The read function will be called with the same argument as
15910 `org-completing-read'.")
15912 (defun org-set-property-function (property)
15913 "Get the function that should be used to set PROPERTY.
15914 This is computed according to `org-property-set-functions-alist'."
15915 (or (cdr (assoc property org-property-set-functions-alist))
15916 'org-completing-read))
15918 (defun org-read-property-value (property)
15919 "Read PROPERTY value from user."
15920 (let* ((completion-ignore-case t)
15921 (allowed (org-property-get-allowed-values nil property 'table))
15922 (cur (org-entry-get nil property))
15923 (prompt (concat property " value"
15924 (if (and cur (string-match "\\S-" cur))
15925 (concat " [" cur "]") "") ": "))
15926 (set-function (org-set-property-function property))
15927 (val (if allowed
15928 (funcall set-function prompt allowed nil
15929 (not (get-text-property 0 'org-unrestricted
15930 (caar allowed))))
15931 (funcall set-function prompt
15932 (mapcar 'list (org-property-values property))
15933 nil nil "" nil cur))))
15934 (org-trim val)))
15936 (defvar org-last-set-property nil)
15937 (defvar org-last-set-property-value nil)
15938 (defun org-read-property-name ()
15939 "Read a property name."
15940 (let ((completion-ignore-case t)
15941 (default-prop (or (and (org-at-property-p)
15942 (match-string-no-properties 2))
15943 org-last-set-property)))
15944 (org-completing-read
15945 (concat "Property"
15946 (if default-prop (concat " [" default-prop "]") "")
15947 ": ")
15948 (mapcar #'list (org-buffer-property-keys nil t t))
15949 nil nil nil nil default-prop)))
15951 (defun org-set-property-and-value (use-last)
15952 "Allow to set [PROPERTY]: [value] direction from prompt.
15953 When use-default, don't even ask, just use the last
15954 \"[PROPERTY]: [value]\" string from the history."
15955 (interactive "P")
15956 (let* ((completion-ignore-case t)
15957 (pv (or (and use-last org-last-set-property-value)
15958 (org-completing-read
15959 "Enter a \"[Property]: [value]\" pair: "
15960 nil nil nil nil nil
15961 org-last-set-property-value)))
15962 prop val)
15963 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15964 (setq prop (match-string 1 pv)
15965 val (match-string 2 pv))
15966 (org-set-property prop val))))
15968 (defun org-set-property (property value)
15969 "In the current entry, set PROPERTY to VALUE.
15971 When called interactively, this will prompt for a property name, offering
15972 completion on existing and default properties. And then it will prompt
15973 for a value, offering completion either on allowed values (via an inherited
15974 xxx_ALL property) or on existing values in other instances of this property
15975 in the current file.
15977 Throw an error when trying to set a property with an invalid name."
15978 (interactive (list nil nil))
15979 (let ((property (or property (org-read-property-name))))
15980 ;; `org-entry-put' also makes the following check, but this one
15981 ;; avoids polluting `org-last-set-property' and
15982 ;; `org-last-set-property-value' needlessly.
15983 (unless (org--valid-property-p property)
15984 (user-error "Invalid property name: \"%s\"" property))
15985 (let ((value (or value (org-read-property-value property)))
15986 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15987 (setq org-last-set-property property)
15988 (setq org-last-set-property-value (concat property ": " value))
15989 ;; Possibly postprocess the inserted value:
15990 (when fn (setq value (funcall fn value)))
15991 (unless (equal (org-entry-get nil property) value)
15992 (org-entry-put nil property value)))))
15994 (defun org-find-property (property &optional value)
15995 "Find first entry in buffer that sets PROPERTY.
15997 When optional argument VALUE is non-nil, only consider an entry
15998 if it contains PROPERTY set to this value. If PROPERTY should be
15999 explicitly set to nil, use string \"nil\" for VALUE.
16001 Return position where the entry begins, or nil if there is no
16002 such entry. If narrowing is in effect, only search the visible
16003 part of the buffer."
16004 (save-excursion
16005 (goto-char (point-min))
16006 (let ((case-fold-search t)
16007 (re (org-re-property property nil (not value) value)))
16008 (catch 'exit
16009 (while (re-search-forward re nil t)
16010 (when (if value (org-at-property-p)
16011 (org-entry-get (point) property nil t))
16012 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16014 (defun org-delete-property (property)
16015 "In the current entry, delete PROPERTY."
16016 (interactive
16017 (let* ((completion-ignore-case t)
16018 (cat (org-entry-get (point) "CATEGORY"))
16019 (props0 (org-entry-properties nil 'standard))
16020 (props (if cat props0
16021 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16022 (prop (if (< 1 (length props))
16023 (completing-read "Property: " props nil t)
16024 (caar props))))
16025 (list prop)))
16026 (if (not property)
16027 (message "No property to delete in this entry")
16028 (org-entry-delete nil property)
16029 (message "Property \"%s\" deleted" property)))
16031 (defun org-delete-property-globally (property)
16032 "Remove PROPERTY globally, from all entries.
16033 This function ignores narrowing, if any."
16034 (interactive
16035 (let* ((completion-ignore-case t)
16036 (prop (completing-read
16037 "Globally remove property: "
16038 (mapcar #'list (org-buffer-property-keys)))))
16039 (list prop)))
16040 (org-with-wide-buffer
16041 (goto-char (point-min))
16042 (let ((count 0)
16043 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16044 (while (re-search-forward re nil t)
16045 (when (org-entry-delete (point) property) (cl-incf count)))
16046 (message "Property \"%s\" removed from %d entries" property count))))
16048 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16050 (defun org-compute-property-at-point ()
16051 "Compute the property at point.
16052 This looks for an enclosing column format, extracts the operator and
16053 then applies it to the property in the column format's scope."
16054 (interactive)
16055 (unless (org-at-property-p)
16056 (user-error "Not at a property"))
16057 (let ((prop (match-string-no-properties 2)))
16058 (org-columns-get-format-and-top-level)
16059 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16060 (user-error "No operator defined for property %s" prop))
16061 (org-columns-compute prop)))
16063 (defvar org-property-allowed-value-functions nil
16064 "Hook for functions supplying allowed values for a specific property.
16065 The functions must take a single argument, the name of the property, and
16066 return a flat list of allowed values. If \":ETC\" is one of
16067 the values, this means that these values are intended as defaults for
16068 completion, but that other values should be allowed too.
16069 The functions must return nil if they are not responsible for this
16070 property.")
16072 (defun org-property-get-allowed-values (pom property &optional table)
16073 "Get allowed values for the property PROPERTY.
16074 When TABLE is non-nil, return an alist that can directly be used for
16075 completion."
16076 (let (vals)
16077 (cond
16078 ((equal property "TODO")
16079 (setq vals (org-with-point-at pom
16080 (append org-todo-keywords-1 '("")))))
16081 ((equal property "PRIORITY")
16082 (let ((n org-lowest-priority))
16083 (while (>= n org-highest-priority)
16084 (push (char-to-string n) vals)
16085 (setq n (1- n)))))
16086 ((equal property "CATEGORY"))
16087 ((member property org-special-properties))
16088 ((setq vals (run-hook-with-args-until-success
16089 'org-property-allowed-value-functions property)))
16091 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16092 (when (and vals (string-match "\\S-" vals))
16093 (setq vals (car (read-from-string (concat "(" vals ")"))))
16094 (setq vals (mapcar (lambda (x)
16095 (cond ((stringp x) x)
16096 ((numberp x) (number-to-string x))
16097 ((symbolp x) (symbol-name x))
16098 (t "???")))
16099 vals)))))
16100 (when (member ":ETC" vals)
16101 (setq vals (remove ":ETC" vals))
16102 (org-add-props (car vals) '(org-unrestricted t)))
16103 (if table (mapcar 'list vals) vals)))
16105 (defun org-property-previous-allowed-value (&optional _previous)
16106 "Switch to the next allowed value for this property."
16107 (interactive)
16108 (org-property-next-allowed-value t))
16110 (defun org-property-next-allowed-value (&optional previous)
16111 "Switch to the next allowed value for this property."
16112 (interactive)
16113 (unless (org-at-property-p)
16114 (user-error "Not at a property"))
16115 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16116 (key (match-string 2))
16117 (value (match-string 3))
16118 (allowed (or (org-property-get-allowed-values (point) key)
16119 (and (member value '("[ ]" "[-]" "[X]"))
16120 '("[ ]" "[X]"))))
16121 (heading (save-match-data (nth 4 (org-heading-components))))
16122 nval)
16123 (unless allowed
16124 (user-error "Allowed values for this property have not been defined"))
16125 (when previous (setq allowed (reverse allowed)))
16126 (when (member value allowed)
16127 (setq nval (car (cdr (member value allowed)))))
16128 (setq nval (or nval (car allowed)))
16129 (when (equal nval value)
16130 (user-error "Only one allowed value for this property"))
16131 (org-at-property-p)
16132 (replace-match (concat " :" key ": " nval) t t)
16133 (org-indent-line)
16134 (beginning-of-line 1)
16135 (skip-chars-forward " \t")
16136 (when (equal prop org-effort-property)
16137 (org-refresh-property
16138 '((effort . identity)
16139 (effort-minutes . org-duration-to-minutes))
16140 nval)
16141 (when (string= org-clock-current-task heading)
16142 (setq org-clock-effort nval)
16143 (org-clock-update-mode-line)))
16144 (run-hook-with-args 'org-property-changed-functions key nval)))
16146 (defun org-find-olp (path &optional this-buffer)
16147 "Return a marker pointing to the entry at outline path OLP.
16148 If anything goes wrong, throw an error.
16149 You can wrap this call to catch the error like this:
16151 (condition-case msg
16152 (org-mobile-locate-entry (match-string 4))
16153 (error (nth 1 msg)))
16155 The return value will then be either a string with the error message,
16156 or a marker if everything is OK.
16158 If THIS-BUFFER is set, the outline path does not contain a file,
16159 only headings."
16160 (let* ((file (if this-buffer buffer-file-name (pop path)))
16161 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16162 (level 1)
16163 (lmin 1)
16164 (lmax 1)
16165 end found flevel)
16166 (unless buffer (error "File not found :%s" file))
16167 (with-current-buffer buffer
16168 (unless (derived-mode-p 'org-mode)
16169 (error "Buffer %s needs to be in Org mode" buffer))
16170 (org-with-wide-buffer
16171 (goto-char (point-min))
16172 (dolist (heading path)
16173 (let ((re (format org-complex-heading-regexp-format
16174 (regexp-quote heading)))
16175 (cnt 0))
16176 (while (re-search-forward re end t)
16177 (setq level (- (match-end 1) (match-beginning 1)))
16178 (when (and (>= level lmin) (<= level lmax))
16179 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16180 (when (= cnt 0)
16181 (error "Heading not found on level %d: %s" lmax heading))
16182 (when (> cnt 1)
16183 (error "Heading not unique on level %d: %s" lmax heading))
16184 (goto-char found)
16185 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16186 (setq end (save-excursion (org-end-of-subtree t t)))))
16187 (when (org-at-heading-p)
16188 (point-marker))))))
16190 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16191 "Find node HEADING in BUFFER.
16192 Return a marker to the heading if it was found, or nil if not.
16193 If POS-ONLY is set, return just the position instead of a marker.
16195 The heading text must match exact, but it may have a TODO keyword,
16196 a priority cookie and tags in the standard locations."
16197 (with-current-buffer (or buffer (current-buffer))
16198 (org-with-wide-buffer
16199 (goto-char (point-min))
16200 (let (case-fold-search)
16201 (when (re-search-forward
16202 (format org-complex-heading-regexp-format
16203 (regexp-quote heading)) nil t)
16204 (if pos-only
16205 (match-beginning 0)
16206 (move-marker (make-marker) (match-beginning 0))))))))
16208 (defun org-find-exact-heading-in-directory (heading &optional dir)
16209 "Find Org node headline HEADING in all .org files in directory DIR.
16210 When the target headline is found, return a marker to this location."
16211 (let ((files (directory-files (or dir default-directory)
16212 t "\\`[^.#].*\\.org\\'"))
16213 visiting m buffer)
16214 (catch 'found
16215 (dolist (file files)
16216 (message "trying %s" file)
16217 (setq visiting (org-find-base-buffer-visiting file))
16218 (setq buffer (or visiting (find-file-noselect file)))
16219 (setq m (org-find-exact-headline-in-buffer
16220 heading buffer))
16221 (when (and (not m) (not visiting)) (kill-buffer buffer))
16222 (and m (throw 'found m))))))
16224 (defun org-find-entry-with-id (ident)
16225 "Locate the entry that contains the ID property with exact value IDENT.
16226 IDENT can be a string, a symbol or a number, this function will search for
16227 the string representation of it.
16228 Return the position where this entry starts, or nil if there is no such entry."
16229 (interactive "sID: ")
16230 (let ((id (cond
16231 ((stringp ident) ident)
16232 ((symbolp ident) (symbol-name ident))
16233 ((numberp ident) (number-to-string ident))
16234 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16235 (org-with-wide-buffer (org-find-property "ID" id))))
16237 ;;;; Timestamps
16239 (defvar org-last-changed-timestamp nil)
16240 (defvar org-last-inserted-timestamp nil
16241 "The last time stamp inserted with `org-insert-time-stamp'.")
16243 (defun org-time-stamp (arg &optional inactive)
16244 "Prompt for a date/time and insert a time stamp.
16246 If the user specifies a time like HH:MM or if this command is
16247 called with at least one prefix argument, the time stamp contains
16248 the date and the time. Otherwise, only the date is included.
16250 All parts of a date not specified by the user are filled in from
16251 the timestamp at point, if any, or the current date/time
16252 otherwise.
16254 If there is already a timestamp at the cursor, it is replaced.
16256 With two universal prefix arguments, insert an active timestamp
16257 with the current time without prompting the user.
16259 When called from lisp, the timestamp is inactive if INACTIVE is
16260 non-nil."
16261 (interactive "P")
16262 (let* ((ts (cond
16263 ((org-at-date-range-p t)
16264 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16265 ((org-at-timestamp-p 'lax) (match-string 0))))
16266 ;; Default time is either the timestamp at point or today.
16267 ;; When entering a range, only the range start is considered.
16268 (default-time (if (not ts) (current-time)
16269 (apply #'encode-time (org-parse-time-string ts))))
16270 (default-input (and ts (org-get-compact-tod ts)))
16271 (repeater (and ts
16272 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16273 (match-string 0 ts)))
16274 org-time-was-given
16275 org-end-time-was-given
16276 (time
16277 (and (if (equal arg '(16)) (current-time)
16278 ;; Preserve `this-command' and `last-command'.
16279 (let ((this-command this-command)
16280 (last-command last-command))
16281 (org-read-date
16282 arg 'totime nil nil default-time default-input
16283 inactive))))))
16284 (cond
16285 ((and ts
16286 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16287 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16288 (insert "--")
16289 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16291 ;; Make sure we're on a timestamp. When in the middle of a date
16292 ;; range, move arbitrarily to range end.
16293 (unless (org-at-timestamp-p 'lax)
16294 (skip-chars-forward "-")
16295 (org-at-timestamp-p 'lax))
16296 (replace-match "")
16297 (setq org-last-changed-timestamp
16298 (org-insert-time-stamp
16299 time (or org-time-was-given arg)
16300 inactive nil nil (list org-end-time-was-given)))
16301 (when repeater
16302 (backward-char)
16303 (insert " " repeater)
16304 (setq org-last-changed-timestamp
16305 (concat (substring org-last-inserted-timestamp 0 -1)
16306 " " repeater ">")))
16307 (message "Timestamp updated"))
16308 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16309 (t (org-insert-time-stamp
16310 time (or org-time-was-given arg) inactive nil nil
16311 (list org-end-time-was-given))))))
16313 ;; FIXME: can we use this for something else, like computing time differences?
16314 (defun org-get-compact-tod (s)
16315 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16316 (let* ((t1 (match-string 1 s))
16317 (h1 (string-to-number (match-string 2 s)))
16318 (m1 (string-to-number (match-string 3 s)))
16319 (t2 (and (match-end 4) (match-string 5 s)))
16320 (h2 (and t2 (string-to-number (match-string 6 s))))
16321 (m2 (and t2 (string-to-number (match-string 7 s))))
16322 dh dm)
16323 (if (not t2)
16325 (setq dh (- h2 h1) dm (- m2 m1))
16326 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16327 (concat t1 "+" (number-to-string dh)
16328 (and (/= 0 dm) (format ":%02d" dm)))))))
16330 (defun org-time-stamp-inactive (&optional arg)
16331 "Insert an inactive time stamp.
16332 An inactive time stamp is enclosed in square brackets instead of angle
16333 brackets. It is inactive in the sense that it does not trigger agenda entries,
16334 does not link to the calendar and cannot be changed with the S-cursor keys.
16335 So these are more for recording a certain time/date."
16336 (interactive "P")
16337 (org-time-stamp arg 'inactive))
16339 (defvar org-date-ovl (make-overlay 1 1))
16340 (overlay-put org-date-ovl 'face 'org-date-selected)
16341 (delete-overlay org-date-ovl)
16343 (defvar org-ans1) ; dynamically scoped parameter
16344 (defvar org-ans2) ; dynamically scoped parameter
16346 (defvar org-plain-time-of-day-regexp) ; defined below
16348 (defvar org-overriding-default-time nil) ; dynamically scoped
16349 (defvar org-read-date-overlay nil)
16350 (defvar org-dcst nil) ; dynamically scoped
16351 (defvar org-read-date-history nil)
16352 (defvar org-read-date-final-answer nil)
16353 (defvar org-read-date-analyze-futurep nil)
16354 (defvar org-read-date-analyze-forced-year nil)
16355 (defvar org-read-date-inactive)
16357 (defvar org-read-date-minibuffer-local-map
16358 (let* ((map (make-sparse-keymap)))
16359 (set-keymap-parent map minibuffer-local-map)
16360 (org-defkey map (kbd ".")
16361 (lambda () (interactive)
16362 ;; Are we at the beginning of the prompt?
16363 (if (looking-back "^[^:]+: "
16364 (let ((inhibit-field-text-motion t))
16365 (line-beginning-position)))
16366 (org-eval-in-calendar '(calendar-goto-today))
16367 (insert "."))))
16368 (org-defkey map (kbd "C-.")
16369 (lambda () (interactive)
16370 (org-eval-in-calendar '(calendar-goto-today))))
16371 (org-defkey map [(meta shift left)]
16372 (lambda () (interactive)
16373 (org-eval-in-calendar '(calendar-backward-month 1))))
16374 (org-defkey map [(meta shift right)]
16375 (lambda () (interactive)
16376 (org-eval-in-calendar '(calendar-forward-month 1))))
16377 (org-defkey map [(meta shift up)]
16378 (lambda () (interactive)
16379 (org-eval-in-calendar '(calendar-backward-year 1))))
16380 (org-defkey map [(meta shift down)]
16381 (lambda () (interactive)
16382 (org-eval-in-calendar '(calendar-forward-year 1))))
16383 (org-defkey map [?\e (shift left)]
16384 (lambda () (interactive)
16385 (org-eval-in-calendar '(calendar-backward-month 1))))
16386 (org-defkey map [?\e (shift right)]
16387 (lambda () (interactive)
16388 (org-eval-in-calendar '(calendar-forward-month 1))))
16389 (org-defkey map [?\e (shift up)]
16390 (lambda () (interactive)
16391 (org-eval-in-calendar '(calendar-backward-year 1))))
16392 (org-defkey map [?\e (shift down)]
16393 (lambda () (interactive)
16394 (org-eval-in-calendar '(calendar-forward-year 1))))
16395 (org-defkey map [(shift up)]
16396 (lambda () (interactive)
16397 (org-eval-in-calendar '(calendar-backward-week 1))))
16398 (org-defkey map [(shift down)]
16399 (lambda () (interactive)
16400 (org-eval-in-calendar '(calendar-forward-week 1))))
16401 (org-defkey map [(shift left)]
16402 (lambda () (interactive)
16403 (org-eval-in-calendar '(calendar-backward-day 1))))
16404 (org-defkey map [(shift right)]
16405 (lambda () (interactive)
16406 (org-eval-in-calendar '(calendar-forward-day 1))))
16407 (org-defkey map "!"
16408 (lambda () (interactive)
16409 (org-eval-in-calendar '(diary-view-entries))
16410 (message "")))
16411 (org-defkey map ">"
16412 (lambda () (interactive)
16413 (org-eval-in-calendar '(calendar-scroll-left 1))))
16414 (org-defkey map "<"
16415 (lambda () (interactive)
16416 (org-eval-in-calendar '(calendar-scroll-right 1))))
16417 (org-defkey map "\C-v"
16418 (lambda () (interactive)
16419 (org-eval-in-calendar
16420 '(calendar-scroll-left-three-months 1))))
16421 (org-defkey map "\M-v"
16422 (lambda () (interactive)
16423 (org-eval-in-calendar
16424 '(calendar-scroll-right-three-months 1))))
16425 map)
16426 "Keymap for minibuffer commands when using `org-read-date'.")
16428 (defvar org-def)
16429 (defvar org-defdecode)
16430 (defvar org-with-time)
16432 (defvar calendar-setup) ; Dynamically scoped.
16433 (defun org-read-date (&optional with-time to-time from-string prompt
16434 default-time default-input inactive)
16435 "Read a date, possibly a time, and make things smooth for the user.
16436 The prompt will suggest to enter an ISO date, but you can also enter anything
16437 which will at least partially be understood by `parse-time-string'.
16438 Unrecognized parts of the date will default to the current day, month, year,
16439 hour and minute. If this command is called to replace a timestamp at point,
16440 or to enter the second timestamp of a range, the default time is taken
16441 from the existing stamp. Furthermore, the command prefers the future,
16442 so if you are giving a date where the year is not given, and the day-month
16443 combination is already past in the current year, it will assume you
16444 mean next year. For details, see the manual. A few examples:
16446 3-2-5 --> 2003-02-05
16447 feb 15 --> currentyear-02-15
16448 2/15 --> currentyear-02-15
16449 sep 12 9 --> 2009-09-12
16450 12:45 --> today 12:45
16451 22 sept 0:34 --> currentyear-09-22 0:34
16452 12 --> currentyear-currentmonth-12
16453 Fri --> nearest Friday after today
16454 -Tue --> last Tuesday
16455 etc.
16457 Furthermore you can specify a relative date by giving, as the *first* thing
16458 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16459 change in days weeks, months, years.
16460 With a single plus or minus, the date is relative to today. With a double
16461 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16462 +4d --> four days from today
16463 +4 --> same as above
16464 +2w --> two weeks from today
16465 ++5 --> five days from default date
16467 The function understands only English month and weekday abbreviations.
16469 While prompting, a calendar is popped up - you can also select the
16470 date with the mouse (button 1). The calendar shows a period of three
16471 months. To scroll it to other months, use the keys `>' and `<'.
16472 If you don't like the calendar, turn it off with
16473 (setq org-read-date-popup-calendar nil)
16475 With optional argument TO-TIME, the date will immediately be converted
16476 to an internal time.
16477 With an optional argument WITH-TIME, the prompt will suggest to
16478 also insert a time. Note that when WITH-TIME is not set, you can
16479 still enter a time, and this function will inform the calling routine
16480 about this change. The calling routine may then choose to change the
16481 format used to insert the time stamp into the buffer to include the time.
16482 With optional argument FROM-STRING, read from this string instead from
16483 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16484 the time/date that is used for everything that is not specified by the
16485 user."
16486 (require 'parse-time)
16487 (let* ((org-with-time with-time)
16488 (org-time-stamp-rounding-minutes
16489 (if (equal org-with-time '(16))
16490 '(0 0)
16491 org-time-stamp-rounding-minutes))
16492 (org-dcst org-display-custom-times)
16493 (ct (org-current-time))
16494 (org-def (or org-overriding-default-time default-time ct))
16495 (org-defdecode (decode-time org-def))
16496 (cur-frame (selected-frame))
16497 (mouse-autoselect-window nil) ; Don't let the mouse jump
16498 (calendar-setup
16499 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16500 (calendar-move-hook nil)
16501 (calendar-view-diary-initially-flag nil)
16502 (calendar-view-holidays-initially-flag nil)
16503 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16504 ;; Rationalize `org-def' and `org-defdecode', if required.
16505 (when (< (nth 2 org-defdecode) org-extend-today-until)
16506 (setf (nth 2 org-defdecode) -1)
16507 (setf (nth 1 org-defdecode) 59)
16508 (setq org-def (apply #'encode-time org-defdecode))
16509 (setq org-defdecode (decode-time org-def)))
16510 (let* ((timestr (format-time-string
16511 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16512 org-def))
16513 (prompt (concat (if prompt (concat prompt " ") "")
16514 (format "Date+time [%s]: " timestr))))
16515 (cond
16516 (from-string (setq ans from-string))
16517 (org-read-date-popup-calendar
16518 (save-excursion
16519 (save-window-excursion
16520 (calendar)
16521 (when (eq calendar-setup 'calendar-only)
16522 (setq cal-frame
16523 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16524 (select-frame cal-frame))
16525 (org-eval-in-calendar '(setq cursor-type nil) t)
16526 (unwind-protect
16527 (progn
16528 (calendar-forward-day (- (time-to-days org-def)
16529 (calendar-absolute-from-gregorian
16530 (calendar-current-date))))
16531 (org-eval-in-calendar nil t)
16532 (let* ((old-map (current-local-map))
16533 (map (copy-keymap calendar-mode-map))
16534 (minibuffer-local-map
16535 (copy-keymap org-read-date-minibuffer-local-map)))
16536 (org-defkey map (kbd "RET") 'org-calendar-select)
16537 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16538 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16539 (unwind-protect
16540 (progn
16541 (use-local-map map)
16542 (setq org-read-date-inactive inactive)
16543 (add-hook 'post-command-hook 'org-read-date-display)
16544 (setq org-ans0
16545 (read-string prompt
16546 default-input
16547 'org-read-date-history
16548 nil))
16549 ;; org-ans0: from prompt
16550 ;; org-ans1: from mouse click
16551 ;; org-ans2: from calendar motion
16552 (setq ans
16553 (concat org-ans0 " " (or org-ans1 org-ans2))))
16554 (remove-hook 'post-command-hook 'org-read-date-display)
16555 (use-local-map old-map)
16556 (when org-read-date-overlay
16557 (delete-overlay org-read-date-overlay)
16558 (setq org-read-date-overlay nil)))))
16559 (bury-buffer "*Calendar*")
16560 (when cal-frame
16561 (delete-frame cal-frame)
16562 (select-frame-set-input-focus cur-frame))))))
16564 (t ; Naked prompt only
16565 (unwind-protect
16566 (setq ans (read-string prompt default-input
16567 'org-read-date-history timestr))
16568 (when org-read-date-overlay
16569 (delete-overlay org-read-date-overlay)
16570 (setq org-read-date-overlay nil))))))
16572 (setq final (org-read-date-analyze ans org-def org-defdecode))
16574 (when org-read-date-analyze-forced-year
16575 (message "Year was forced into %s"
16576 (if org-read-date-force-compatible-dates
16577 "compatible range (1970-2037)"
16578 "range representable on this machine"))
16579 (ding))
16581 ;; One round trip to get rid of 34th of August and stuff like that....
16582 (setq final (decode-time (apply 'encode-time final)))
16584 (setq org-read-date-final-answer ans)
16586 (if to-time
16587 (apply 'encode-time final)
16588 (if (and (boundp 'org-time-was-given) org-time-was-given)
16589 (format "%04d-%02d-%02d %02d:%02d"
16590 (nth 5 final) (nth 4 final) (nth 3 final)
16591 (nth 2 final) (nth 1 final))
16592 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16594 (defun org-read-date-display ()
16595 "Display the current date prompt interpretation in the minibuffer."
16596 (when org-read-date-display-live
16597 (when org-read-date-overlay
16598 (delete-overlay org-read-date-overlay))
16599 (when (minibufferp (current-buffer))
16600 (save-excursion
16601 (end-of-line 1)
16602 (while (not (equal (buffer-substring
16603 (max (point-min) (- (point) 4)) (point))
16604 " "))
16605 (insert " ")))
16606 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16607 " " (or org-ans1 org-ans2)))
16608 (org-end-time-was-given nil)
16609 (f (org-read-date-analyze ans org-def org-defdecode))
16610 (fmts (if org-dcst
16611 org-time-stamp-custom-formats
16612 org-time-stamp-formats))
16613 (fmt (if (or org-with-time
16614 (and (boundp 'org-time-was-given) org-time-was-given))
16615 (cdr fmts)
16616 (car fmts)))
16617 (txt (format-time-string fmt (apply 'encode-time f)))
16618 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16619 (txt (concat "=> " txt)))
16620 (when (and org-end-time-was-given
16621 (string-match org-plain-time-of-day-regexp txt))
16622 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16623 org-end-time-was-given
16624 (substring txt (match-end 0)))))
16625 (when org-read-date-analyze-futurep
16626 (setq txt (concat txt " (=>F)")))
16627 (setq org-read-date-overlay
16628 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16629 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16631 (defun org-read-date-analyze (ans def defdecode)
16632 "Analyze the combined answer of the date prompt."
16633 ;; FIXME: cleanup and comment
16634 ;; Pass `current-time' result to `decode-time' (instead of calling
16635 ;; without arguments) so that only `current-time' has to be
16636 ;; overridden in tests.
16637 (let ((org-def def)
16638 (org-defdecode defdecode)
16639 (nowdecode (decode-time (current-time)))
16640 delta deltan deltaw deltadef year month day
16641 hour minute second wday pm h2 m2 tl wday1
16642 iso-year iso-weekday iso-week iso-date futurep kill-year)
16643 (setq org-read-date-analyze-futurep nil
16644 org-read-date-analyze-forced-year nil)
16645 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16646 (setq ans "+0"))
16648 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16649 (setq ans (replace-match "" t t ans)
16650 deltan (car delta)
16651 deltaw (nth 1 delta)
16652 deltadef (nth 2 delta)))
16654 ;; Check if there is an iso week date in there. If yes, store the
16655 ;; info and postpone interpreting it until the rest of the parsing
16656 ;; is done.
16657 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16658 (setq iso-year (when (match-end 1)
16659 (org-small-year-to-year
16660 (string-to-number (match-string 1 ans))))
16661 iso-weekday (when (match-end 3)
16662 (string-to-number (match-string 3 ans)))
16663 iso-week (string-to-number (match-string 2 ans)))
16664 (setq ans (replace-match "" t t ans)))
16666 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16667 (when (string-match
16668 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16669 (setq year (if (match-end 2)
16670 (string-to-number (match-string 2 ans))
16671 (progn (setq kill-year t)
16672 (string-to-number (format-time-string "%Y"))))
16673 month (string-to-number (match-string 3 ans))
16674 day (string-to-number (match-string 4 ans)))
16675 (setq year (org-small-year-to-year year))
16676 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16677 t nil ans)))
16679 ;; Help matching dotted european dates
16680 (when (string-match
16681 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16682 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16683 (setq kill-year t)
16684 (string-to-number (format-time-string "%Y")))
16685 day (string-to-number (match-string 1 ans))
16686 month (string-to-number (match-string 2 ans))
16687 ans (replace-match (format "%04d-%02d-%02d" year month day)
16688 t nil ans)))
16690 ;; Help matching american dates, like 5/30 or 5/30/7
16691 (when (string-match
16692 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16693 (setq year (if (match-end 4)
16694 (string-to-number (match-string 4 ans))
16695 (progn (setq kill-year t)
16696 (string-to-number (format-time-string "%Y"))))
16697 month (string-to-number (match-string 1 ans))
16698 day (string-to-number (match-string 2 ans)))
16699 (setq year (org-small-year-to-year year))
16700 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16701 t nil ans)))
16702 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16703 ;; If there is a time with am/pm, and *no* time without it, we convert
16704 ;; so that matching will be successful.
16705 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16706 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16707 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16708 (setq hour (string-to-number (match-string 1 ans))
16709 minute (if (match-end 3)
16710 (string-to-number (match-string 3 ans))
16712 pm (equal ?p
16713 (string-to-char (downcase (match-string 4 ans)))))
16714 (if (and (= hour 12) (not pm))
16715 (setq hour 0)
16716 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16717 (setq ans (replace-match (format "%02d:%02d" hour minute)
16718 t t ans))))
16720 ;; Check if a time range is given as a duration
16721 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16722 (setq hour (string-to-number (match-string 1 ans))
16723 h2 (+ hour (string-to-number (match-string 3 ans)))
16724 minute (string-to-number (match-string 2 ans))
16725 m2 (+ minute (if (match-end 5) (string-to-number
16726 (match-string 5 ans))0)))
16727 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16728 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16729 t t ans)))
16731 ;; Check if there is a time range
16732 (when (boundp 'org-end-time-was-given)
16733 (setq org-time-was-given nil)
16734 (when (and (string-match org-plain-time-of-day-regexp ans)
16735 (match-end 8))
16736 (setq org-end-time-was-given (match-string 8 ans))
16737 (setq ans (concat (substring ans 0 (match-beginning 7))
16738 (substring ans (match-end 7))))))
16740 (setq tl (parse-time-string ans)
16741 day (or (nth 3 tl) (nth 3 org-defdecode))
16742 month
16743 (cond ((nth 4 tl))
16744 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16745 ;; Day was specified. Make sure DAY+MONTH
16746 ;; combination happens in the future.
16747 ((nth 3 tl)
16748 (setq futurep t)
16749 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16750 (nth 4 nowdecode)))
16751 (t (nth 4 org-defdecode)))
16752 year
16753 (cond ((and (not kill-year) (nth 5 tl)))
16754 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16755 ;; Month was guessed in the future and is at least
16756 ;; equal to NOWDECODE's. Fix year accordingly.
16757 (futurep
16758 (if (or (> month (nth 4 nowdecode))
16759 (>= day (nth 3 nowdecode)))
16760 (nth 5 nowdecode)
16761 (1+ (nth 5 nowdecode))))
16762 ;; Month was specified. Make sure MONTH+YEAR
16763 ;; combination happens in the future.
16764 ((nth 4 tl)
16765 (setq futurep t)
16766 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16767 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16768 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16769 (t (nth 5 nowdecode))))
16770 (t (nth 5 org-defdecode)))
16771 hour (or (nth 2 tl) (nth 2 org-defdecode))
16772 minute (or (nth 1 tl) (nth 1 org-defdecode))
16773 second (or (nth 0 tl) 0)
16774 wday (nth 6 tl))
16776 (when (and (eq org-read-date-prefer-future 'time)
16777 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16778 (equal day (nth 3 nowdecode))
16779 (equal month (nth 4 nowdecode))
16780 (equal year (nth 5 nowdecode))
16781 (nth 2 tl)
16782 (or (< (nth 2 tl) (nth 2 nowdecode))
16783 (and (= (nth 2 tl) (nth 2 nowdecode))
16784 (nth 1 tl)
16785 (< (nth 1 tl) (nth 1 nowdecode)))))
16786 (setq day (1+ day)
16787 futurep t))
16789 ;; Special date definitions below
16790 (cond
16791 (iso-week
16792 ;; There was an iso week
16793 (require 'cal-iso)
16794 (setq futurep nil)
16795 (setq year (or iso-year year)
16796 day (or iso-weekday wday 1)
16797 wday nil ; to make sure that the trigger below does not match
16798 iso-date (calendar-gregorian-from-absolute
16799 (calendar-iso-to-absolute
16800 (list iso-week day year))))
16801 ; FIXME: Should we also push ISO weeks into the future?
16802 ; (when (and org-read-date-prefer-future
16803 ; (not iso-year)
16804 ; (< (calendar-absolute-from-gregorian iso-date)
16805 ; (time-to-days (current-time))))
16806 ; (setq year (1+ year)
16807 ; iso-date (calendar-gregorian-from-absolute
16808 ; (calendar-iso-to-absolute
16809 ; (list iso-week day year)))))
16810 (setq month (car iso-date)
16811 year (nth 2 iso-date)
16812 day (nth 1 iso-date)))
16813 (deltan
16814 (setq futurep nil)
16815 (unless deltadef
16816 ;; Pass `current-time' result to `decode-time' (instead of
16817 ;; calling without arguments) so that only `current-time' has
16818 ;; to be overridden in tests.
16819 (let ((now (decode-time (current-time))))
16820 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16821 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16822 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16823 ((equal deltaw "m") (setq month (+ month deltan)))
16824 ((equal deltaw "y") (setq year (+ year deltan)))))
16825 ((and wday (not (nth 3 tl)))
16826 ;; Weekday was given, but no day, so pick that day in the week
16827 ;; on or after the derived date.
16828 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16829 (unless (equal wday wday1)
16830 (setq day (+ day (% (- wday wday1 -7) 7))))))
16831 (when (and (boundp 'org-time-was-given)
16832 (nth 2 tl))
16833 (setq org-time-was-given t))
16834 (when (< year 100) (setq year (+ 2000 year)))
16835 ;; Check of the date is representable
16836 (if org-read-date-force-compatible-dates
16837 (progn
16838 (when (< year 1970)
16839 (setq year 1970 org-read-date-analyze-forced-year t))
16840 (when (> year 2037)
16841 (setq year 2037 org-read-date-analyze-forced-year t)))
16842 (condition-case nil
16843 (ignore (encode-time second minute hour day month year))
16844 (error
16845 (setq year (nth 5 org-defdecode))
16846 (setq org-read-date-analyze-forced-year t))))
16847 (setq org-read-date-analyze-futurep futurep)
16848 (list second minute hour day month year)))
16850 (defvar parse-time-weekdays)
16851 (defun org-read-date-get-relative (s today default)
16852 "Check string S for special relative date string.
16853 TODAY and DEFAULT are internal times, for today and for a default.
16854 Return shift list (N what def-flag)
16855 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16856 N is the number of WHATs to shift.
16857 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16858 the DEFAULT date rather than TODAY."
16859 (require 'parse-time)
16860 (when (and
16861 (string-match
16862 (concat
16863 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16864 "\\([0-9]+\\)?"
16865 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16866 "\\([ \t]\\|$\\)") s)
16867 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16868 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16869 (string-to-char (substring (match-string 1 s) -1))
16870 ?+))
16871 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16872 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16873 (what (if (match-end 3) (match-string 3 s) "d"))
16874 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16875 (date (if rel default today))
16876 (wday (nth 6 (decode-time date)))
16877 delta)
16878 (if wday1
16879 (progn
16880 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16881 (when (= delta 0) (setq delta 7))
16882 (when (= dir ?-)
16883 (setq delta (- delta 7))
16884 (when (= delta 0) (setq delta -7)))
16885 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16886 (list delta "d" rel))
16887 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16889 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16890 "Turn a user-specified date into the internal representation.
16891 The internal representation needed by the calendar is (month day year).
16892 This is a wrapper to handle the brain-dead convention in calendar that
16893 user function argument order change dependent on argument order."
16894 (pcase calendar-date-style
16895 (`american (list arg1 arg2 arg3))
16896 (`european (list arg2 arg1 arg3))
16897 (`iso (list arg2 arg3 arg1))))
16899 (defun org-eval-in-calendar (form &optional keepdate)
16900 "Eval FORM in the calendar window and return to current window.
16901 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16902 (let ((sf (selected-frame))
16903 (sw (selected-window)))
16904 (select-window (get-buffer-window "*Calendar*" t))
16905 (eval form)
16906 (when (and (not keepdate) (calendar-cursor-to-date))
16907 (let* ((date (calendar-cursor-to-date))
16908 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16909 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16910 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16911 (select-window sw)
16912 (select-frame-set-input-focus sf)))
16914 (defun org-calendar-select ()
16915 "Return to `org-read-date' with the date currently selected.
16916 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16917 (interactive)
16918 (when (calendar-cursor-to-date)
16919 (let* ((date (calendar-cursor-to-date))
16920 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16921 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16922 (when (active-minibuffer-window) (exit-minibuffer))))
16924 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16925 "Insert a date stamp for the date given by the internal TIME.
16926 See `format-time-string' for the format of TIME.
16927 WITH-HM means use the stamp format that includes the time of the day.
16928 INACTIVE means use square brackets instead of angular ones, so that the
16929 stamp will not contribute to the agenda.
16930 PRE and POST are optional strings to be inserted before and after the
16931 stamp.
16932 The command returns the inserted time stamp."
16933 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16934 stamp)
16935 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16936 (insert-before-markers (or pre ""))
16937 (when (listp extra)
16938 (setq extra (car extra))
16939 (if (and (stringp extra)
16940 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16941 (setq extra (format "-%02d:%02d"
16942 (string-to-number (match-string 1 extra))
16943 (string-to-number (match-string 2 extra))))
16944 (setq extra nil)))
16945 (when extra
16946 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16947 (insert-before-markers (setq stamp (format-time-string fmt time)))
16948 (insert-before-markers (or post ""))
16949 (setq org-last-inserted-timestamp stamp)))
16951 (defun org-toggle-time-stamp-overlays ()
16952 "Toggle the use of custom time stamp formats."
16953 (interactive)
16954 (setq org-display-custom-times (not org-display-custom-times))
16955 (unless org-display-custom-times
16956 (let ((p (point-min)) (bmp (buffer-modified-p)))
16957 (while (setq p (next-single-property-change p 'display))
16958 (when (and (get-text-property p 'display)
16959 (eq (get-text-property p 'face) 'org-date))
16960 (remove-text-properties
16961 p (setq p (next-single-property-change p 'display))
16962 '(display t))))
16963 (set-buffer-modified-p bmp)))
16964 (org-restart-font-lock)
16965 (setq org-table-may-need-update t)
16966 (if org-display-custom-times
16967 (message "Time stamps are overlaid with custom format")
16968 (message "Time stamp overlays removed")))
16970 (defun org-display-custom-time (beg end)
16971 "Overlay modified time stamp format over timestamp between BEG and END."
16972 (let* ((ts (buffer-substring beg end))
16973 t1 with-hm tf time str (off 0))
16974 (save-match-data
16975 (setq t1 (org-parse-time-string ts t))
16976 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16977 (setq off (- (match-end 0) (match-beginning 0)))))
16978 (setq end (- end off))
16979 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16980 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16981 time (org-fix-decoded-time t1)
16982 str (org-add-props
16983 (format-time-string
16984 (substring tf 1 -1) (apply 'encode-time time))
16985 nil 'mouse-face 'highlight))
16986 (put-text-property beg end 'display str)))
16988 (defun org-fix-decoded-time (time)
16989 "Set 0 instead of nil for the first 6 elements of time.
16990 Don't touch the rest."
16991 (let ((n 0))
16992 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16994 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16995 "Difference between TIMESTAMP-STRING and now in days.
16996 If SECONDS is non-nil, return the difference in seconds."
16997 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16998 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16999 (funcall fdiff (current-time)))))
17001 (defun org-deadline-close-p (timestamp-string &optional ndays)
17002 "Is the time in TIMESTAMP-STRING close to the current date?"
17003 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17004 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17005 (not (org-entry-is-done-p))))
17007 (defun org-get-wdays (ts &optional delay zero-delay)
17008 "Get the deadline lead time appropriate for timestring TS.
17009 When DELAY is non-nil, get the delay time for scheduled items
17010 instead of the deadline lead time. When ZERO-DELAY is non-nil
17011 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17012 don't try to find the delay cookie in the scheduled timestamp."
17013 (let ((tv (if delay org-scheduled-delay-days
17014 org-deadline-warning-days)))
17015 (cond
17016 ((or (and delay (< tv 0))
17017 (and delay zero-delay (<= tv 0))
17018 (and (not delay) (<= tv 0)))
17019 ;; Enforce this value no matter what
17020 (- tv))
17021 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17022 ;; lead time is specified.
17023 (floor (* (string-to-number (match-string 1 ts))
17024 (cdr (assoc (match-string 2 ts)
17025 '(("d" . 1) ("w" . 7)
17026 ("m" . 30.4) ("y" . 365.25)
17027 ("h" . 0.041667)))))))
17028 ;; go for the default.
17029 (t tv))))
17031 (defun org-calendar-select-mouse (ev)
17032 "Return to `org-read-date' with the date currently selected.
17033 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17034 (interactive "e")
17035 (mouse-set-point ev)
17036 (when (calendar-cursor-to-date)
17037 (let* ((date (calendar-cursor-to-date))
17038 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17039 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17040 (when (active-minibuffer-window) (exit-minibuffer))))
17042 (defun org-check-deadlines (ndays)
17043 "Check if there are any deadlines due or past due.
17044 A deadline is considered due if it happens within `org-deadline-warning-days'
17045 days from today's date. If the deadline appears in an entry marked DONE,
17046 it is not shown. A numeric prefix argument NDAYS can be used to test that
17047 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17048 are shown."
17049 (interactive "P")
17050 (let* ((org-warn-days
17051 (cond
17052 ((equal ndays '(4)) 100000)
17053 (ndays (prefix-numeric-value ndays))
17054 (t (abs org-deadline-warning-days))))
17055 (case-fold-search nil)
17056 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17057 (callback
17058 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17059 (message "%d deadlines past-due or due within %d days"
17060 (org-occur regexp nil callback)
17061 org-warn-days)))
17063 (defsubst org-re-timestamp (type)
17064 "Return a regexp for timestamp TYPE.
17065 Allowed values for TYPE are:
17067 all: all timestamps
17068 active: only active timestamps (<...>)
17069 inactive: only inactive timestamps ([...])
17070 scheduled: only scheduled timestamps
17071 deadline: only deadline timestamps
17072 closed: only closed time-stamps
17074 When TYPE is nil, fall back on returning a regexp that matches
17075 both scheduled and deadline timestamps."
17076 (cl-case type
17077 (all org-ts-regexp-both)
17078 (active org-ts-regexp)
17079 (inactive org-ts-regexp-inactive)
17080 (scheduled org-scheduled-time-regexp)
17081 (deadline org-deadline-time-regexp)
17082 (closed org-closed-time-regexp)
17083 (otherwise
17084 (concat "\\<"
17085 (regexp-opt (list org-deadline-string org-scheduled-string))
17086 " *<\\([^>]+\\)>"))))
17088 (defun org-check-before-date (d)
17089 "Check if there are deadlines or scheduled entries before date D."
17090 (interactive (list (org-read-date)))
17091 (let* ((case-fold-search nil)
17092 (regexp (org-re-timestamp org-ts-type))
17093 (ts-type org-ts-type)
17094 (callback
17095 (lambda ()
17096 (let ((match (match-string 1)))
17097 (and (if (memq ts-type '(active inactive all))
17098 (eq (org-element-type (save-excursion
17099 (backward-char)
17100 (org-element-context)))
17101 'timestamp)
17102 (org-at-planning-p))
17103 (time-less-p
17104 (org-time-string-to-time match)
17105 (org-time-string-to-time d)))))))
17106 (message "%d entries before %s"
17107 (org-occur regexp nil callback)
17108 d)))
17110 (defun org-check-after-date (d)
17111 "Check if there are deadlines or scheduled entries after date D."
17112 (interactive (list (org-read-date)))
17113 (let* ((case-fold-search nil)
17114 (regexp (org-re-timestamp org-ts-type))
17115 (ts-type org-ts-type)
17116 (callback
17117 (lambda ()
17118 (let ((match (match-string 1)))
17119 (and (if (memq ts-type '(active inactive all))
17120 (eq (org-element-type (save-excursion
17121 (backward-char)
17122 (org-element-context)))
17123 'timestamp)
17124 (org-at-planning-p))
17125 (not (time-less-p
17126 (org-time-string-to-time match)
17127 (org-time-string-to-time d))))))))
17128 (message "%d entries after %s"
17129 (org-occur regexp nil callback)
17130 d)))
17132 (defun org-check-dates-range (start-date end-date)
17133 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17134 (interactive (list (org-read-date nil nil nil "Range starts")
17135 (org-read-date nil nil nil "Range end")))
17136 (let ((case-fold-search nil)
17137 (regexp (org-re-timestamp org-ts-type))
17138 (callback
17139 (let ((type org-ts-type))
17140 (lambda ()
17141 (let ((match (match-string 1)))
17142 (and
17143 (if (memq type '(active inactive all))
17144 (eq (org-element-type (save-excursion
17145 (backward-char)
17146 (org-element-context)))
17147 'timestamp)
17148 (org-at-planning-p))
17149 (not (time-less-p
17150 (org-time-string-to-time match)
17151 (org-time-string-to-time start-date)))
17152 (time-less-p
17153 (org-time-string-to-time match)
17154 (org-time-string-to-time end-date))))))))
17155 (message "%d entries between %s and %s"
17156 (org-occur regexp nil callback) start-date end-date)))
17158 (defun org-evaluate-time-range (&optional to-buffer)
17159 "Evaluate a time range by computing the difference between start and end.
17160 Normally the result is just printed in the echo area, but with prefix arg
17161 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17162 If the time range is actually in a table, the result is inserted into the
17163 next column.
17164 For time difference computation, a year is assumed to be exactly 365
17165 days in order to avoid rounding problems."
17166 (interactive "P")
17168 (org-clock-update-time-maybe)
17169 (save-excursion
17170 (unless (org-at-date-range-p t)
17171 (goto-char (point-at-bol))
17172 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17173 (unless (org-at-date-range-p t)
17174 (user-error "Not at a time-stamp range, and none found in current line")))
17175 (let* ((ts1 (match-string 1))
17176 (ts2 (match-string 2))
17177 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17178 (match-end (match-end 0))
17179 (time1 (org-time-string-to-time ts1))
17180 (time2 (org-time-string-to-time ts2))
17181 (t1 (float-time time1))
17182 (t2 (float-time time2))
17183 (diff (abs (- t2 t1)))
17184 (negative (< (- t2 t1) 0))
17185 ;; (ys (floor (* 365 24 60 60)))
17186 (ds (* 24 60 60))
17187 (hs (* 60 60))
17188 (fy "%dy %dd %02d:%02d")
17189 (fy1 "%dy %dd")
17190 (fd "%dd %02d:%02d")
17191 (fd1 "%dd")
17192 (fh "%02d:%02d")
17193 y d h m align)
17194 (if havetime
17195 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17197 d (floor (/ diff ds)) diff (mod diff ds)
17198 h (floor (/ diff hs)) diff (mod diff hs)
17199 m (floor (/ diff 60)))
17200 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17202 d (floor (+ (/ diff ds) 0.5))
17203 h 0 m 0))
17204 (if (not to-buffer)
17205 (message "%s" (org-make-tdiff-string y d h m))
17206 (if (org-at-table-p)
17207 (progn
17208 (goto-char match-end)
17209 (setq align t)
17210 (and (looking-at " *|") (goto-char (match-end 0))))
17211 (goto-char match-end))
17212 (when (looking-at
17213 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17214 (replace-match ""))
17215 (when negative (insert " -"))
17216 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17217 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17218 (insert " " (format fh h m))))
17219 (when align (org-table-align))
17220 (message "Time difference inserted")))))
17222 (defun org-make-tdiff-string (y d h m)
17223 (let ((fmt "")
17224 (l nil))
17225 (when (> y 0)
17226 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17227 (push y l))
17228 (when (> d 0)
17229 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17230 (push d l))
17231 (when (> h 0)
17232 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17233 (push h l))
17234 (when (> m 0)
17235 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17236 (push m l))
17237 (apply 'format fmt (nreverse l))))
17239 (defun org-time-string-to-time (s)
17240 "Convert timestamp string S into internal time."
17241 (apply #'encode-time (org-parse-time-string s)))
17243 (defun org-time-string-to-seconds (s)
17244 "Convert a timestamp string S into a number of seconds."
17245 (float-time (org-time-string-to-time s)))
17247 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17249 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17250 "Convert time stamp S to an absolute day number.
17252 If DAYNR in non-nil, and there is a specifier for a cyclic time
17253 stamp, get the closest date to DAYNR. If PREFER is
17254 `past' (respectively `future') return a date past (respectively
17255 after) or equal to DAYNR.
17257 POS is the location of time stamp S, as a buffer position in
17258 BUFFER.
17260 Diary sexp timestamps are matched against DAYNR, when non-nil.
17261 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17262 signaled."
17263 (cond
17264 ((string-match "\\`%%\\((.*)\\)" s)
17265 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17266 ;; only able to match individual dates. If it fails, raise an
17267 ;; error.
17268 (if (and daynr
17269 (org-diary-sexp-entry
17270 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17271 daynr
17272 (signal 'org-diary-sexp-no-match (list s))))
17273 (daynr (org-closest-date s daynr prefer))
17274 (t (time-to-days
17275 (condition-case errdata
17276 (apply #'encode-time (org-parse-time-string s))
17277 (error (error "Bad timestamp `%s'%s\nError was: %s"
17279 (if (not (and buffer pos)) ""
17280 (format-message " at %d in buffer `%s'" pos buffer))
17281 (cdr errdata))))))))
17283 (defun org-days-to-iso-week (days)
17284 "Return the iso week number."
17285 (require 'cal-iso)
17286 (car (calendar-iso-from-absolute days)))
17288 (defun org-small-year-to-year (year)
17289 "Convert 2-digit years into 4-digit years.
17290 YEAR is expanded into one of the 30 next years, if possible, or
17291 into a past one. Any year larger than 99 is returned unchanged."
17292 (if (>= year 100) year
17293 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17294 (century (/ current 100))
17295 (offset (- year (% current 100))))
17296 (cond ((> offset 30) (+ (* (1- century) 100) year))
17297 ((> offset -70) (+ (* century 100) year))
17298 (t (+ (* (1+ century) 100) year))))))
17300 (defun org-time-from-absolute (d)
17301 "Return the time corresponding to date D.
17302 D may be an absolute day number, or a calendar-type list (month day year)."
17303 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17304 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17306 (defvar org-agenda-current-date)
17307 (defun org-calendar-holiday ()
17308 "List of holidays, for Diary display in Org mode."
17309 (require 'holidays)
17310 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17311 (and hl (mapconcat #'identity hl "; "))))
17313 (defun org-diary-sexp-entry (sexp entry d)
17314 "Process a SEXP diary ENTRY for date D."
17315 (require 'diary-lib)
17316 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17317 ;; dynamically.
17318 (let* ((sexp `(let ((entry ,entry)
17319 (date ',d))
17320 ,(car (read-from-string sexp))))
17321 (result (if calendar-debug-sexp (eval sexp)
17322 (condition-case nil
17323 (eval sexp)
17324 (error
17325 (beep)
17326 (message "Bad sexp at line %d in %s: %s"
17327 (org-current-line)
17328 (buffer-file-name) sexp)
17329 (sleep-for 2))))))
17330 (cond ((stringp result) (split-string result "; "))
17331 ((and (consp result)
17332 (not (consp (cdr result)))
17333 (stringp (cdr result))) (cdr result))
17334 ((and (consp result)
17335 (stringp (car result))) result)
17336 (result entry))))
17338 (defun org-diary-to-ical-string (frombuf)
17339 "Get iCalendar entries from diary entries in buffer FROMBUF.
17340 This uses the icalendar.el library."
17341 (let* ((tmpdir temporary-file-directory)
17342 (tmpfile (make-temp-name
17343 (expand-file-name "orgics" tmpdir)))
17344 buf rtn b e)
17345 (with-current-buffer frombuf
17346 (icalendar-export-region (point-min) (point-max) tmpfile)
17347 (setq buf (find-buffer-visiting tmpfile))
17348 (set-buffer buf)
17349 (goto-char (point-min))
17350 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17351 (setq b (match-beginning 0)))
17352 (goto-char (point-max))
17353 (when (re-search-backward "^END:VEVENT" nil t)
17354 (setq e (match-end 0)))
17355 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17356 (kill-buffer buf)
17357 (delete-file tmpfile)
17358 rtn))
17360 (defun org-closest-date (start current prefer)
17361 "Return closest date to CURRENT starting from START.
17363 CURRENT and START are both time stamps.
17365 When PREFER is `past', return a date that is either CURRENT or
17366 past. When PREFER is `future', return a date that is either
17367 CURRENT or future.
17369 Only time stamps with a repeater are modified. Any other time
17370 stamp stay unchanged. In any case, return value is an absolute
17371 day number."
17372 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17373 ;; No repeater. Do not shift time stamp.
17374 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17375 (let ((value (string-to-number (match-string 1 start)))
17376 (type (match-string 2 start)))
17377 (if (= 0 value)
17378 ;; Repeater with a 0-value is considered as void.
17379 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17380 (let* ((base (org-date-to-gregorian start))
17381 (target (org-date-to-gregorian current))
17382 (sday (calendar-absolute-from-gregorian base))
17383 (cday (calendar-absolute-from-gregorian target))
17384 n1 n2)
17385 ;; If START is already past CURRENT, just return START.
17386 (if (<= cday sday) sday
17387 ;; Compute closest date before (N1) and closest date past
17388 ;; (N2) CURRENT.
17389 (pcase type
17390 ("h"
17391 (let ((missing-hours
17392 (mod (+ (- (* 24 (- cday sday))
17393 (nth 2 (org-parse-time-string start)))
17394 org-extend-today-until)
17395 value)))
17396 (setf n1 (if (= missing-hours 0) cday
17397 (- cday (1+ (/ missing-hours 24)))))
17398 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17399 ((or "d" "w")
17400 (let ((value (if (equal type "w") (* 7 value) value)))
17401 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17402 (setf n2 (+ n1 value))))
17403 ("m"
17404 (let* ((add-months
17405 (lambda (d n)
17406 ;; Add N months to gregorian date D, i.e.,
17407 ;; a list (MONTH DAY YEAR). Return a valid
17408 ;; gregorian date.
17409 (let ((m (+ (nth 0 d) n)))
17410 (list (mod m 12)
17411 (nth 1 d)
17412 (+ (/ m 12) (nth 2 d))))))
17413 (months ; Complete months to TARGET.
17414 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17415 (- (nth 0 target) (nth 0 base))
17416 ;; If START's day is greater than
17417 ;; TARGET's, remove incomplete month.
17418 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17419 value)
17420 value))
17421 (before (funcall add-months base months)))
17422 (setf n1 (calendar-absolute-from-gregorian before))
17423 (setf n2
17424 (calendar-absolute-from-gregorian
17425 (funcall add-months before value)))))
17427 (let* ((d (nth 1 base))
17428 (m (nth 0 base))
17429 (y (nth 2 base))
17430 (years ; Complete years to TARGET.
17431 (* (/ (- (nth 2 target)
17433 ;; If START's month and day are
17434 ;; greater than TARGET's, remove
17435 ;; incomplete year.
17436 (if (or (> (nth 0 target) m)
17437 (and (= (nth 0 target) m)
17438 (> (nth 1 target) d)))
17441 value)
17442 value))
17443 (before (list m d (+ y years))))
17444 (setf n1 (calendar-absolute-from-gregorian before))
17445 (setf n2 (calendar-absolute-from-gregorian
17446 (list m d (+ (nth 2 before) value)))))))
17447 ;; Handle PREFER parameter, if any.
17448 (cond
17449 ((eq prefer 'past) (if (= cday n2) n2 n1))
17450 ((eq prefer 'future) (if (= cday n1) n1 n2))
17451 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17453 (defun org-date-to-gregorian (d)
17454 "Turn any specification of date D into a Gregorian date for the calendar."
17455 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17456 ((and (listp d) (= (length d) 3)) d)
17457 ((stringp d)
17458 (let ((d (org-parse-time-string d)))
17459 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17460 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17462 (defun org-parse-time-string (s &optional nodefault)
17463 "Parse the standard Org time string.
17465 This should be a lot faster than the normal `parse-time-string'.
17467 If time is not given, defaults to 0:00. However, with optional
17468 NODEFAULT, hour and minute fields will be nil if not given."
17469 (cond ((string-match org-ts-regexp0 s)
17470 (list 0
17471 (when (or (match-beginning 8) (not nodefault))
17472 (string-to-number (or (match-string 8 s) "0")))
17473 (when (or (match-beginning 7) (not nodefault))
17474 (string-to-number (or (match-string 7 s) "0")))
17475 (string-to-number (match-string 4 s))
17476 (string-to-number (match-string 3 s))
17477 (string-to-number (match-string 2 s))
17478 nil nil nil))
17479 ((string-match "^<[^>]+>$" s)
17480 ;; FIXME: `decode-time' needs to be called with ZONE as its
17481 ;; second argument. However, this requires at least Emacs
17482 ;; 25.1. We can do it when we switch to this version as our
17483 ;; minimal requirement.
17484 (decode-time (seconds-to-time (org-matcher-time s))))
17485 (t (error "Not a standard Org time string: %s" s))))
17487 (defun org-timestamp-up (&optional arg)
17488 "Increase the date item at the cursor by one.
17489 If the cursor is on the year, change the year. If it is on the month,
17490 the day or the time, change that.
17491 With prefix ARG, change by that many units."
17492 (interactive "p")
17493 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17495 (defun org-timestamp-down (&optional arg)
17496 "Decrease the date item at the cursor by one.
17497 If the cursor is on the year, change the year. If it is on the month,
17498 the day or the time, change that.
17499 With prefix ARG, change by that many units."
17500 (interactive "p")
17501 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17503 (defun org-timestamp-up-day (&optional arg)
17504 "Increase the date in the time stamp by one day.
17505 With prefix ARG, change that many days."
17506 (interactive "p")
17507 (if (and (not (org-at-timestamp-p 'lax))
17508 (org-at-heading-p))
17509 (org-todo 'up)
17510 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17512 (defun org-timestamp-down-day (&optional arg)
17513 "Decrease the date in the time stamp by one day.
17514 With prefix ARG, change that many days."
17515 (interactive "p")
17516 (if (and (not (org-at-timestamp-p 'lax))
17517 (org-at-heading-p))
17518 (org-todo 'down)
17519 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17521 (defun org-at-timestamp-p (&optional extended)
17522 "Non-nil if point is inside a timestamp.
17524 By default, the function only consider syntactically valid active
17525 timestamps. However, the caller may have a broader definition
17526 for timestamps. As a consequence, optional argument EXTENDED can
17527 be set to the following values
17529 `inactive'
17531 Include also syntactically valid inactive timestamps.
17533 `agenda'
17535 Include timestamps allowed in Agenda, i.e., those in
17536 properties drawers, planning lines and clock lines.
17538 `lax'
17540 Ignore context. The function matches any part of the
17541 document looking like a timestamp. This includes comments,
17542 example blocks...
17544 For backward-compatibility with Org 9.0, every other non-nil
17545 value is equivalent to `inactive'.
17547 When at a timestamp, return the position of the point as a symbol
17548 among `bracket', `after', `year', `month', `hour', `minute',
17549 `day' or a number of character from the last know part of the
17550 time stamp.
17552 When matching, the match groups are the following:
17553 group 1: year
17554 group 2: month
17555 group 3: day number
17556 group 4: day name
17557 group 5: hours, if any
17558 group 6: minutes, if any"
17559 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17560 (pos (point))
17561 (match?
17562 (let ((boundaries (org-in-regexp regexp)))
17563 (save-match-data
17564 (cond ((null boundaries) nil)
17565 ((eq extended 'lax) t)
17567 (or (and (eq extended 'agenda)
17568 (or (org-at-planning-p)
17569 (org-at-property-p)
17570 (and (bound-and-true-p
17571 org-agenda-include-inactive-timestamps)
17572 (org-at-clock-log-p))))
17573 (eq 'timestamp
17574 (save-excursion
17575 (when (= pos (cdr boundaries)) (forward-char -1))
17576 (org-element-type (org-element-context)))))))))))
17577 (cond
17578 ((not match?) nil)
17579 ((= pos (match-beginning 0)) 'bracket)
17580 ;; Distinguish location right before the closing bracket from
17581 ;; right after it.
17582 ((= pos (1- (match-end 0))) 'bracket)
17583 ((= pos (match-end 0)) 'after)
17584 ((org-pos-in-match-range pos 2) 'year)
17585 ((org-pos-in-match-range pos 3) 'month)
17586 ((org-pos-in-match-range pos 7) 'hour)
17587 ((org-pos-in-match-range pos 8) 'minute)
17588 ((or (org-pos-in-match-range pos 4)
17589 (org-pos-in-match-range pos 5)) 'day)
17590 ((and (> pos (or (match-end 8) (match-end 5)))
17591 (< pos (match-end 0)))
17592 (- pos (or (match-end 8) (match-end 5))))
17593 (t 'day))))
17595 (defun org-toggle-timestamp-type ()
17596 "Toggle the type (<active> or [inactive]) of a time stamp."
17597 (interactive)
17598 (when (org-at-timestamp-p 'lax)
17599 (let ((beg (match-beginning 0)) (end (match-end 0))
17600 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17601 (save-excursion
17602 (goto-char beg)
17603 (while (re-search-forward "[][<>]" end t)
17604 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17605 t t)))
17606 (message "Timestamp is now %sactive"
17607 (if (equal (char-after beg) ?<) "" "in")))))
17609 (defun org-at-clock-log-p ()
17610 "Non-nil if point is on a clock log line."
17611 (and (org-match-line org-clock-line-re)
17612 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17614 (defvar org-clock-history) ; defined in org-clock.el
17615 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17616 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17617 "Change the date in the time stamp at point.
17618 The date will be changed by N times WHAT. WHAT can be `day', `month',
17619 `year', `minute', `second'. If WHAT is not given, the cursor position
17620 in the timestamp determines what will be changed.
17621 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17622 (let ((origin (point))
17623 (timestamp? (org-at-timestamp-p 'lax))
17624 origin-cat
17625 with-hm inactive
17626 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17627 extra rem
17628 ts time time0 fixnext clrgx)
17629 (unless timestamp? (user-error "Not at a timestamp"))
17630 (if (and (not what) (eq timestamp? 'bracket))
17631 (org-toggle-timestamp-type)
17632 ;; Point isn't on brackets. Remember the part of the time-stamp
17633 ;; the point was in. Indeed, size of time-stamps may change,
17634 ;; but point must be kept in the same category nonetheless.
17635 (setq origin-cat timestamp?)
17636 (when (and (not what) (not (eq timestamp? 'day))
17637 org-display-custom-times
17638 (get-text-property (point) 'display)
17639 (not (get-text-property (1- (point)) 'display)))
17640 (setq timestamp? 'day))
17641 (setq timestamp? (or what timestamp?)
17642 inactive (= (char-after (match-beginning 0)) ?\[)
17643 ts (match-string 0))
17644 (replace-match "")
17645 (when (string-match
17646 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17648 (setq extra (match-string 1 ts))
17649 (when suppress-tmp-delay
17650 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17651 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17652 (setq with-hm t))
17653 (setq time0 (org-parse-time-string ts))
17654 (when (and updown
17655 (eq timestamp? 'minute)
17656 (not current-prefix-arg))
17657 ;; This looks like s-up and s-down. Change by one rounding step.
17658 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17659 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17660 (setcar (cdr time0) (+ (nth 1 time0)
17661 (if (> n 0) (- rem) (- dm rem))))))
17662 (setq time
17663 (apply #'encode-time
17664 (or (car time0) 0)
17665 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17666 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17667 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17668 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17669 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17670 (nthcdr 6 time0)))
17671 (when (and (memq timestamp? '(hour minute))
17672 extra
17673 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17674 (setq extra (org-modify-ts-extra
17675 extra
17676 (if (eq timestamp? 'hour) 2 5)
17677 n dm)))
17678 (when (integerp timestamp?)
17679 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17680 (when (eq what 'calendar)
17681 (let ((cal-date (org-get-date-from-calendar)))
17682 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17683 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17684 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17685 (setcar time0 (or (car time0) 0))
17686 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17687 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17688 (setq time (apply 'encode-time time0))))
17689 ;; Insert the new time-stamp, and ensure point stays in the same
17690 ;; category as before (i.e. not after the last position in that
17691 ;; category).
17692 (let ((pos (point)))
17693 ;; Stay before inserted string. `save-excursion' is of no use.
17694 (setq org-last-changed-timestamp
17695 (org-insert-time-stamp time with-hm inactive nil nil extra))
17696 (goto-char pos))
17697 (save-match-data
17698 (looking-at org-ts-regexp3)
17699 (goto-char
17700 (pcase origin-cat
17701 ;; `day' category ends before `hour' if any, or at the end
17702 ;; of the day name.
17703 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17704 (`hour (min (match-end 7) origin))
17705 (`minute (min (1- (match-end 8)) origin))
17706 ((pred integerp) (min (1- (match-end 0)) origin))
17707 ;; Point was right after the time-stamp. However, the
17708 ;; time-stamp length might have changed, so refer to
17709 ;; (match-end 0) instead.
17710 (`after (match-end 0))
17711 ;; `year' and `month' have both fixed size: point couldn't
17712 ;; have moved into another part.
17713 (_ origin))))
17714 ;; Update clock if on a CLOCK line.
17715 (org-clock-update-time-maybe)
17716 ;; Maybe adjust the closest clock in `org-clock-history'
17717 (when org-clock-adjust-closest
17718 (if (not (and (org-at-clock-log-p)
17719 (< 1 (length (delq nil (mapcar 'marker-position
17720 org-clock-history))))))
17721 (message "No clock to adjust")
17722 (cond ((save-excursion ; fix previous clock?
17723 (re-search-backward org-ts-regexp0 nil t)
17724 (looking-back (concat org-clock-string " \\[")
17725 (line-beginning-position)))
17726 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17727 ((save-excursion ; fix next clock?
17728 (re-search-backward org-ts-regexp0 nil t)
17729 (looking-at (concat org-ts-regexp0 "\\] =>")))
17730 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17731 (save-window-excursion
17732 ;; Find closest clock to point, adjust the previous/next one in history
17733 (let* ((p (save-excursion (org-back-to-heading t)))
17734 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17735 (clfixnth
17736 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17737 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17738 (if (not clfixpos)
17739 (message "No clock to adjust")
17740 (save-excursion
17741 (org-goto-marker-or-bmk clfixpos)
17742 (org-show-subtree)
17743 (when (re-search-forward clrgx nil t)
17744 (goto-char (match-beginning 1))
17745 (let (org-clock-adjust-closest)
17746 (org-timestamp-change n timestamp? updown))
17747 (message "Clock adjusted in %s for heading: %s"
17748 (file-name-nondirectory (buffer-file-name))
17749 (org-get-heading t t)))))))))
17750 ;; Try to recenter the calendar window, if any.
17751 (when (and org-calendar-follow-timestamp-change
17752 (get-buffer-window "*Calendar*" t)
17753 (memq timestamp? '(day month year)))
17754 (org-recenter-calendar (time-to-days time))))))
17756 (defun org-modify-ts-extra (s pos n dm)
17757 "Change the different parts of the lead-time and repeat fields in timestamp."
17758 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17759 ng h m new rem)
17760 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17761 (cond
17762 ((or (org-pos-in-match-range pos 2)
17763 (org-pos-in-match-range pos 3))
17764 (setq m (string-to-number (match-string 3 s))
17765 h (string-to-number (match-string 2 s)))
17766 (if (org-pos-in-match-range pos 2)
17767 (setq h (+ h n))
17768 (setq n (* dm (with-no-warnings (signum n))))
17769 (unless (= 0 (setq rem (% m dm)))
17770 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17771 (setq m (+ m n)))
17772 (when (< m 0) (setq m (+ m 60) h (1- h)))
17773 (when (> m 59) (setq m (- m 60) h (1+ h)))
17774 (setq h (mod h 24))
17775 (setq ng 1 new (format "-%02d:%02d" h m)))
17776 ((org-pos-in-match-range pos 6)
17777 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17778 ((org-pos-in-match-range pos 5)
17779 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17781 ((org-pos-in-match-range pos 9)
17782 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17783 ((org-pos-in-match-range pos 8)
17784 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17786 (when ng
17787 (setq s (concat
17788 (substring s 0 (match-beginning ng))
17790 (substring s (match-end ng))))))
17793 (defun org-recenter-calendar (d)
17794 "If the calendar is visible, recenter it to date D."
17795 (let ((cwin (get-buffer-window "*Calendar*" t)))
17796 (when cwin
17797 (let ((calendar-move-hook nil))
17798 (with-selected-window cwin
17799 (calendar-goto-date
17800 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17802 (defun org-goto-calendar (&optional arg)
17803 "Go to the Emacs calendar at the current date.
17804 If there is a time stamp in the current line, go to that date.
17805 A prefix ARG can be used to force the current date."
17806 (interactive "P")
17807 (let ((calendar-move-hook nil)
17808 (calendar-view-holidays-initially-flag nil)
17809 (calendar-view-diary-initially-flag nil)
17810 diff)
17811 (when (or (org-at-timestamp-p 'lax)
17812 (org-match-line (concat ".*" org-ts-regexp)))
17813 (let ((d1 (time-to-days (current-time)))
17814 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17815 (setq diff (- d2 d1))))
17816 (calendar)
17817 (calendar-goto-today)
17818 (when (and diff (not arg)) (calendar-forward-day diff))))
17820 (defun org-get-date-from-calendar ()
17821 "Return a list (month day year) of date at point in calendar."
17822 (with-current-buffer "*Calendar*"
17823 (save-match-data
17824 (calendar-cursor-to-date))))
17826 (defun org-date-from-calendar ()
17827 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17828 If there is already a time stamp at the cursor position, update it."
17829 (interactive)
17830 (if (org-at-timestamp-p 'lax)
17831 (org-timestamp-change 0 'calendar)
17832 (let ((cal-date (org-get-date-from-calendar)))
17833 (org-insert-time-stamp
17834 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17836 (defcustom org-effort-durations
17837 `(("min" . 1)
17838 ("h" . 60)
17839 ("d" . ,(* 60 8))
17840 ("w" . ,(* 60 8 5))
17841 ("m" . ,(* 60 8 5 4))
17842 ("y" . ,(* 60 8 5 40)))
17843 "Conversion factor to minutes for an effort modifier.
17845 Each entry has the form (MODIFIER . MINUTES).
17847 In an effort string, a number followed by MODIFIER is multiplied
17848 by the specified number of MINUTES to obtain an effort in
17849 minutes.
17851 For example, if the value of this variable is ((\"hours\" . 60)), then an
17852 effort string \"2hours\" is equivalent to 120 minutes."
17853 :group 'org-agenda
17854 :version "26.1"
17855 :package-version '(Org . "8.3")
17856 :type '(alist :key-type (string :tag "Modifier")
17857 :value-type (number :tag "Minutes")))
17859 (defcustom org-image-actual-width t
17860 "Should we use the actual width of images when inlining them?
17862 When set to t, always use the image width.
17864 When set to a number, use imagemagick (when available) to set
17865 the image's width to this value.
17867 When set to a number in a list, try to get the width from any
17868 #+ATTR.* keyword if it matches a width specification like
17870 #+ATTR_HTML: :width 300px
17872 and fall back on that number if none is found.
17874 When set to nil, try to get the width from an #+ATTR.* keyword
17875 and fall back on the original width if none is found.
17877 This requires Emacs >= 24.1, build with imagemagick support."
17878 :group 'org-appearance
17879 :version "24.4"
17880 :package-version '(Org . "8.0")
17881 :type '(choice
17882 (const :tag "Use the image width" t)
17883 (integer :tag "Use a number of pixels")
17884 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17885 (const :tag "Use #+ATTR* or don't resize" nil)))
17887 (defcustom org-agenda-inhibit-startup nil
17888 "Inhibit startup when preparing agenda buffers.
17889 When this variable is t, the initialization of the Org agenda
17890 buffers is inhibited: e.g. the visibility state is not set, the
17891 tables are not re-aligned, etc."
17892 :type 'boolean
17893 :version "24.3"
17894 :group 'org-agenda)
17896 (defcustom org-agenda-ignore-properties nil
17897 "Avoid updating text properties when building the agenda.
17898 Properties are used to prepare buffers for effort estimates,
17899 appointments, statistics and subtree-local categories.
17900 If you don't use these in the agenda, you can add them to this
17901 list and agenda building will be a bit faster.
17902 The value is a list, with zero or more of the symbols `effort', `appt',
17903 `stats' or `category'."
17904 :type '(set :greedy t
17905 (const effort)
17906 (const appt)
17907 (const stats)
17908 (const category))
17909 :version "26.1"
17910 :package-version '(Org . "8.3")
17911 :group 'org-agenda)
17913 ;;;; Files
17915 (defun org-save-all-org-buffers ()
17916 "Save all Org buffers without user confirmation."
17917 (interactive)
17918 (message "Saving all Org buffers...")
17919 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17920 (when (featurep 'org-id) (org-id-locations-save))
17921 (message "Saving all Org buffers... done"))
17923 (defun org-revert-all-org-buffers ()
17924 "Revert all Org buffers.
17925 Prompt for confirmation when there are unsaved changes.
17926 Be sure you know what you are doing before letting this function
17927 overwrite your changes.
17929 This function is useful in a setup where one tracks org files
17930 with a version control system, to revert on one machine after pulling
17931 changes from another. I believe the procedure must be like this:
17933 1. M-x org-save-all-org-buffers
17934 2. Pull changes from the other machine, resolve conflicts
17935 3. M-x org-revert-all-org-buffers"
17936 (interactive)
17937 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17938 (user-error "Abort"))
17939 (save-excursion
17940 (save-window-excursion
17941 (dolist (b (buffer-list))
17942 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17943 (with-current-buffer b buffer-file-name))
17944 (pop-to-buffer-same-window b)
17945 (revert-buffer t 'no-confirm)))
17946 (when (and (featurep 'org-id) org-id-track-globally)
17947 (org-id-locations-load)))))
17949 ;;;; Agenda files
17951 ;;;###autoload
17952 (defun org-switchb (&optional arg)
17953 "Switch between Org buffers.
17955 With `\\[universal-argument]' prefix, restrict available buffers to files.
17957 With `\\[universal-argument] \\[universal-argument]' \
17958 prefix, restrict available buffers to agenda files."
17959 (interactive "P")
17960 (let ((blist (org-buffer-list
17961 (cond ((equal arg '(4)) 'files)
17962 ((equal arg '(16)) 'agenda)))))
17963 (pop-to-buffer-same-window
17964 (completing-read "Org buffer: "
17965 (mapcar #'list (mapcar #'buffer-name blist))
17966 nil t))))
17968 (defun org-buffer-list (&optional predicate exclude-tmp)
17969 "Return a list of Org buffers.
17970 PREDICATE can be `export', `files' or `agenda'.
17972 export restrict the list to Export buffers.
17973 files restrict the list to buffers visiting Org files.
17974 agenda restrict the list to buffers visiting agenda files.
17976 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17977 (let* ((bfn nil)
17978 (agenda-files (and (eq predicate 'agenda)
17979 (mapcar 'file-truename (org-agenda-files t))))
17980 (filter
17981 (cond
17982 ((eq predicate 'files)
17983 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17984 ((eq predicate 'export)
17985 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17986 ((eq predicate 'agenda)
17987 (lambda (b)
17988 (with-current-buffer b
17989 (and (derived-mode-p 'org-mode)
17990 (setq bfn (buffer-file-name b))
17991 (member (file-truename bfn) agenda-files)))))
17992 (t (lambda (b) (with-current-buffer b
17993 (or (derived-mode-p 'org-mode)
17994 (string-match "\\*Org .*Export"
17995 (buffer-name b)))))))))
17996 (delq nil
17997 (mapcar
17998 (lambda(b)
17999 (if (and (funcall filter b)
18000 (or (not exclude-tmp)
18001 (not (string-match "tmp" (buffer-name b)))))
18003 nil))
18004 (buffer-list)))))
18006 (defun org-agenda-files (&optional unrestricted archives)
18007 "Get the list of agenda files.
18008 Optional UNRESTRICTED means return the full list even if a restriction
18009 is currently in place.
18010 When ARCHIVES is t, include all archive files that are really being
18011 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18012 `org-agenda-archives-mode' is t."
18013 (let ((files
18014 (cond
18015 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18016 ((stringp org-agenda-files) (org-read-agenda-file-list))
18017 ((listp org-agenda-files) org-agenda-files)
18018 (t (error "Invalid value of `org-agenda-files'")))))
18019 (setq files (apply 'append
18020 (mapcar (lambda (f)
18021 (if (file-directory-p f)
18022 (directory-files
18023 f t org-agenda-file-regexp)
18024 (list f)))
18025 files)))
18026 (when org-agenda-skip-unavailable-files
18027 (setq files (delq nil
18028 (mapcar (function
18029 (lambda (file)
18030 (and (file-readable-p file) file)))
18031 files))))
18032 (when (or (eq archives t)
18033 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18034 (setq files (org-add-archive-files files)))
18035 files))
18037 (defun org-agenda-file-p (&optional file)
18038 "Return non-nil, if FILE is an agenda file.
18039 If FILE is omitted, use the file associated with the current
18040 buffer."
18041 (let ((fname (or file (buffer-file-name))))
18042 (and fname
18043 (member (file-truename fname)
18044 (mapcar #'file-truename (org-agenda-files t))))))
18046 (defun org-edit-agenda-file-list ()
18047 "Edit the list of agenda files.
18048 Depending on setup, this either uses customize to edit the variable
18049 `org-agenda-files', or it visits the file that is holding the list. In the
18050 latter case, the buffer is set up in a way that saving it automatically kills
18051 the buffer and restores the previous window configuration."
18052 (interactive)
18053 (if (stringp org-agenda-files)
18054 (let ((cw (current-window-configuration)))
18055 (find-file org-agenda-files)
18056 (setq-local org-window-configuration cw)
18057 (add-hook 'after-save-hook
18058 (lambda ()
18059 (set-window-configuration
18060 (prog1 org-window-configuration
18061 (kill-buffer (current-buffer))))
18062 (org-install-agenda-files-menu)
18063 (message "New agenda file list installed"))
18064 nil 'local)
18065 (message "%s" (substitute-command-keys
18066 "Edit list and finish with \\[save-buffer]")))
18067 (customize-variable 'org-agenda-files)))
18069 (defun org-store-new-agenda-file-list (list)
18070 "Set new value for the agenda file list and save it correctly."
18071 (if (stringp org-agenda-files)
18072 (let ((fe (org-read-agenda-file-list t)) b u)
18073 (while (setq b (find-buffer-visiting org-agenda-files))
18074 (kill-buffer b))
18075 (with-temp-file org-agenda-files
18076 (insert
18077 (mapconcat
18078 (lambda (f) ;; Keep un-expanded entries.
18079 (if (setq u (assoc f fe))
18080 (cdr u)
18082 list "\n")
18083 "\n")))
18084 (let ((org-mode-hook nil) (org-inhibit-startup t)
18085 (org-insert-mode-line-in-empty-file nil))
18086 (setq org-agenda-files list)
18087 (customize-save-variable 'org-agenda-files org-agenda-files))))
18089 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18090 "Read the list of agenda files from a file.
18091 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18092 filenames, used by `org-store-new-agenda-file-list' to write back
18093 un-expanded file names."
18094 (when (file-directory-p org-agenda-files)
18095 (error "`org-agenda-files' cannot be a single directory"))
18096 (when (stringp org-agenda-files)
18097 (with-temp-buffer
18098 (insert-file-contents org-agenda-files)
18099 (mapcar
18100 (lambda (f)
18101 (let ((e (expand-file-name (substitute-in-file-name f)
18102 org-directory)))
18103 (if pair-with-expansion
18104 (cons e f)
18105 e)))
18106 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18108 ;;;###autoload
18109 (defun org-cycle-agenda-files ()
18110 "Cycle through the files in `org-agenda-files'.
18111 If the current buffer visits an agenda file, find the next one in the list.
18112 If the current buffer does not, find the first agenda file."
18113 (interactive)
18114 (let* ((fs (or (org-agenda-files t)
18115 (user-error "No agenda files")))
18116 (files (copy-sequence fs))
18117 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18118 file)
18119 (when tcf
18120 (while (and (setq file (pop files))
18121 (not (equal (file-truename file) tcf)))))
18122 (find-file (car (or files fs)))
18123 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18125 (defun org-agenda-file-to-front (&optional to-end)
18126 "Move/add the current file to the top of the agenda file list.
18127 If the file is not present in the list, it is added to the front. If it is
18128 present, it is moved there. With optional argument TO-END, add/move to the
18129 end of the list."
18130 (interactive "P")
18131 (let ((org-agenda-skip-unavailable-files nil)
18132 (file-alist (mapcar (lambda (x)
18133 (cons (file-truename x) x))
18134 (org-agenda-files t)))
18135 (ctf (file-truename
18136 (or buffer-file-name
18137 (user-error "Please save the current buffer to a file"))))
18138 x had)
18139 (setq x (assoc ctf file-alist) had x)
18141 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18142 (if to-end
18143 (setq file-alist (append (delq x file-alist) (list x)))
18144 (setq file-alist (cons x (delq x file-alist))))
18145 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18146 (org-install-agenda-files-menu)
18147 (message "File %s to %s of agenda file list"
18148 (if had "moved" "added") (if to-end "end" "front"))))
18150 (defun org-remove-file (&optional file)
18151 "Remove current file from the list of files in variable `org-agenda-files'.
18152 These are the files which are being checked for agenda entries.
18153 Optional argument FILE means use this file instead of the current."
18154 (interactive)
18155 (let* ((org-agenda-skip-unavailable-files nil)
18156 (file (or file buffer-file-name
18157 (user-error "Current buffer does not visit a file")))
18158 (true-file (file-truename file))
18159 (afile (abbreviate-file-name file))
18160 (files (delq nil (mapcar
18161 (lambda (x)
18162 (unless (equal true-file
18163 (file-truename x))
18165 (org-agenda-files t)))))
18166 (if (not (= (length files) (length (org-agenda-files t))))
18167 (progn
18168 (org-store-new-agenda-file-list files)
18169 (org-install-agenda-files-menu)
18170 (message "Removed from Org Agenda list: %s" afile))
18171 (message "File was not in list: %s (not removed)" afile))))
18173 (defun org-file-menu-entry (file)
18174 (vector file (list 'find-file file) t))
18176 (defun org-check-agenda-file (file)
18177 "Make sure FILE exists. If not, ask user what to do."
18178 (unless (file-exists-p file)
18179 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18180 (abbreviate-file-name file))
18181 (let ((r (downcase (read-char-exclusive))))
18182 (cond
18183 ((equal r ?r)
18184 (org-remove-file file)
18185 (throw 'nextfile t))
18186 (t (user-error "Abort"))))))
18188 (defun org-get-agenda-file-buffer (file)
18189 "Get an agenda buffer visiting FILE.
18190 If the buffer needs to be created, add it to the list of buffers
18191 which might be released later."
18192 (let ((buf (org-find-base-buffer-visiting file)))
18193 (if buf
18194 buf ; just return it
18195 ;; Make a new buffer and remember it
18196 (setq buf (find-file-noselect file))
18197 (when buf (push buf org-agenda-new-buffers))
18198 buf)))
18200 (defun org-release-buffers (blist)
18201 "Release all buffers in list, asking the user for confirmation when needed.
18202 When a buffer is unmodified, it is just killed. When modified, it is saved
18203 \(if the user agrees) and then killed."
18204 (let (file)
18205 (dolist (buf blist)
18206 (setq file (buffer-file-name buf))
18207 (when (and (buffer-modified-p buf)
18208 file
18209 (y-or-n-p (format "Save file %s? " file)))
18210 (with-current-buffer buf (save-buffer)))
18211 (kill-buffer buf))))
18213 (defun org-agenda-prepare-buffers (files)
18214 "Create buffers for all agenda files, protect archived trees and comments."
18215 (interactive)
18216 (let ((pa '(:org-archived t))
18217 (pc '(:org-comment t))
18218 (pall '(:org-archived t :org-comment t))
18219 (inhibit-read-only t)
18220 (org-inhibit-startup org-agenda-inhibit-startup)
18221 (rea (concat ":" org-archive-tag ":"))
18222 re pos)
18223 (setq org-tag-alist-for-agenda nil
18224 org-tag-groups-alist-for-agenda nil)
18225 (save-excursion
18226 (save-restriction
18227 (dolist (file files)
18228 (catch 'nextfile
18229 (if (bufferp file)
18230 (set-buffer file)
18231 (org-check-agenda-file file)
18232 (set-buffer (org-get-agenda-file-buffer file)))
18233 (widen)
18234 (org-set-regexps-and-options 'tags-only)
18235 (setq pos (point))
18236 (or (memq 'category org-agenda-ignore-properties)
18237 (org-refresh-category-properties))
18238 (or (memq 'stats org-agenda-ignore-properties)
18239 (org-refresh-stats-properties))
18240 (or (memq 'effort org-agenda-ignore-properties)
18241 (org-refresh-effort-properties))
18242 (or (memq 'appt org-agenda-ignore-properties)
18243 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18244 (setq org-todo-keywords-for-agenda
18245 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18246 (setq org-done-keywords-for-agenda
18247 (append org-done-keywords-for-agenda org-done-keywords))
18248 (setq org-todo-keyword-alist-for-agenda
18249 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18250 (setq org-tag-alist-for-agenda
18251 (org-uniquify
18252 (append org-tag-alist-for-agenda
18253 org-current-tag-alist)))
18254 ;; Merge current file's tag groups into global
18255 ;; `org-tag-groups-alist-for-agenda'.
18256 (when org-group-tags
18257 (dolist (alist org-tag-groups-alist)
18258 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18259 (if old
18260 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18261 (push alist org-tag-groups-alist-for-agenda)))))
18262 (org-with-silent-modifications
18263 (save-excursion
18264 (remove-text-properties (point-min) (point-max) pall)
18265 (when org-agenda-skip-archived-trees
18266 (goto-char (point-min))
18267 (while (re-search-forward rea nil t)
18268 (when (org-at-heading-p t)
18269 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18270 (goto-char (point-min))
18271 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18272 (while (re-search-forward re nil t)
18273 (when (save-match-data (org-in-commented-heading-p t))
18274 (add-text-properties
18275 (match-beginning 0) (org-end-of-subtree t) pc)))))
18276 (goto-char pos)))))
18277 (setq org-todo-keywords-for-agenda
18278 (org-uniquify org-todo-keywords-for-agenda))
18279 (setq org-todo-keyword-alist-for-agenda
18280 (org-uniquify org-todo-keyword-alist-for-agenda))))
18283 ;;;; CDLaTeX minor mode
18285 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18286 "Keymap for the minor `org-cdlatex-mode'.")
18288 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18289 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18290 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18291 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18292 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18294 (defvar org-cdlatex-texmathp-advice-is-done nil
18295 "Flag remembering if we have applied the advice to texmathp already.")
18297 (define-minor-mode org-cdlatex-mode
18298 "Toggle the minor `org-cdlatex-mode'.
18299 This mode supports entering LaTeX environment and math in LaTeX fragments
18300 in Org mode.
18301 \\{org-cdlatex-mode-map}"
18302 nil " OCDL" nil
18303 (when org-cdlatex-mode
18304 (require 'cdlatex)
18305 (run-hooks 'cdlatex-mode-hook)
18306 (cdlatex-compute-tables))
18307 (unless org-cdlatex-texmathp-advice-is-done
18308 (setq org-cdlatex-texmathp-advice-is-done t)
18309 (defadvice texmathp (around org-math-always-on activate)
18310 "Always return t in Org buffers.
18311 This is because we want to insert math symbols without dollars even outside
18312 the LaTeX math segments. If Org mode thinks that point is actually inside
18313 an embedded LaTeX fragment, let `texmathp' do its job.
18314 `\\[org-cdlatex-mode-map]'"
18315 (interactive)
18316 (let (p)
18317 (cond
18318 ((not (derived-mode-p 'org-mode)) ad-do-it)
18319 ((eq this-command 'cdlatex-math-symbol)
18320 (setq ad-return-value t
18321 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18323 (let ((p (org-inside-LaTeX-fragment-p)))
18324 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18325 (setq ad-return-value t
18326 texmathp-why '("Org mode embedded math" . 0))
18327 (when p ad-do-it)))))))))
18329 (defun turn-on-org-cdlatex ()
18330 "Unconditionally turn on `org-cdlatex-mode'."
18331 (org-cdlatex-mode 1))
18333 (defun org-try-cdlatex-tab ()
18334 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18335 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18336 - inside a LaTeX fragment, or
18337 - after the first word in a line, where an abbreviation expansion could
18338 insert a LaTeX environment."
18339 (when org-cdlatex-mode
18340 (cond
18341 ;; Before any word on the line: No expansion possible.
18342 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18343 ;; Just after first word on the line: Expand it. Make sure it
18344 ;; cannot happen on headlines, though.
18345 ((save-excursion
18346 (skip-chars-backward "a-zA-Z0-9*")
18347 (skip-chars-backward " \t")
18348 (and (bolp) (not (org-at-heading-p))))
18349 (cdlatex-tab) t)
18350 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18352 (defun org-cdlatex-underscore-caret (&optional _arg)
18353 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18354 Revert to the normal definition outside of these fragments."
18355 (interactive "P")
18356 (if (org-inside-LaTeX-fragment-p)
18357 (call-interactively 'cdlatex-sub-superscript)
18358 (let (org-cdlatex-mode)
18359 (call-interactively (key-binding (vector last-input-event))))))
18361 (defun org-cdlatex-math-modify (&optional _arg)
18362 "Execute `cdlatex-math-modify' in LaTeX fragments.
18363 Revert to the normal definition outside of these fragments."
18364 (interactive "P")
18365 (if (org-inside-LaTeX-fragment-p)
18366 (call-interactively 'cdlatex-math-modify)
18367 (let (org-cdlatex-mode)
18368 (call-interactively (key-binding (vector last-input-event))))))
18370 (defun org-cdlatex-environment-indent (&optional environment item)
18371 "Execute `cdlatex-environment' and indent the inserted environment.
18373 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18375 The inserted environment is indented to current indentation
18376 unless point is at the beginning of the line, in which the
18377 environment remains unintended."
18378 (interactive)
18379 ;; cdlatex-environment always return nil. Therefore, capture output
18380 ;; first and determine if an environment was selected.
18381 (let* ((beg (point-marker))
18382 (end (copy-marker (point) t))
18383 (inserted (progn
18384 (ignore-errors (cdlatex-environment environment item))
18385 (< beg end)))
18386 ;; Figure out how many lines to move forward after the
18387 ;; environment has been inserted.
18388 (lines (when inserted
18389 (save-excursion
18390 (- (cl-loop while (< beg (point))
18391 with x = 0
18392 do (forward-line -1)
18393 (cl-incf x)
18394 finally return x)
18395 (if (progn (goto-char beg)
18396 (and (progn (skip-chars-forward " \t") (eolp))
18397 (progn (skip-chars-backward " \t") (bolp))))
18398 1 0)))))
18399 (env (org-trim (delete-and-extract-region beg end))))
18400 (when inserted
18401 ;; Get indentation of next line unless at column 0.
18402 (let ((ind (if (bolp) 0
18403 (save-excursion
18404 (org-return-indent)
18405 (prog1 (org-get-indentation)
18406 (when (progn (skip-chars-forward " \t") (eolp))
18407 (delete-region beg (point)))))))
18408 (bol (progn (skip-chars-backward " \t") (bolp))))
18409 ;; Insert a newline before environment unless at column zero
18410 ;; to "escape" the current line. Insert a newline if
18411 ;; something is one the same line as \end{ENVIRONMENT}.
18412 (insert
18413 (concat (unless bol "\n") env
18414 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18415 (unless (zerop ind)
18416 (save-excursion
18417 (goto-char beg)
18418 (while (< (point) end)
18419 (unless (eolp) (indent-line-to ind))
18420 (forward-line))))
18421 (goto-char beg)
18422 (forward-line lines)
18423 (indent-line-to ind)))
18424 (set-marker beg nil)
18425 (set-marker end nil)))
18428 ;;;; LaTeX fragments
18430 (defun org-inside-LaTeX-fragment-p ()
18431 "Test if point is inside a LaTeX fragment.
18432 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18433 sequence appearing also before point.
18434 Even though the matchers for math are configurable, this function assumes
18435 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18436 delimiters are skipped when they have been removed by customization.
18437 The return value is nil, or a cons cell with the delimiter and the
18438 position of this delimiter.
18440 This function does a reasonably good job, but can locally be fooled by
18441 for example currency specifications. For example it will assume being in
18442 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18443 fragments that are properly closed, but during editing, we have to live
18444 with the uncertainty caused by missing closing delimiters. This function
18445 looks only before point, not after."
18446 (catch 'exit
18447 (let ((pos (point))
18448 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18449 (lim (save-excursion (org-backward-paragraph) (point)))
18450 dd-on str (start 0) m re)
18451 (goto-char pos)
18452 (when dodollar
18453 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18454 re (nth 1 (assoc "$" org-latex-regexps)))
18455 (while (string-match re str start)
18456 (cond
18457 ((= (match-end 0) (length str))
18458 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18459 ((= (match-end 0) (- (length str) 5))
18460 (throw 'exit nil))
18461 (t (setq start (match-end 0))))))
18462 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18463 (goto-char pos)
18464 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18465 (and (match-beginning 2) (throw 'exit nil))
18466 ;; count $$
18467 (while (re-search-backward "\\$\\$" lim t)
18468 (setq dd-on (not dd-on)))
18469 (goto-char pos)
18470 (when dd-on (cons "$$" m))))))
18472 (defun org-inside-latex-macro-p ()
18473 "Is point inside a LaTeX macro or its arguments?"
18474 (save-match-data
18475 (org-in-regexp
18476 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18478 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18479 "Build an overlay between BEG and END using IMAGE file.
18480 Argument IMAGETYPE is the extension of the displayed image,
18481 as a string. It defaults to \"png\"."
18482 (let ((ov (make-overlay beg end))
18483 (imagetype (or (intern imagetype) 'png)))
18484 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18485 (overlay-put ov 'evaporate t)
18486 (overlay-put ov
18487 'modification-hooks
18488 (list (lambda (o _flag _beg _end &optional _l)
18489 (delete-overlay o))))
18490 (overlay-put ov
18491 'display
18492 (list 'image :type imagetype :file image :ascent 'center))))
18494 (defun org--list-latex-overlays (&optional beg end)
18495 "List all Org LaTeX overlays in current buffer.
18496 Limit to overlays between BEG and END when those are provided."
18497 (cl-remove-if-not
18498 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18499 (overlays-in (or beg (point-min)) (or end (point-max)))))
18501 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18502 "Remove all overlays with LaTeX fragment images in current buffer.
18503 When optional arguments BEG and END are non-nil, remove all
18504 overlays between them instead. Return a non-nil value when some
18505 overlays were removed, nil otherwise."
18506 (let ((overlays (org--list-latex-overlays beg end)))
18507 (mapc #'delete-overlay overlays)
18508 overlays))
18510 (defun org-toggle-latex-fragment (&optional arg)
18511 "Preview the LaTeX fragment at point, or all locally or globally.
18513 If the cursor is on a LaTeX fragment, create the image and overlay
18514 it over the source code, if there is none. Remove it otherwise.
18515 If there is no fragment at point, display all fragments in the
18516 current section.
18518 With prefix ARG, preview or clear image for all fragments in the
18519 current subtree or in the whole buffer when used before the first
18520 headline. With a prefix ARG `\\[universal-argument] \
18521 \\[universal-argument]' preview or clear images
18522 for all fragments in the buffer."
18523 (interactive "P")
18524 (when (display-graphic-p)
18525 (catch 'exit
18526 (save-excursion
18527 (let (beg end msg)
18528 (cond
18529 ((or (equal arg '(16))
18530 (and (equal arg '(4))
18531 (org-with-limited-levels (org-before-first-heading-p))))
18532 (if (org-remove-latex-fragment-image-overlays)
18533 (progn (message "LaTeX fragments images removed from buffer")
18534 (throw 'exit nil))
18535 (setq msg "Creating images for buffer...")))
18536 ((equal arg '(4))
18537 (org-with-limited-levels (org-back-to-heading t))
18538 (setq beg (point))
18539 (setq end (progn (org-end-of-subtree t) (point)))
18540 (if (org-remove-latex-fragment-image-overlays beg end)
18541 (progn
18542 (message "LaTeX fragment images removed from subtree")
18543 (throw 'exit nil))
18544 (setq msg "Creating images for subtree...")))
18545 ((let ((datum (org-element-context)))
18546 (when (memq (org-element-type datum)
18547 '(latex-environment latex-fragment))
18548 (setq beg (org-element-property :begin datum))
18549 (setq end (org-element-property :end datum))
18550 (if (org-remove-latex-fragment-image-overlays beg end)
18551 (progn (message "LaTeX fragment image removed")
18552 (throw 'exit nil))
18553 (setq msg "Creating image...")))))
18555 (org-with-limited-levels
18556 (setq beg (if (org-at-heading-p) (line-beginning-position)
18557 (outline-previous-heading)
18558 (point)))
18559 (setq end (progn (outline-next-heading) (point)))
18560 (if (org-remove-latex-fragment-image-overlays beg end)
18561 (progn
18562 (message "LaTeX fragment images removed from section")
18563 (throw 'exit nil))
18564 (setq msg "Creating images for section...")))))
18565 (let ((file (buffer-file-name (buffer-base-buffer))))
18566 (org-format-latex
18567 (concat org-preview-latex-image-directory "org-ltximg")
18568 beg end
18569 ;; Emacs cannot overlay images from remote hosts. Create
18570 ;; it in `temporary-file-directory' instead.
18571 (if (or (not file) (file-remote-p file))
18572 temporary-file-directory
18573 default-directory)
18574 'overlays msg 'forbuffer org-preview-latex-default-process))
18575 (message (concat msg "done")))))))
18577 (defun org-format-latex
18578 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18579 "Replace LaTeX fragments with links to an image.
18581 The function takes care of creating the replacement image.
18583 Only consider fragments between BEG and END when those are
18584 provided.
18586 When optional argument OVERLAYS is non-nil, display the image on
18587 top of the fragment instead of replacing it.
18589 PROCESSING-TYPE is the conversion method to use, as a symbol.
18591 Some of the options can be changed using the variable
18592 `org-format-latex-options', which see."
18593 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18594 (unless (eq processing-type 'verbatim)
18595 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18596 (cnt 0)
18597 checkdir-flag)
18598 (goto-char (or beg (point-min)))
18599 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18600 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18601 (overlay-recenter (or end (point-max))))
18602 (while (re-search-forward math-regexp end t)
18603 (unless (and overlays
18604 (eq (get-char-property (point) 'org-overlay-type)
18605 'org-latex-overlay))
18606 (let* ((context (org-element-context))
18607 (type (org-element-type context)))
18608 (when (memq type '(latex-environment latex-fragment))
18609 (let ((block-type (eq type 'latex-environment))
18610 (value (org-element-property :value context))
18611 (beg (org-element-property :begin context))
18612 (end (save-excursion
18613 (goto-char (org-element-property :end context))
18614 (skip-chars-backward " \r\t\n")
18615 (point))))
18616 (cond
18617 ((eq processing-type 'mathjax)
18618 ;; Prepare for MathJax processing.
18619 (if (not (string-match "\\`\\$\\$?" value))
18620 (goto-char end)
18621 (delete-region beg end)
18622 (if (string= (match-string 0 value) "$$")
18623 (insert "\\[" (substring value 2 -2) "\\]")
18624 (insert "\\(" (substring value 1 -1) "\\)"))))
18625 ((assq processing-type org-preview-latex-process-alist)
18626 ;; Process to an image.
18627 (cl-incf cnt)
18628 (goto-char beg)
18629 (let* ((processing-info
18630 (cdr (assq processing-type org-preview-latex-process-alist)))
18631 (face (face-at-point))
18632 ;; Get the colors from the face at point.
18634 (let ((color (plist-get org-format-latex-options
18635 :foreground)))
18636 (if (and forbuffer (eq color 'auto))
18637 (face-attribute face :foreground nil 'default)
18638 color)))
18640 (let ((color (plist-get org-format-latex-options
18641 :background)))
18642 (if (and forbuffer (eq color 'auto))
18643 (face-attribute face :background nil 'default)
18644 color)))
18645 (hash (sha1 (prin1-to-string
18646 (list org-format-latex-header
18647 org-latex-default-packages-alist
18648 org-latex-packages-alist
18649 org-format-latex-options
18650 forbuffer value fg bg))))
18651 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18652 (absprefix (expand-file-name prefix dir))
18653 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18654 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18655 (sep (and block-type "\n\n"))
18656 (link (concat sep "[[file:" linkfile "]]" sep))
18657 (options
18658 (org-combine-plists
18659 org-format-latex-options
18660 `(:foreground ,fg :background ,bg))))
18661 (when msg (message msg cnt))
18662 (unless checkdir-flag ; Ensure the directory exists.
18663 (setq checkdir-flag t)
18664 (let ((todir (file-name-directory absprefix)))
18665 (unless (file-directory-p todir)
18666 (make-directory todir t))))
18667 (unless (file-exists-p movefile)
18668 (org-create-formula-image
18669 value movefile options forbuffer processing-type))
18670 (if overlays
18671 (progn
18672 (dolist (o (overlays-in beg end))
18673 (when (eq (overlay-get o 'org-overlay-type)
18674 'org-latex-overlay)
18675 (delete-overlay o)))
18676 (org--format-latex-make-overlay beg end movefile imagetype)
18677 (goto-char end))
18678 (delete-region beg end)
18679 (insert
18680 (org-add-props link
18681 (list 'org-latex-src
18682 (replace-regexp-in-string "\"" "" value)
18683 'org-latex-src-embed-type
18684 (if block-type 'paragraph 'character)))))))
18685 ((eq processing-type 'mathml)
18686 ;; Process to MathML.
18687 (unless (org-format-latex-mathml-available-p)
18688 (user-error "LaTeX to MathML converter not configured"))
18689 (cl-incf cnt)
18690 (when msg (message msg cnt))
18691 (goto-char beg)
18692 (delete-region beg end)
18693 (insert (org-format-latex-as-mathml
18694 value block-type prefix dir)))
18696 (error "Unknown conversion process %s for LaTeX fragments"
18697 processing-type)))))))))))
18699 (defun org-create-math-formula (latex-frag &optional mathml-file)
18700 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18701 Use `org-latex-to-mathml-convert-command'. If the conversion is
18702 sucessful, return the portion between \"<math...> </math>\"
18703 elements otherwise return nil. When MATHML-FILE is specified,
18704 write the results in to that file. When invoked as an
18705 interactive command, prompt for LATEX-FRAG, with initial value
18706 set to the current active region and echo the results for user
18707 inspection."
18708 (interactive (list (let ((frag (when (org-region-active-p)
18709 (buffer-substring-no-properties
18710 (region-beginning) (region-end)))))
18711 (read-string "LaTeX Fragment: " frag nil frag))))
18712 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18713 (let* ((tmp-in-file
18714 (let ((file (file-relative-name
18715 (make-temp-name (expand-file-name "ltxmathml-in")))))
18716 (write-region latex-frag nil file)
18717 file))
18718 (tmp-out-file (file-relative-name
18719 (make-temp-name (expand-file-name "ltxmathml-out"))))
18720 (cmd (format-spec
18721 org-latex-to-mathml-convert-command
18722 `((?j . ,(and org-latex-to-mathml-jar-file
18723 (shell-quote-argument
18724 (expand-file-name
18725 org-latex-to-mathml-jar-file))))
18726 (?I . ,(shell-quote-argument tmp-in-file))
18727 (?i . ,latex-frag)
18728 (?o . ,(shell-quote-argument tmp-out-file)))))
18729 mathml shell-command-output)
18730 (when (called-interactively-p 'any)
18731 (unless (org-format-latex-mathml-available-p)
18732 (user-error "LaTeX to MathML converter not configured")))
18733 (message "Running %s" cmd)
18734 (setq shell-command-output (shell-command-to-string cmd))
18735 (setq mathml
18736 (when (file-readable-p tmp-out-file)
18737 (with-current-buffer (find-file-noselect tmp-out-file t)
18738 (goto-char (point-min))
18739 (when (re-search-forward
18740 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18741 (regexp-quote
18742 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18743 nil t)
18744 (prog1 (match-string 0) (kill-buffer))))))
18745 (cond
18746 (mathml
18747 (setq mathml
18748 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18749 (when mathml-file
18750 (write-region mathml nil mathml-file))
18751 (when (called-interactively-p 'any)
18752 (message mathml)))
18753 ((message "LaTeX to MathML conversion failed")
18754 (message shell-command-output)))
18755 (delete-file tmp-in-file)
18756 (when (file-exists-p tmp-out-file)
18757 (delete-file tmp-out-file))
18758 mathml))
18760 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18761 prefix &optional dir)
18762 "Use `org-create-math-formula' but check local cache first."
18763 (let* ((absprefix (expand-file-name prefix dir))
18764 (print-length nil) (print-level nil)
18765 (formula-id (concat
18766 "formula-"
18767 (sha1
18768 (prin1-to-string
18769 (list latex-frag
18770 org-latex-to-mathml-convert-command)))))
18771 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18772 (formula-cache-dir (file-name-directory formula-cache)))
18774 (unless (file-directory-p formula-cache-dir)
18775 (make-directory formula-cache-dir t))
18777 (unless (file-exists-p formula-cache)
18778 (org-create-math-formula latex-frag formula-cache))
18780 (if (file-exists-p formula-cache)
18781 ;; Successful conversion. Return the link to MathML file.
18782 (org-add-props
18783 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18784 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18785 'org-latex-src-embed-type (if latex-frag-type
18786 'paragraph 'character)))
18787 ;; Failed conversion. Return the LaTeX fragment verbatim
18788 latex-frag)))
18790 (defun org--get-display-dpi ()
18791 "Get the DPI of the display.
18792 The function assumes that the display has the same pixel width in
18793 the horizontal and vertical directions."
18794 (if (display-graphic-p)
18795 (round (/ (display-pixel-height)
18796 (/ (display-mm-height) 25.4)))
18797 (error "Attempt to calculate the dpi of a non-graphic display")))
18799 (defun org-create-formula-image
18800 (string tofile options buffer &optional processing-type)
18801 "Create an image from LaTeX source using external processes.
18803 The LaTeX STRING is saved to a temporary LaTeX file, then
18804 converted to an image file by process PROCESSING-TYPE defined in
18805 `org-preview-latex-process-alist'. A nil value defaults to
18806 `org-preview-latex-default-process'.
18808 The generated image file is eventually moved to TOFILE.
18810 The OPTIONS argument controls the size, foreground color and
18811 background color of the generated image.
18813 When BUFFER non-nil, this function is used for LaTeX previewing.
18814 Otherwise, it is used to deal with LaTeX snippets showed in
18815 a HTML file."
18816 (let* ((processing-type (or processing-type
18817 org-preview-latex-default-process))
18818 (processing-info
18819 (cdr (assq processing-type org-preview-latex-process-alist)))
18820 (programs (plist-get processing-info :programs))
18821 (error-message (or (plist-get processing-info :message) ""))
18822 (use-xcolor (plist-get processing-info :use-xcolor))
18823 (image-input-type (plist-get processing-info :image-input-type))
18824 (image-output-type (plist-get processing-info :image-output-type))
18825 (post-clean (or (plist-get processing-info :post-clean)
18826 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18827 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18828 (latex-header
18829 (or (plist-get processing-info :latex-header)
18830 (org-latex-make-preamble
18831 (org-export-get-environment (org-export-get-backend 'latex))
18832 org-format-latex-header
18833 'snippet)))
18834 (latex-compiler (plist-get processing-info :latex-compiler))
18835 (image-converter (plist-get processing-info :image-converter))
18836 (tmpdir temporary-file-directory)
18837 (texfilebase (make-temp-name
18838 (expand-file-name "orgtex" tmpdir)))
18839 (texfile (concat texfilebase ".tex"))
18840 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18841 '(1.0 . 1.0)))
18842 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18843 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18844 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18845 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18846 "Black"))
18847 (bg (or (plist-get options (if buffer :background :html-background))
18848 "Transparent"))
18849 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18850 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18851 (dolist (program programs)
18852 (org-check-external-command program error-message))
18853 (if use-xcolor
18854 (progn (if (eq fg 'default)
18855 (setq fg (org-latex-color :foreground))
18856 (setq fg (org-latex-color-format fg)))
18857 (if (eq bg 'default)
18858 (setq bg (org-latex-color :background))
18859 (setq bg (org-latex-color-format
18860 (if (string= bg "Transparent") "white" bg))))
18861 (with-temp-file texfile
18862 (insert latex-header)
18863 (insert "\n\\begin{document}\n"
18864 "\\definecolor{fg}{rgb}{" fg "}\n"
18865 "\\definecolor{bg}{rgb}{" bg "}\n"
18866 "\n\\pagecolor{bg}\n"
18867 "\n{\\color{fg}\n"
18868 string
18869 "\n}\n"
18870 "\n\\end{document}\n")))
18871 (if (eq fg 'default)
18872 (setq fg (org-dvipng-color :foreground))
18873 (unless (string= fg "Transparent")
18874 (setq fg (org-dvipng-color-format fg))))
18875 (if (eq bg 'default)
18876 (setq bg (org-dvipng-color :background))
18877 (unless (string= bg "Transparent")
18878 (setq bg (org-dvipng-color-format bg))))
18879 (with-temp-file texfile
18880 (insert latex-header)
18881 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18883 (let* ((err-msg (format "Please adjust `%s' part of \
18884 `org-preview-latex-process-alist'."
18885 processing-type))
18886 (image-input-file
18887 (org-compile-file
18888 texfile latex-compiler image-input-type err-msg log-buf))
18889 (image-output-file
18890 (org-compile-file
18891 image-input-file image-converter image-output-type err-msg log-buf
18892 `((?F . ,(shell-quote-argument fg))
18893 (?B . ,(shell-quote-argument bg))
18894 (?D . ,(shell-quote-argument (format "%s" dpi)))
18895 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18896 (copy-file image-output-file tofile 'replace)
18897 (dolist (e post-clean)
18898 (when (file-exists-p (concat texfilebase e))
18899 (delete-file (concat texfilebase e))))
18900 image-output-file)))
18902 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18903 "Fill a LaTeX header template TPL.
18904 In the template, the following place holders will be recognized:
18906 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18907 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18908 [PACKAGES] \\usepackage statements for PKG
18909 [NO-PACKAGES] do not include PKG
18910 [EXTRA] the string EXTRA
18911 [NO-EXTRA] do not include EXTRA
18913 For backward compatibility, if both the positive and the negative place
18914 holder is missing, the positive one (without the \"NO-\") will be
18915 assumed to be present at the end of the template.
18916 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18917 EXTRA is a string.
18918 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18919 (let (rpl (end ""))
18920 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18921 (setq rpl (if (or (match-end 1) (not def-pkg))
18922 "" (org-latex-packages-to-string def-pkg snippets-p t))
18923 tpl (replace-match rpl t t tpl))
18924 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18926 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18927 (setq rpl (if (or (match-end 1) (not pkg))
18928 "" (org-latex-packages-to-string pkg snippets-p t))
18929 tpl (replace-match rpl t t tpl))
18930 (when pkg (setq end
18931 (concat end "\n"
18932 (org-latex-packages-to-string pkg snippets-p)))))
18934 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18935 (setq rpl (if (or (match-end 1) (not extra))
18936 "" (concat extra "\n"))
18937 tpl (replace-match rpl t t tpl))
18938 (when (and extra (string-match "\\S-" extra))
18939 (setq end (concat end "\n" extra))))
18941 (if (string-match "\\S-" end)
18942 (concat tpl "\n" end)
18943 tpl)))
18945 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18946 "Turn an alist of packages into a string with the \\usepackage macros."
18947 (setq pkg (mapconcat (lambda(p)
18948 (cond
18949 ((stringp p) p)
18950 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18951 (format "%% Package %s omitted" (cadr p)))
18952 ((equal "" (car p))
18953 (format "\\usepackage{%s}" (cadr p)))
18955 (format "\\usepackage[%s]{%s}"
18956 (car p) (cadr p)))))
18958 "\n"))
18959 (if newline (concat pkg "\n") pkg))
18961 (defun org-dvipng-color (attr)
18962 "Return a RGB color specification for dvipng."
18963 (org-dvipng-color-format (face-attribute 'default attr nil)))
18965 (defun org-dvipng-color-format (color-name)
18966 "Convert COLOR-NAME to a RGB color value for dvipng."
18967 (apply #'format "rgb %s %s %s"
18968 (mapcar 'org-normalize-color
18969 (color-values color-name))))
18971 (defun org-latex-color (attr)
18972 "Return a RGB color for the LaTeX color package."
18973 (org-latex-color-format (face-attribute 'default attr nil)))
18975 (defun org-latex-color-format (color-name)
18976 "Convert COLOR-NAME to a RGB color value."
18977 (apply #'format "%s,%s,%s"
18978 (mapcar 'org-normalize-color
18979 (color-values color-name))))
18981 (defun org-normalize-color (value)
18982 "Return string to be used as color value for an RGB component."
18983 (format "%g" (/ value 65535.0)))
18987 ;; Image display
18989 (defvar-local org-inline-image-overlays nil)
18991 (defun org-toggle-inline-images (&optional include-linked)
18992 "Toggle the display of inline images.
18993 INCLUDE-LINKED is passed to `org-display-inline-images'."
18994 (interactive "P")
18995 (if org-inline-image-overlays
18996 (progn
18997 (org-remove-inline-images)
18998 (when (called-interactively-p 'interactive)
18999 (message "Inline image display turned off")))
19000 (org-display-inline-images include-linked)
19001 (when (called-interactively-p 'interactive)
19002 (message (if org-inline-image-overlays
19003 (format "%d images displayed inline"
19004 (length org-inline-image-overlays))
19005 "No images to display inline")))))
19007 (defun org-redisplay-inline-images ()
19008 "Refresh the display of inline images."
19009 (interactive)
19010 (if (not org-inline-image-overlays)
19011 (org-toggle-inline-images)
19012 (org-toggle-inline-images)
19013 (org-toggle-inline-images)))
19015 (defun org-display-inline-images (&optional include-linked refresh beg end)
19016 "Display inline images.
19018 An inline image is a link which follows either of these
19019 conventions:
19021 1. Its path is a file with an extension matching return value
19022 from `image-file-name-regexp' and it has no contents.
19024 2. Its description consists in a single link of the previous
19025 type.
19027 When optional argument INCLUDE-LINKED is non-nil, also links with
19028 a text description part will be inlined. This can be nice for
19029 a quick look at those images, but it does not reflect what
19030 exported files will look like.
19032 When optional argument REFRESH is non-nil, refresh existing
19033 images between BEG and END. This will create new image displays
19034 only if necessary. BEG and END default to the buffer
19035 boundaries."
19036 (interactive "P")
19037 (when (display-graphic-p)
19038 (unless refresh
19039 (org-remove-inline-images)
19040 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19041 (org-with-wide-buffer
19042 (goto-char (or beg (point-min)))
19043 (let* ((case-fold-search t)
19044 (file-extension-re (image-file-name-regexp))
19045 (link-abbrevs (mapcar #'car
19046 (append org-link-abbrev-alist-local
19047 org-link-abbrev-alist)))
19048 ;; Check absolute, relative file names and explicit
19049 ;; "file:" links. Also check link abbreviations since
19050 ;; some might expand to "file" links.
19051 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19052 (if (not link-abbrevs) ""
19053 (format "\\|\\(?:%s:\\)"
19054 (regexp-opt link-abbrevs))))))
19055 (while (re-search-forward file-types-re end t)
19056 (let ((link (save-match-data (org-element-context))))
19057 ;; Check if we're at an inline image, i.e., an image file
19058 ;; link without a description (unless INCLUDE-LINKED is
19059 ;; non-nil).
19060 (when (and (equal "file" (org-element-property :type link))
19061 (or include-linked
19062 (null (org-element-contents link)))
19063 (string-match-p file-extension-re
19064 (org-element-property :path link)))
19065 (let ((file (expand-file-name
19066 (org-link-unescape
19067 (org-element-property :path link)))))
19068 (when (file-exists-p file)
19069 (let ((width
19070 ;; Apply `org-image-actual-width' specifications.
19071 (cond
19072 ((not (image-type-available-p 'imagemagick)) nil)
19073 ((eq org-image-actual-width t) nil)
19074 ((listp org-image-actual-width)
19076 ;; First try to find a width among
19077 ;; attributes associated to the paragraph
19078 ;; containing link.
19079 (let ((paragraph
19080 (let ((e link))
19081 (while (and (setq e (org-element-property
19082 :parent e))
19083 (not (eq (org-element-type e)
19084 'paragraph))))
19085 e)))
19086 (when paragraph
19087 (save-excursion
19088 (goto-char (org-element-property :begin paragraph))
19089 (when
19090 (re-search-forward
19091 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19092 (org-element-property
19093 :post-affiliated paragraph)
19095 (string-to-number (match-string 1))))))
19096 ;; Otherwise, fall-back to provided number.
19097 (car org-image-actual-width)))
19098 ((numberp org-image-actual-width)
19099 org-image-actual-width)))
19100 (old (get-char-property-and-overlay
19101 (org-element-property :begin link)
19102 'org-image-overlay)))
19103 (if (and (car-safe old) refresh)
19104 (image-refresh (overlay-get (cdr old) 'display))
19105 (let ((image (create-image file
19106 (and width 'imagemagick)
19108 :width width)))
19109 (when image
19110 (let ((ov (make-overlay
19111 (org-element-property :begin link)
19112 (progn
19113 (goto-char
19114 (org-element-property :end link))
19115 (skip-chars-backward " \t")
19116 (point)))))
19117 (overlay-put ov 'display image)
19118 (overlay-put ov 'face 'default)
19119 (overlay-put ov 'org-image-overlay t)
19120 (overlay-put
19121 ov 'modification-hooks
19122 (list 'org-display-inline-remove-overlay))
19123 (push ov org-inline-image-overlays)))))))))))))))
19125 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19126 "Remove inline-display overlay if a corresponding region is modified."
19127 (let ((inhibit-modification-hooks t))
19128 (when (and ov after)
19129 (delete ov org-inline-image-overlays)
19130 (delete-overlay ov))))
19132 (defun org-remove-inline-images ()
19133 "Remove inline display of images."
19134 (interactive)
19135 (mapc #'delete-overlay org-inline-image-overlays)
19136 (setq org-inline-image-overlays nil))
19138 ;;;; Key bindings
19140 (defun org-remap (map &rest commands)
19141 "In MAP, remap the functions given in COMMANDS.
19142 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19143 (let (new old)
19144 (while commands
19145 (setq old (pop commands) new (pop commands))
19146 (org-defkey map (vector 'remap old) new))))
19148 ;; Outline functions from `outline-mode-prefix-map'
19149 ;; that can be remapped in Org:
19150 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19151 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19152 (define-key org-mode-map [remap outline-forward-same-level]
19153 'org-forward-heading-same-level)
19154 (define-key org-mode-map [remap outline-backward-same-level]
19155 'org-backward-heading-same-level)
19156 (define-key org-mode-map [remap outline-show-branches]
19157 'org-kill-note-or-show-branches)
19158 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19159 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19160 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19161 (define-key org-mode-map [remap outline-next-visible-heading]
19162 'org-next-visible-heading)
19163 (define-key org-mode-map [remap outline-previous-visible-heading]
19164 'org-previous-visible-heading)
19165 (define-key org-mode-map [remap show-children] 'org-show-children)
19167 ;; Outline functions from `outline-mode-prefix-map' that can not
19168 ;; be remapped in Org:
19170 ;; - the column "key binding" shows whether the Outline function is still
19171 ;; available in Org mode on the same key that it has been bound to in
19172 ;; Outline mode:
19173 ;; - "overridden": key used for a different functionality in Org mode
19174 ;; - else: key still bound to the same Outline function in Org mode
19176 ;; | Outline function | key binding | Org replacement |
19177 ;; |------------------------------------+-------------+--------------------------|
19178 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19179 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19180 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19181 ;; | `show-entry' | overridden | no replacement |
19182 ;; | `show-branches' | `C-c C-k' | still same function |
19183 ;; | `show-subtree' | overridden | visibility cycling |
19184 ;; | `show-all' | overridden | no replacement |
19185 ;; | `hide-subtree' | overridden | visibility cycling |
19186 ;; | `hide-body' | overridden | no replacement |
19187 ;; | `hide-entry' | overridden | visibility cycling |
19188 ;; | `hide-leaves' | overridden | no replacement |
19189 ;; | `hide-sublevels' | overridden | no replacement |
19190 ;; | `hide-other' | overridden | no replacement |
19192 ;; Make `C-c C-x' a prefix key
19193 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19195 ;; TAB key with modifiers
19196 (org-defkey org-mode-map "\C-i" 'org-cycle)
19197 (org-defkey org-mode-map [(tab)] 'org-cycle)
19198 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19199 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19201 ;; The following line is necessary under Suse GNU/Linux
19202 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19203 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19204 (define-key org-mode-map [backtab] 'org-shifttab)
19206 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19207 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19208 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19210 ;; Cursor keys with modifiers
19211 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19212 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19213 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19214 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19216 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19217 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19218 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19219 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19220 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19221 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19223 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19224 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19225 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19226 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19228 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19229 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19230 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19231 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19233 ;; Babel keys
19234 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19235 (dolist (pair org-babel-key-bindings)
19236 (define-key org-babel-map (car pair) (cdr pair)))
19238 ;;; Extra keys for tty access.
19239 ;; We only set them when really needed because otherwise the
19240 ;; menus don't show the simple keys
19242 (when (or org-use-extra-keys (not window-system))
19243 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19244 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19245 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19246 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19247 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19248 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19249 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19250 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19251 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19252 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19253 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19254 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19255 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19256 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19257 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19258 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19259 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19260 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19261 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19262 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19263 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19264 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19265 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19266 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19267 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19268 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19269 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19270 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19272 ;; All the other keys
19273 (org-remap org-mode-map
19274 'self-insert-command 'org-self-insert-command
19275 'delete-char 'org-delete-char
19276 'delete-backward-char 'org-delete-backward-char)
19277 (org-defkey org-mode-map "|" 'org-force-self-insert)
19279 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19280 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19281 (if (boundp 'narrow-map)
19282 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19283 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19284 (if (boundp 'narrow-map)
19285 (org-defkey narrow-map "b" 'org-narrow-to-block)
19286 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19287 (if (boundp 'narrow-map)
19288 (org-defkey narrow-map "e" 'org-narrow-to-element)
19289 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19290 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19291 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19292 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19293 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19294 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19295 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19296 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19297 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19298 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19299 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19300 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19301 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19302 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19303 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19304 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19305 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19306 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19307 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19308 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19309 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19310 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19311 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19312 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19313 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19314 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19315 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19316 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19317 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19318 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19319 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19320 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19321 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19322 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19323 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19324 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19325 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19326 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19327 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19328 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19329 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19330 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19331 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19332 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19333 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19334 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19335 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19336 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19337 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19338 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19339 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19340 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19341 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19342 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19343 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19344 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19345 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19346 (org-defkey org-mode-map "\C-c^" 'org-sort)
19347 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19348 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19349 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19350 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19351 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19352 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19353 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19354 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19355 (org-defkey org-mode-map "\C-m" 'org-return)
19356 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19357 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19358 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19359 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19360 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19361 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19362 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19363 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19364 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19365 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19366 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19367 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19368 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19369 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19370 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19371 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19372 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19373 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19374 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19375 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19376 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19377 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19378 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19379 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19380 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19382 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19383 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19384 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19386 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19387 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19388 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19389 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19390 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19391 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19392 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19393 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19394 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19395 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19396 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19397 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19398 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19399 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19400 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19401 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19402 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19403 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19404 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19405 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19406 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19407 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19408 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19410 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19411 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19412 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19413 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19414 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19416 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19418 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19420 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19421 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19423 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19426 (defconst org-speed-commands-default
19428 ("Outline Navigation")
19429 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19430 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19431 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19432 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19433 ("F" . org-next-block)
19434 ("B" . org-previous-block)
19435 ("u" . (org-speed-move-safe 'outline-up-heading))
19436 ("j" . org-goto)
19437 ("g" . (org-refile t))
19438 ("Outline Visibility")
19439 ("c" . org-cycle)
19440 ("C" . org-shifttab)
19441 (" " . org-display-outline-path)
19442 ("s" . org-narrow-to-subtree)
19443 ("=" . org-columns)
19444 ("Outline Structure Editing")
19445 ("U" . org-metaup)
19446 ("D" . org-metadown)
19447 ("r" . org-metaright)
19448 ("l" . org-metaleft)
19449 ("R" . org-shiftmetaright)
19450 ("L" . org-shiftmetaleft)
19451 ("i" . (progn (forward-char 1) (call-interactively
19452 'org-insert-heading-respect-content)))
19453 ("^" . org-sort)
19454 ("w" . org-refile)
19455 ("a" . org-archive-subtree-default-with-confirmation)
19456 ("@" . org-mark-subtree)
19457 ("#" . org-toggle-comment)
19458 ("Clock Commands")
19459 ("I" . org-clock-in)
19460 ("O" . org-clock-out)
19461 ("Meta Data Editing")
19462 ("t" . org-todo)
19463 ("," . (org-priority))
19464 ("0" . (org-priority ?\ ))
19465 ("1" . (org-priority ?A))
19466 ("2" . (org-priority ?B))
19467 ("3" . (org-priority ?C))
19468 (":" . org-set-tags-command)
19469 ("e" . org-set-effort)
19470 ("E" . org-inc-effort)
19471 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19472 (org-entry-put (point) "APPT_WARNTIME" m)))
19473 ("Agenda Views etc")
19474 ("v" . org-agenda)
19475 ("/" . org-sparse-tree)
19476 ("Misc")
19477 ("o" . org-open-at-point)
19478 ("?" . org-speed-command-help)
19479 ("<" . (org-agenda-set-restriction-lock 'subtree))
19480 (">" . (org-agenda-remove-restriction-lock))
19482 "The default speed commands.")
19484 (defun org-print-speed-command (e)
19485 (if (> (length (car e)) 1)
19486 (progn
19487 (princ "\n")
19488 (princ (car e))
19489 (princ "\n")
19490 (princ (make-string (length (car e)) ?-))
19491 (princ "\n"))
19492 (princ (car e))
19493 (princ " ")
19494 (if (symbolp (cdr e))
19495 (princ (symbol-name (cdr e)))
19496 (prin1 (cdr e)))
19497 (princ "\n")))
19499 (defun org-speed-command-help ()
19500 "Show the available speed commands."
19501 (interactive)
19502 (if (not org-use-speed-commands)
19503 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19504 (with-output-to-temp-buffer "*Help*"
19505 (princ "User-defined Speed commands\n===========================\n")
19506 (mapc #'org-print-speed-command org-speed-commands-user)
19507 (princ "\n")
19508 (princ "Built-in Speed commands\n=======================\n")
19509 (mapc #'org-print-speed-command org-speed-commands-default))
19510 (with-current-buffer "*Help*"
19511 (setq truncate-lines t))))
19513 (defun org-speed-move-safe (cmd)
19514 "Execute CMD, but make sure that the cursor always ends up in a headline.
19515 If not, return to the original position and throw an error."
19516 (interactive)
19517 (let ((pos (point)))
19518 (call-interactively cmd)
19519 (unless (and (bolp) (org-at-heading-p))
19520 (goto-char pos)
19521 (error "Boundary reached while executing %s" cmd))))
19523 (defvar org-self-insert-command-undo-counter 0)
19525 (defvar org-table-auto-blank-field) ; defined in org-table.el
19526 (defvar org-speed-command nil)
19528 (defun org-speed-command-activate (keys)
19529 "Hook for activating single-letter speed commands.
19530 `org-speed-commands-default' specifies a minimal command set.
19531 Use `org-speed-commands-user' for further customization."
19532 (when (or (and (bolp) (looking-at org-outline-regexp))
19533 (and (functionp org-use-speed-commands)
19534 (funcall org-use-speed-commands)))
19535 (cdr (assoc keys (append org-speed-commands-user
19536 org-speed-commands-default)))))
19538 (defun org-babel-speed-command-activate (keys)
19539 "Hook for activating single-letter code block commands."
19540 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19541 (cdr (assoc keys org-babel-key-bindings))))
19543 (defcustom org-speed-command-hook
19544 '(org-speed-command-activate org-babel-speed-command-activate)
19545 "Hook for activating speed commands at strategic locations.
19546 Hook functions are called in sequence until a valid handler is
19547 found.
19549 Each hook takes a single argument, a user-pressed command key
19550 which is also a `self-insert-command' from the global map.
19552 Within the hook, examine the cursor position and the command key
19553 and return nil or a valid handler as appropriate. Handler could
19554 be one of an interactive command, a function, or a form.
19556 Set `org-use-speed-commands' to non-nil value to enable this
19557 hook. The default setting is `org-speed-command-activate'."
19558 :group 'org-structure
19559 :version "24.1"
19560 :type 'hook)
19562 (defun org-self-insert-command (N)
19563 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19564 If the cursor is in a table looking at whitespace, the whitespace is
19565 overwritten, and the table is not marked as requiring realignment."
19566 (interactive "p")
19567 (org-check-before-invisible-edit 'insert)
19568 (cond
19569 ((and org-use-speed-commands
19570 (let ((kv (this-command-keys-vector)))
19571 (setq org-speed-command
19572 (run-hook-with-args-until-success
19573 'org-speed-command-hook
19574 (make-string 1 (aref kv (1- (length kv))))))))
19575 (cond
19576 ((commandp org-speed-command)
19577 (setq this-command org-speed-command)
19578 (call-interactively org-speed-command))
19579 ((functionp org-speed-command)
19580 (funcall org-speed-command))
19581 ((and org-speed-command (listp org-speed-command))
19582 (eval org-speed-command))
19583 (t (let (org-use-speed-commands)
19584 (call-interactively 'org-self-insert-command)))))
19585 ((and
19586 (org-at-table-p)
19587 (eq N 1)
19588 (not (org-region-active-p))
19589 (progn
19590 ;; Check if we blank the field, and if that triggers align.
19591 (and (featurep 'org-table) org-table-auto-blank-field
19592 (memq last-command
19593 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19594 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19595 ;; Got extra space, this field does not determine
19596 ;; column width.
19597 (let (org-table-may-need-update) (org-table-blank-field))
19598 ;; No extra space, this field may determine column
19599 ;; width.
19600 (org-table-blank-field)))
19602 (looking-at "[^|\n]* \\( \\)|"))
19603 ;; There is room for insertion without re-aligning the table.
19604 (delete-region (match-beginning 1) (match-end 1))
19605 (self-insert-command N))
19607 (setq org-table-may-need-update t)
19608 (self-insert-command N)
19609 (org-fix-tags-on-the-fly)
19610 (when org-self-insert-cluster-for-undo
19611 (if (not (eq last-command 'org-self-insert-command))
19612 (setq org-self-insert-command-undo-counter 1)
19613 (if (>= org-self-insert-command-undo-counter 20)
19614 (setq org-self-insert-command-undo-counter 1)
19615 (and (> org-self-insert-command-undo-counter 0)
19616 buffer-undo-list (listp buffer-undo-list)
19617 (not (cadr buffer-undo-list)) ; remove nil entry
19618 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19619 (setq org-self-insert-command-undo-counter
19620 (1+ org-self-insert-command-undo-counter))))))))
19622 (defun org-check-before-invisible-edit (kind)
19623 "Check is editing if kind KIND would be dangerous with invisible text around.
19624 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19625 ;; First, try to get out of here as quickly as possible, to reduce overhead
19626 (when (and org-catch-invisible-edits
19627 (or (not (boundp 'visible-mode)) (not visible-mode))
19628 (or (get-char-property (point) 'invisible)
19629 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19630 ;; OK, we need to take a closer look. Do not consider
19631 ;; invisibility obtained through text properties (e.g., link
19632 ;; fontification), as it cannot be toggled.
19633 (let* ((invisible-at-point
19634 (pcase (get-char-property-and-overlay (point) 'invisible)
19635 (`(,_ . ,(and (pred overlayp) o)) o)))
19636 ;; Assume that point cannot land in the middle of an
19637 ;; overlay, or between two overlays.
19638 (invisible-before-point
19639 (and (not invisible-at-point)
19640 (not (bobp))
19641 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19642 (`(,_ . ,(and (pred overlayp) o)) o))))
19643 (border-and-ok-direction
19645 ;; Check if we are acting predictably before invisible
19646 ;; text.
19647 (and invisible-at-point
19648 (memq kind '(insert delete-backward)))
19649 ;; Check if we are acting predictably after invisible text
19650 ;; This works not well, and I have turned it off. It seems
19651 ;; better to always show and stop after invisible text.
19652 ;; (and (not invisible-at-point) invisible-before-point
19653 ;; (memq kind '(insert delete)))
19655 (when (or invisible-at-point invisible-before-point)
19656 (when (eq org-catch-invisible-edits 'error)
19657 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19658 (if (and org-custom-properties-overlays
19659 (y-or-n-p "Display invisible properties in this buffer? "))
19660 (org-toggle-custom-properties-visibility)
19661 ;; Make the area visible
19662 (save-excursion
19663 (when invisible-before-point
19664 (goto-char
19665 (previous-single-char-property-change (point) 'invisible)))
19666 ;; Remove whatever overlay is currently making yet-to-be
19667 ;; edited text invisible. Also remove nested invisibility
19668 ;; related overlays.
19669 (delete-overlay (or invisible-at-point invisible-before-point))
19670 (let ((origin (if invisible-at-point (point) (1- (point)))))
19671 (while (pcase (get-char-property-and-overlay origin 'invisible)
19672 (`(,_ . ,(and (pred overlayp) o))
19673 (delete-overlay o)
19674 t)))))
19675 (cond
19676 ((eq org-catch-invisible-edits 'show)
19677 ;; That's it, we do the edit after showing
19678 (message
19679 "Unfolding invisible region around point before editing")
19680 (sit-for 1))
19681 ((and (eq org-catch-invisible-edits 'smart)
19682 border-and-ok-direction)
19683 (message "Unfolding invisible region around point before editing"))
19685 ;; Don't do the edit, make the user repeat it in full visibility
19686 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19688 (defun org-fix-tags-on-the-fly ()
19689 "Align tags in headline at point.
19690 Unlike to `org-set-tags', it ignores region and sorting."
19691 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19692 (org-at-heading-p))
19693 (let ((org-ignore-region t)
19694 (org-tags-sort-function nil))
19695 (org-set-tags nil t))))
19697 (defun org-delete-backward-char (N)
19698 "Like `delete-backward-char', insert whitespace at field end in tables.
19699 When deleting backwards, in tables this function will insert whitespace in
19700 front of the next \"|\" separator, to keep the table aligned. The table will
19701 still be marked for re-alignment if the field did fill the entire column,
19702 because, in this case the deletion might narrow the column."
19703 (interactive "p")
19704 (save-match-data
19705 (org-check-before-invisible-edit 'delete-backward)
19706 (if (and (org-at-table-p)
19707 (eq N 1)
19708 (not (org-region-active-p))
19709 (string-match "|" (buffer-substring (point-at-bol) (point)))
19710 (looking-at ".*?|"))
19711 (let ((pos (point))
19712 (noalign (looking-at "[^|\n\r]* |"))
19713 (c org-table-may-need-update))
19714 (backward-delete-char N)
19715 (unless overwrite-mode
19716 (skip-chars-forward "^|")
19717 (insert " ")
19718 (goto-char (1- pos)))
19719 ;; noalign: if there were two spaces at the end, this field
19720 ;; does not determine the width of the column.
19721 (when noalign (setq org-table-may-need-update c)))
19722 (backward-delete-char N)
19723 (org-fix-tags-on-the-fly))))
19725 (defun org-delete-char (N)
19726 "Like `delete-char', but insert whitespace at field end in tables.
19727 When deleting characters, in tables this function will insert whitespace in
19728 front of the next \"|\" separator, to keep the table aligned. The table will
19729 still be marked for re-alignment if the field did fill the entire column,
19730 because, in this case the deletion might narrow the column."
19731 (interactive "p")
19732 (save-match-data
19733 (org-check-before-invisible-edit 'delete)
19734 (if (and (org-at-table-p)
19735 (not (bolp))
19736 (not (= (char-after) ?|))
19737 (eq N 1))
19738 (if (looking-at ".*?|")
19739 (let ((pos (point))
19740 (noalign (looking-at "[^|\n\r]* |"))
19741 (c org-table-may-need-update))
19742 (replace-match
19743 (concat (substring (match-string 0) 1 -1) " |") nil t)
19744 (goto-char pos)
19745 ;; noalign: if there were two spaces at the end, this field
19746 ;; does not determine the width of the column.
19747 (when noalign (setq org-table-may-need-update c)))
19748 (delete-char N))
19749 (delete-char N)
19750 (org-fix-tags-on-the-fly))))
19752 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19753 (put 'org-self-insert-command 'delete-selection
19754 (lambda ()
19755 (not (run-hook-with-args-until-success
19756 'self-insert-uses-region-functions))))
19757 (put 'orgtbl-self-insert-command 'delete-selection
19758 (lambda ()
19759 (not (run-hook-with-args-until-success
19760 'self-insert-uses-region-functions))))
19761 (put 'org-delete-char 'delete-selection 'supersede)
19762 (put 'org-delete-backward-char 'delete-selection 'supersede)
19763 (put 'org-yank 'delete-selection 'yank)
19765 ;; Make `flyspell-mode' delay after some commands
19766 (put 'org-self-insert-command 'flyspell-delayed t)
19767 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19768 (put 'org-delete-char 'flyspell-delayed t)
19769 (put 'org-delete-backward-char 'flyspell-delayed t)
19771 ;; Make pabbrev-mode expand after Org mode commands
19772 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19773 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19775 (defun org-transpose-words ()
19776 "Transpose words for Org.
19777 This uses the `org-mode-transpose-word-syntax-table' syntax
19778 table, which interprets characters in `org-emphasis-alist' as
19779 word constituents."
19780 (interactive)
19781 (with-syntax-table org-mode-transpose-word-syntax-table
19782 (call-interactively 'transpose-words)))
19783 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19785 (defvar org-ctrl-c-ctrl-c-hook nil
19786 "Hook for functions attaching themselves to `C-c C-c'.
19788 This can be used to add additional functionality to the C-c C-c
19789 key which executes context-dependent commands. This hook is run
19790 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19791 run after the last test.
19793 Each function will be called with no arguments. The function
19794 must check if the context is appropriate for it to act. If yes,
19795 it should do its thing and then return a non-nil value. If the
19796 context is wrong, just do nothing and return nil.")
19798 (defvar org-ctrl-c-ctrl-c-final-hook nil
19799 "Hook for functions attaching themselves to `C-c C-c'.
19801 This can be used to add additional functionality to the C-c C-c
19802 key which executes context-dependent commands. This hook is run
19803 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19804 before the first test.
19806 Each function will be called with no arguments. The function
19807 must check if the context is appropriate for it to act. If yes,
19808 it should do its thing and then return a non-nil value. If the
19809 context is wrong, just do nothing and return nil.")
19811 (defvar org-tab-first-hook nil
19812 "Hook for functions to attach themselves to TAB.
19813 See `org-ctrl-c-ctrl-c-hook' for more information.
19814 This hook runs as the first action when TAB is pressed, even before
19815 `org-cycle' messes around with the `outline-regexp' to cater for
19816 inline tasks and plain list item folding.
19817 If any function in this hook returns t, any other actions that
19818 would have been caused by TAB (such as table field motion or visibility
19819 cycling) will not occur.")
19821 (defvar org-tab-after-check-for-table-hook nil
19822 "Hook for functions to attach themselves to TAB.
19823 See `org-ctrl-c-ctrl-c-hook' for more information.
19824 This hook runs after it has been established that the cursor is not in a
19825 table, but before checking if the cursor is in a headline or if global cycling
19826 should be done.
19827 If any function in this hook returns t, not other actions like visibility
19828 cycling will be done.")
19830 (defvar org-tab-after-check-for-cycling-hook nil
19831 "Hook for functions to attach themselves to TAB.
19832 See `org-ctrl-c-ctrl-c-hook' for more information.
19833 This hook runs after it has been established that not table field motion and
19834 not visibility should be done because of current context. This is probably
19835 the place where a package like yasnippets can hook in.")
19837 (defvar org-tab-before-tab-emulation-hook nil
19838 "Hook for functions to attach themselves to TAB.
19839 See `org-ctrl-c-ctrl-c-hook' for more information.
19840 This hook runs after every other options for TAB have been exhausted, but
19841 before indentation and \t insertion takes place.")
19843 (defvar org-metaleft-hook nil
19844 "Hook for functions attaching themselves to `M-left'.
19845 See `org-ctrl-c-ctrl-c-hook' for more information.")
19846 (defvar org-metaright-hook nil
19847 "Hook for functions attaching themselves to `M-right'.
19848 See `org-ctrl-c-ctrl-c-hook' for more information.")
19849 (defvar org-metaup-hook nil
19850 "Hook for functions attaching themselves to `M-up'.
19851 See `org-ctrl-c-ctrl-c-hook' for more information.")
19852 (defvar org-metadown-hook nil
19853 "Hook for functions attaching themselves to `M-down'.
19854 See `org-ctrl-c-ctrl-c-hook' for more information.")
19855 (defvar org-shiftmetaleft-hook nil
19856 "Hook for functions attaching themselves to `M-S-left'.
19857 See `org-ctrl-c-ctrl-c-hook' for more information.")
19858 (defvar org-shiftmetaright-hook nil
19859 "Hook for functions attaching themselves to `M-S-right'.
19860 See `org-ctrl-c-ctrl-c-hook' for more information.")
19861 (defvar org-shiftmetaup-hook nil
19862 "Hook for functions attaching themselves to `M-S-up'.
19863 See `org-ctrl-c-ctrl-c-hook' for more information.")
19864 (defvar org-shiftmetadown-hook nil
19865 "Hook for functions attaching themselves to `M-S-down'.
19866 See `org-ctrl-c-ctrl-c-hook' for more information.")
19867 (defvar org-metareturn-hook nil
19868 "Hook for functions attaching themselves to `M-RET'.
19869 See `org-ctrl-c-ctrl-c-hook' for more information.")
19870 (defvar org-shiftup-hook nil
19871 "Hook for functions attaching themselves to `S-up'.
19872 See `org-ctrl-c-ctrl-c-hook' for more information.")
19873 (defvar org-shiftup-final-hook nil
19874 "Hook for functions attaching themselves to `S-up'.
19875 This one runs after all other options except shift-select have been excluded.
19876 See `org-ctrl-c-ctrl-c-hook' for more information.")
19877 (defvar org-shiftdown-hook nil
19878 "Hook for functions attaching themselves to `S-down'.
19879 See `org-ctrl-c-ctrl-c-hook' for more information.")
19880 (defvar org-shiftdown-final-hook nil
19881 "Hook for functions attaching themselves to `S-down'.
19882 This one runs after all other options except shift-select have been excluded.
19883 See `org-ctrl-c-ctrl-c-hook' for more information.")
19884 (defvar org-shiftleft-hook nil
19885 "Hook for functions attaching themselves to `S-left'.
19886 See `org-ctrl-c-ctrl-c-hook' for more information.")
19887 (defvar org-shiftleft-final-hook nil
19888 "Hook for functions attaching themselves to `S-left'.
19889 This one runs after all other options except shift-select have been excluded.
19890 See `org-ctrl-c-ctrl-c-hook' for more information.")
19891 (defvar org-shiftright-hook nil
19892 "Hook for functions attaching themselves to `S-right'.
19893 See `org-ctrl-c-ctrl-c-hook' for more information.")
19894 (defvar org-shiftright-final-hook nil
19895 "Hook for functions attaching themselves to `S-right'.
19896 This one runs after all other options except shift-select have been excluded.
19897 See `org-ctrl-c-ctrl-c-hook' for more information.")
19899 (defun org-modifier-cursor-error ()
19900 "Throw an error, a modified cursor command was applied in wrong context."
19901 (user-error "This command is active in special context like tables, headlines or items"))
19903 (defun org-shiftselect-error ()
19904 "Throw an error because Shift-Cursor command was applied in wrong context."
19905 (if (and (boundp 'shift-select-mode) shift-select-mode)
19906 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19907 (user-error "This command works only in special context like headlines or timestamps")))
19909 (defun org-call-for-shift-select (cmd)
19910 (let ((this-command-keys-shift-translated t))
19911 (call-interactively cmd)))
19913 (defun org-shifttab (&optional arg)
19914 "Global visibility cycling or move to previous table field.
19915 Call `org-table-previous-field' within a table.
19916 When ARG is nil, cycle globally through visibility states.
19917 When ARG is a numeric prefix, show contents of this level."
19918 (interactive "P")
19919 (cond
19920 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19921 ((integerp arg)
19922 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19923 (message "Content view to level: %d" arg)
19924 (org-content (prefix-numeric-value arg2))
19925 (org-cycle-show-empty-lines t)
19926 (setq org-cycle-global-status 'overview)))
19927 (t (call-interactively 'org-global-cycle))))
19929 (defun org-shiftmetaleft ()
19930 "Promote subtree or delete table column.
19931 Calls `org-promote-subtree', `org-outdent-item-tree', or
19932 `org-table-delete-column', depending on context. See the
19933 individual commands for more information."
19934 (interactive)
19935 (cond
19936 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19937 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19938 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19939 ((if (not (org-region-active-p)) (org-at-item-p)
19940 (save-excursion (goto-char (region-beginning))
19941 (org-at-item-p)))
19942 (call-interactively 'org-outdent-item-tree))
19943 (t (org-modifier-cursor-error))))
19945 (defun org-shiftmetaright ()
19946 "Demote subtree or insert table column.
19947 Calls `org-demote-subtree', `org-indent-item-tree', or
19948 `org-table-insert-column', depending on context. See the
19949 individual commands for more information."
19950 (interactive)
19951 (cond
19952 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19953 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19954 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19955 ((if (not (org-region-active-p)) (org-at-item-p)
19956 (save-excursion (goto-char (region-beginning))
19957 (org-at-item-p)))
19958 (call-interactively 'org-indent-item-tree))
19959 (t (org-modifier-cursor-error))))
19961 (defun org-shiftmetaup (&optional _arg)
19962 "Drag the line at point up.
19963 In a table, kill the current row.
19964 On a clock timestamp, update the value of the timestamp like `S-<up>'
19965 but also adjust the previous clocked item in the clock history.
19966 Everywhere else, drag the line at point up."
19967 (interactive "P")
19968 (cond
19969 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19970 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19971 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19972 (call-interactively 'org-timestamp-up)))
19973 (t (call-interactively 'org-drag-line-backward))))
19975 (defun org-shiftmetadown (&optional _arg)
19976 "Drag the line at point down.
19977 In a table, insert an empty row at the current line.
19978 On a clock timestamp, update the value of the timestamp like `S-<down>'
19979 but also adjust the previous clocked item in the clock history.
19980 Everywhere else, drag the line at point down."
19981 (interactive "P")
19982 (cond
19983 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19984 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19985 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19986 (call-interactively 'org-timestamp-down)))
19987 (t (call-interactively 'org-drag-line-forward))))
19989 (defsubst org-hidden-tree-error ()
19990 (user-error
19991 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19993 (defun org-metaleft (&optional _arg)
19994 "Promote heading, list item at point or move table column left.
19996 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19997 depending on context. With no specific context, calls the Emacs
19998 default `backward-word'. See the individual commands for more
19999 information.
20001 This function runs the hook `org-metaleft-hook' as a first step,
20002 and returns at first non-nil value."
20003 (interactive "P")
20004 (cond
20005 ((run-hook-with-args-until-success 'org-metaleft-hook))
20006 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20007 ((org-with-limited-levels
20008 (or (org-at-heading-p)
20009 (and (org-region-active-p)
20010 (save-excursion
20011 (goto-char (region-beginning))
20012 (org-at-heading-p)))))
20013 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20014 (call-interactively 'org-do-promote))
20015 ;; At an inline task.
20016 ((org-at-heading-p)
20017 (call-interactively 'org-inlinetask-promote))
20018 ((or (org-at-item-p)
20019 (and (org-region-active-p)
20020 (save-excursion
20021 (goto-char (region-beginning))
20022 (org-at-item-p))))
20023 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20024 (call-interactively 'org-outdent-item))
20025 (t (call-interactively 'backward-word))))
20027 (defun org-metaright (&optional _arg)
20028 "Demote heading, list item at point or move table column right.
20030 In front of a drawer or a block keyword, indent it correctly.
20032 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20033 `org-indent-drawer' or `org-indent-block' depending on context.
20034 With no specific context, calls the Emacs default `forward-word'.
20035 See the individual commands for more information.
20037 This function runs the hook `org-metaright-hook' as a first step,
20038 and returns at first non-nil value."
20039 (interactive "P")
20040 (cond
20041 ((run-hook-with-args-until-success 'org-metaright-hook))
20042 ((org-at-table-p) (call-interactively 'org-table-move-column))
20043 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20044 ((org-at-block-p) (call-interactively 'org-indent-block))
20045 ((org-with-limited-levels
20046 (or (org-at-heading-p)
20047 (and (org-region-active-p)
20048 (save-excursion
20049 (goto-char (region-beginning))
20050 (org-at-heading-p)))))
20051 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20052 (call-interactively 'org-do-demote))
20053 ;; At an inline task.
20054 ((org-at-heading-p)
20055 (call-interactively 'org-inlinetask-demote))
20056 ((or (org-at-item-p)
20057 (and (org-region-active-p)
20058 (save-excursion
20059 (goto-char (region-beginning))
20060 (org-at-item-p))))
20061 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20062 (call-interactively 'org-indent-item))
20063 (t (call-interactively 'forward-word))))
20065 (defun org-check-for-hidden (what)
20066 "Check if there are hidden headlines/items in the current visual line.
20067 WHAT can be either `headlines' or `items'. If the current line is
20068 an outline or item heading and it has a folded subtree below it,
20069 this function returns t, nil otherwise."
20070 (let ((re (cond
20071 ((eq what 'headlines) org-outline-regexp-bol)
20072 ((eq what 'items) (org-item-beginning-re))
20073 (t (error "This should not happen"))))
20074 beg end)
20075 (save-excursion
20076 (catch 'exit
20077 (unless (org-region-active-p)
20078 (setq beg (point-at-bol))
20079 (beginning-of-line 2)
20080 (while (and (not (eobp)) ;; this is like `next-line'
20081 (get-char-property (1- (point)) 'invisible))
20082 (beginning-of-line 2))
20083 (setq end (point))
20084 (goto-char beg)
20085 (goto-char (point-at-eol))
20086 (setq end (max end (point)))
20087 (while (re-search-forward re end t)
20088 (when (get-char-property (match-beginning 0) 'invisible)
20089 (throw 'exit t))))
20090 nil))))
20092 (defun org-metaup (&optional _arg)
20093 "Move subtree up or move table row up.
20094 Calls `org-move-subtree-up' or `org-table-move-row' or
20095 `org-move-item-up', depending on context. See the individual commands
20096 for more information."
20097 (interactive "P")
20098 (cond
20099 ((run-hook-with-args-until-success 'org-metaup-hook))
20100 ((org-region-active-p)
20101 (let* ((a (min (region-beginning) (region-end)))
20102 (b (1- (max (region-beginning) (region-end))))
20103 (c (save-excursion (goto-char a)
20104 (move-beginning-of-line 0)))
20105 (d (save-excursion (goto-char a)
20106 (move-end-of-line 0) (point))))
20107 (transpose-regions a b c d)
20108 (goto-char c)))
20109 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20110 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20111 ((org-at-item-p) (call-interactively 'org-move-item-up))
20112 (t (org-drag-element-backward))))
20114 (defun org-metadown (&optional _arg)
20115 "Move subtree down or move table row down.
20116 Calls `org-move-subtree-down' or `org-table-move-row' or
20117 `org-move-item-down', depending on context. See the individual
20118 commands for more information."
20119 (interactive "P")
20120 (cond
20121 ((run-hook-with-args-until-success 'org-metadown-hook))
20122 ((org-region-active-p)
20123 (let* ((a (min (region-beginning) (region-end)))
20124 (b (max (region-beginning) (region-end)))
20125 (c (save-excursion (goto-char b)
20126 (move-beginning-of-line 1)))
20127 (d (save-excursion (goto-char b)
20128 (move-end-of-line 1) (1+ (point)))))
20129 (transpose-regions a b c d)
20130 (goto-char d)))
20131 ((org-at-table-p) (call-interactively 'org-table-move-row))
20132 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20133 ((org-at-item-p) (call-interactively 'org-move-item-down))
20134 (t (org-drag-element-forward))))
20136 (defun org-shiftup (&optional arg)
20137 "Increase item in timestamp or increase priority of current headline.
20138 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20139 depending on context. See the individual commands for more information."
20140 (interactive "P")
20141 (cond
20142 ((run-hook-with-args-until-success 'org-shiftup-hook))
20143 ((and org-support-shift-select (org-region-active-p))
20144 (org-call-for-shift-select 'previous-line))
20145 ((org-at-timestamp-p 'lax)
20146 (call-interactively (if org-edit-timestamp-down-means-later
20147 'org-timestamp-down 'org-timestamp-up)))
20148 ((and (not (eq org-support-shift-select 'always))
20149 org-enable-priority-commands
20150 (org-at-heading-p))
20151 (call-interactively 'org-priority-up))
20152 ((and (not org-support-shift-select) (org-at-item-p))
20153 (call-interactively 'org-previous-item))
20154 ((org-clocktable-try-shift 'up arg))
20155 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20156 (org-support-shift-select
20157 (org-call-for-shift-select 'previous-line))
20158 (t (org-shiftselect-error))))
20160 (defun org-shiftdown (&optional arg)
20161 "Decrease item in timestamp or decrease priority of current headline.
20162 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20163 depending on context. See the individual commands for more information."
20164 (interactive "P")
20165 (cond
20166 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20167 ((and org-support-shift-select (org-region-active-p))
20168 (org-call-for-shift-select 'next-line))
20169 ((org-at-timestamp-p 'lax)
20170 (call-interactively (if org-edit-timestamp-down-means-later
20171 'org-timestamp-up 'org-timestamp-down)))
20172 ((and (not (eq org-support-shift-select 'always))
20173 org-enable-priority-commands
20174 (org-at-heading-p))
20175 (call-interactively 'org-priority-down))
20176 ((and (not org-support-shift-select) (org-at-item-p))
20177 (call-interactively 'org-next-item))
20178 ((org-clocktable-try-shift 'down arg))
20179 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20180 (org-support-shift-select
20181 (org-call-for-shift-select 'next-line))
20182 (t (org-shiftselect-error))))
20184 (defun org-shiftright (&optional arg)
20185 "Cycle the thing at point or in the current line, depending on context.
20186 Depending on context, this does one of the following:
20188 - switch a timestamp at point one day into the future
20189 - on a headline, switch to the next TODO keyword.
20190 - on an item, switch entire list to the next bullet type
20191 - on a property line, switch to the next allowed value
20192 - on a clocktable definition line, move time block into the future"
20193 (interactive "P")
20194 (cond
20195 ((run-hook-with-args-until-success 'org-shiftright-hook))
20196 ((and org-support-shift-select (org-region-active-p))
20197 (org-call-for-shift-select 'forward-char))
20198 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20199 ((and (not (eq org-support-shift-select 'always))
20200 (org-at-heading-p))
20201 (let ((org-inhibit-logging
20202 (not org-treat-S-cursor-todo-selection-as-state-change))
20203 (org-inhibit-blocking
20204 (not org-treat-S-cursor-todo-selection-as-state-change)))
20205 (org-call-with-arg 'org-todo 'right)))
20206 ((or (and org-support-shift-select
20207 (not (eq org-support-shift-select 'always))
20208 (org-at-item-bullet-p))
20209 (and (not org-support-shift-select) (org-at-item-p)))
20210 (org-call-with-arg 'org-cycle-list-bullet nil))
20211 ((and (not (eq org-support-shift-select 'always))
20212 (org-at-property-p))
20213 (call-interactively 'org-property-next-allowed-value))
20214 ((org-clocktable-try-shift 'right arg))
20215 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20216 (org-support-shift-select
20217 (org-call-for-shift-select 'forward-char))
20218 (t (org-shiftselect-error))))
20220 (defun org-shiftleft (&optional arg)
20221 "Cycle the thing at point or in the current line, depending on context.
20222 Depending on context, this does one of the following:
20224 - switch a timestamp at point one day into the past
20225 - on a headline, switch to the previous TODO keyword.
20226 - on an item, switch entire list to the previous bullet type
20227 - on a property line, switch to the previous allowed value
20228 - on a clocktable definition line, move time block into the past"
20229 (interactive "P")
20230 (cond
20231 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20232 ((and org-support-shift-select (org-region-active-p))
20233 (org-call-for-shift-select 'backward-char))
20234 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20235 ((and (not (eq org-support-shift-select 'always))
20236 (org-at-heading-p))
20237 (let ((org-inhibit-logging
20238 (not org-treat-S-cursor-todo-selection-as-state-change))
20239 (org-inhibit-blocking
20240 (not org-treat-S-cursor-todo-selection-as-state-change)))
20241 (org-call-with-arg 'org-todo 'left)))
20242 ((or (and org-support-shift-select
20243 (not (eq org-support-shift-select 'always))
20244 (org-at-item-bullet-p))
20245 (and (not org-support-shift-select) (org-at-item-p)))
20246 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20247 ((and (not (eq org-support-shift-select 'always))
20248 (org-at-property-p))
20249 (call-interactively 'org-property-previous-allowed-value))
20250 ((org-clocktable-try-shift 'left arg))
20251 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20252 (org-support-shift-select
20253 (org-call-for-shift-select 'backward-char))
20254 (t (org-shiftselect-error))))
20256 (defun org-shiftcontrolright ()
20257 "Switch to next TODO set."
20258 (interactive)
20259 (cond
20260 ((and org-support-shift-select (org-region-active-p))
20261 (org-call-for-shift-select 'forward-word))
20262 ((and (not (eq org-support-shift-select 'always))
20263 (org-at-heading-p))
20264 (org-call-with-arg 'org-todo 'nextset))
20265 (org-support-shift-select
20266 (org-call-for-shift-select 'forward-word))
20267 (t (org-shiftselect-error))))
20269 (defun org-shiftcontrolleft ()
20270 "Switch to previous TODO set."
20271 (interactive)
20272 (cond
20273 ((and org-support-shift-select (org-region-active-p))
20274 (org-call-for-shift-select 'backward-word))
20275 ((and (not (eq org-support-shift-select 'always))
20276 (org-at-heading-p))
20277 (org-call-with-arg 'org-todo 'previousset))
20278 (org-support-shift-select
20279 (org-call-for-shift-select 'backward-word))
20280 (t (org-shiftselect-error))))
20282 (defun org-shiftcontrolup (&optional n)
20283 "Change timestamps synchronously up in CLOCK log lines.
20284 Optional argument N tells to change by that many units."
20285 (interactive "P")
20286 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20287 (let (org-support-shift-select)
20288 (org-clock-timestamps-up n))
20289 (user-error "Not at a clock log")))
20291 (defun org-shiftcontroldown (&optional n)
20292 "Change timestamps synchronously down in CLOCK log lines.
20293 Optional argument N tells to change by that many units."
20294 (interactive "P")
20295 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20296 (let (org-support-shift-select)
20297 (org-clock-timestamps-down n))
20298 (user-error "Not at a clock log")))
20300 (defun org-increase-number-at-point (&optional inc)
20301 "Increment the number at point.
20302 With an optional prefix numeric argument INC, increment using
20303 this numeric value."
20304 (interactive "p")
20305 (if (not (number-at-point))
20306 (user-error "Not on a number")
20307 (unless inc (setq inc 1))
20308 (let ((pos (point))
20309 (beg (skip-chars-backward "-+^/*0-9eE."))
20310 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20311 (setq nap (buffer-substring-no-properties
20312 (+ pos beg) (+ pos beg end)))
20313 (delete-region (+ pos beg) (+ pos beg end))
20314 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20315 (when (org-at-table-p)
20316 (org-table-align)
20317 (org-table-end-of-field 1))))
20319 (defun org-decrease-number-at-point (&optional inc)
20320 "Decrement the number at point.
20321 With an optional prefix numeric argument INC, decrement using
20322 this numeric value."
20323 (interactive "p")
20324 (org-increase-number-at-point (- (or inc 1))))
20326 (defun org-ctrl-c-ret ()
20327 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20328 (interactive)
20329 (cond
20330 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20331 (t (call-interactively 'org-insert-heading))))
20333 (defun org-find-visible ()
20334 (let ((s (point)))
20335 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20336 (get-char-property s 'invisible)))
20338 (defun org-find-invisible ()
20339 (let ((s (point)))
20340 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20341 (not (get-char-property s 'invisible))))
20344 (defun org-copy-visible (beg end)
20345 "Copy the visible parts of the region."
20346 (interactive "r")
20347 (let ((result ""))
20348 (while (/= beg end)
20349 (when (get-char-property beg 'invisible)
20350 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20351 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20352 (setq result (concat result (buffer-substring beg next)))
20353 (setq beg next)))
20354 (kill-new result)))
20356 (defun org-copy-special ()
20357 "Copy region in table or copy current subtree.
20358 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20359 context. See the individual commands for more information."
20360 (interactive)
20361 (call-interactively
20362 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20364 (defun org-cut-special ()
20365 "Cut region in table or cut current subtree.
20366 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20367 context. See the individual commands for more information."
20368 (interactive)
20369 (call-interactively
20370 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20372 (defun org-paste-special (arg)
20373 "Paste rectangular region into table, or past subtree relative to level.
20374 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20375 See the individual commands for more information."
20376 (interactive "P")
20377 (if (org-at-table-p)
20378 (org-table-paste-rectangle)
20379 (org-paste-subtree arg)))
20381 (defun org-edit-special (&optional arg)
20382 "Call a special editor for the element at point.
20383 When at a table, call the formula editor with `org-table-edit-formulas'.
20384 When in a source code block, call `org-edit-src-code'.
20385 When in a fixed-width region, call `org-edit-fixed-width-region'.
20386 When in an export block, call `org-edit-export-block'.
20387 When in a LaTeX environment, call `org-edit-latex-environment'.
20388 When at an #+INCLUDE keyword, visit the included file.
20389 When at a footnote reference, call `org-edit-footnote-reference'
20390 On a link, call `ffap' to visit the link at point.
20391 Otherwise, return a user error."
20392 (interactive "P")
20393 (let ((element (org-element-at-point)))
20394 (barf-if-buffer-read-only)
20395 (pcase (org-element-type element)
20396 (`src-block
20397 (if (not arg) (org-edit-src-code)
20398 (let* ((info (org-babel-get-src-block-info))
20399 (lang (nth 0 info))
20400 (params (nth 2 info))
20401 (session (cdr (assq :session params))))
20402 (if (not session) (org-edit-src-code)
20403 ;; At a src-block with a session and function called with
20404 ;; an ARG: switch to the buffer related to the inferior
20405 ;; process.
20406 (switch-to-buffer
20407 (funcall (intern (concat "org-babel-prep-session:" lang))
20408 session params))))))
20409 (`keyword
20410 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20411 (org-open-link-from-string
20412 (format "[[%s]]"
20413 (expand-file-name
20414 (let ((value (org-element-property :value element)))
20415 (cond ((org-file-url-p value)
20416 (user-error "The file is specified as a URL, cannot be edited"))
20417 ((not (org-string-nw-p value))
20418 (user-error "No file to edit"))
20419 ((string-match "\\`\"\\(.*?\\)\"" value)
20420 (match-string 1 value))
20421 ((string-match "\\`[^ \t\"]\\S-*" value)
20422 (match-string 0 value))
20423 (t (user-error "No valid file specified")))))))
20424 (user-error "No special environment to edit here")))
20425 (`table
20426 (if (eq (org-element-property :type element) 'table.el)
20427 (org-edit-table.el)
20428 (call-interactively 'org-table-edit-formulas)))
20429 ;; Only Org tables contain `table-row' type elements.
20430 (`table-row (call-interactively 'org-table-edit-formulas))
20431 (`example-block (org-edit-src-code))
20432 (`export-block (org-edit-export-block))
20433 (`fixed-width (org-edit-fixed-width-region))
20434 (`latex-environment (org-edit-latex-environment))
20436 ;; No notable element at point. Though, we may be at a link or
20437 ;; a footnote reference, which are objects. Thus, scan deeper.
20438 (let ((context (org-element-context element)))
20439 (pcase (org-element-type context)
20440 (`footnote-reference (org-edit-footnote-reference))
20441 (`inline-src-block (org-edit-inline-src-code))
20442 (`link (call-interactively #'ffap))
20443 (_ (user-error "No special environment to edit here"))))))))
20445 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20446 (defun org-ctrl-c-ctrl-c (&optional arg)
20447 "Set tags in headline, or update according to changed information at point.
20449 This command does many different things, depending on context:
20451 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20452 this is what we do.
20454 - If the cursor is on a statistics cookie, update it.
20456 - If the cursor is in a headline, prompt for tags and insert them
20457 into the current line, aligned to `org-tags-column'. When called
20458 with prefix arg, realign all tags in the current buffer.
20460 - If the cursor is in one of the special #+KEYWORD lines, this
20461 triggers scanning the buffer for these lines and updating the
20462 information.
20464 - If the cursor is inside a table, realign the table. This command
20465 works even if the automatic table editor has been turned off.
20467 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20468 the entire table.
20470 - If the cursor is at a footnote reference or definition, jump to
20471 the corresponding definition or references, respectively.
20473 - If the cursor is a the beginning of a dynamic block, update it.
20475 - If the current buffer is a capture buffer, close note and file it.
20477 - If the cursor is on a <<<target>>>, update radio targets and
20478 corresponding links in this buffer.
20480 - If the cursor is on a numbered item in a plain list, renumber the
20481 ordered list.
20483 - If the cursor is on a checkbox, toggle it.
20485 - If the cursor is on a code block, evaluate it. The variable
20486 `org-confirm-babel-evaluate' can be used to control prompting
20487 before code block evaluation, by default every code block
20488 evaluation requires confirmation. Code block evaluation can be
20489 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20490 (interactive "P")
20491 (cond
20492 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20493 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20494 (org-remove-occur-highlights)
20495 (message "Temporary highlights/overlays removed from current buffer"))
20496 ((and (local-variable-p 'org-finish-function)
20497 (fboundp org-finish-function))
20498 (funcall org-finish-function))
20499 ((org-babel-hash-at-point))
20500 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20502 (let* ((context
20503 (org-element-lineage
20504 (org-element-context)
20505 ;; Limit to supported contexts.
20506 '(babel-call clock dynamic-block footnote-definition
20507 footnote-reference inline-babel-call inline-src-block
20508 inlinetask item keyword node-property paragraph
20509 plain-list planning property-drawer radio-target
20510 src-block statistics-cookie table table-cell table-row
20511 timestamp)
20513 (type (org-element-type context)))
20514 ;; For convenience: at the first line of a paragraph on the same
20515 ;; line as an item, apply function on that item instead.
20516 (when (eq type 'paragraph)
20517 (let ((parent (org-element-property :parent context)))
20518 (when (and (eq (org-element-type parent) 'item)
20519 (= (line-beginning-position)
20520 (org-element-property :begin parent)))
20521 (setq context parent)
20522 (setq type 'item))))
20523 ;; Act according to type of element or object at point.
20525 ;; Do nothing on a blank line, except if it is contained in
20526 ;; a src block. Hence, we first check if point is in such
20527 ;; a block and then if it is at a blank line.
20528 (pcase type
20529 ((or `inline-src-block `src-block)
20530 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20531 (org-babel-eval-wipe-error-buffer)
20532 (org-babel-execute-src-block
20533 current-prefix-arg (org-babel-get-src-block-info nil context))))
20534 ((guard (org-match-line "[ \t]*$"))
20535 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20536 (user-error
20537 (substitute-command-keys
20538 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20539 ((or `babel-call `inline-babel-call)
20540 (let ((info (org-babel-lob-get-info context)))
20541 (when info (org-babel-execute-src-block nil info))))
20542 (`clock (org-clock-update-time-maybe))
20543 (`dynamic-block
20544 (save-excursion
20545 (goto-char (org-element-property :post-affiliated context))
20546 (org-update-dblock)))
20547 (`footnote-definition
20548 (goto-char (org-element-property :post-affiliated context))
20549 (call-interactively 'org-footnote-action))
20550 (`footnote-reference (call-interactively #'org-footnote-action))
20551 ((or `headline `inlinetask)
20552 (save-excursion (goto-char (org-element-property :begin context))
20553 (call-interactively #'org-set-tags)))
20554 (`item
20555 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20556 ;; unconditionally, whereas `C-u' will toggle its presence.
20557 ;; Without a universal argument, if the item has a checkbox,
20558 ;; toggle it. Otherwise repair the list.
20559 (let* ((box (org-element-property :checkbox context))
20560 (struct (org-element-property :structure context))
20561 (old-struct (copy-tree struct))
20562 (parents (org-list-parents-alist struct))
20563 (prevs (org-list-prevs-alist struct))
20564 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20565 (org-list-set-checkbox
20566 (org-element-property :begin context) struct
20567 (cond ((equal arg '(16)) "[-]")
20568 ((and (not box) (equal arg '(4))) "[ ]")
20569 ((or (not box) (equal arg '(4))) nil)
20570 ((eq box 'on) "[ ]")
20571 (t "[X]")))
20572 ;; Mimic `org-list-write-struct' but with grabbing a return
20573 ;; value from `org-list-struct-fix-box'.
20574 (org-list-struct-fix-ind struct parents 2)
20575 (org-list-struct-fix-item-end struct)
20576 (org-list-struct-fix-bul struct prevs)
20577 (org-list-struct-fix-ind struct parents)
20578 (let ((block-item
20579 (org-list-struct-fix-box struct parents prevs orderedp)))
20580 (if (and box (equal struct old-struct))
20581 (if (equal arg '(16))
20582 (message "Checkboxes already reset")
20583 (user-error "Cannot toggle this checkbox: %s"
20584 (if (eq box 'on)
20585 "all subitems checked"
20586 "unchecked subitems")))
20587 (org-list-struct-apply-struct struct old-struct)
20588 (org-update-checkbox-count-maybe))
20589 (when block-item
20590 (message "Checkboxes were removed due to empty box at line %d"
20591 (org-current-line block-item))))))
20592 (`keyword
20593 (let ((org-inhibit-startup-visibility-stuff t)
20594 (org-startup-align-all-tables nil))
20595 (when (boundp 'org-table-coordinate-overlays)
20596 (mapc #'delete-overlay org-table-coordinate-overlays)
20597 (setq org-table-coordinate-overlays nil))
20598 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20599 (message "Local setup has been refreshed"))
20600 (`plain-list
20601 ;; At a plain list, with a double C-u argument, set
20602 ;; checkboxes of each item to "[-]", whereas a single one
20603 ;; will toggle their presence according to the state of the
20604 ;; first item in the list. Without an argument, repair the
20605 ;; list.
20606 (let* ((begin (org-element-property :contents-begin context))
20607 (beginm (move-marker (make-marker) begin))
20608 (struct (org-element-property :structure context))
20609 (old-struct (copy-tree struct))
20610 (first-box (save-excursion
20611 (goto-char begin)
20612 (looking-at org-list-full-item-re)
20613 (match-string-no-properties 3)))
20614 (new-box (cond ((equal arg '(16)) "[-]")
20615 ((equal arg '(4)) (unless first-box "[ ]"))
20616 ((equal first-box "[X]") "[ ]")
20617 (t "[X]"))))
20618 (cond
20619 (arg
20620 (dolist (pos
20621 (org-list-get-all-items
20622 begin struct (org-list-prevs-alist struct)))
20623 (org-list-set-checkbox pos struct new-box)))
20624 ((and first-box (eq (point) begin))
20625 ;; For convenience, when point is at bol on the first
20626 ;; item of the list and no argument is provided, simply
20627 ;; toggle checkbox of that item, if any.
20628 (org-list-set-checkbox begin struct new-box)))
20629 (org-list-write-struct
20630 struct (org-list-parents-alist struct) old-struct)
20631 (org-update-checkbox-count-maybe)
20632 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20633 ((or `property-drawer `node-property)
20634 (call-interactively #'org-property-action))
20635 (`radio-target
20636 (call-interactively #'org-update-radio-target-regexp))
20637 (`statistics-cookie
20638 (call-interactively #'org-update-statistics-cookies))
20639 ((or `table `table-cell `table-row)
20640 ;; At a table, recalculate every field and align it. Also
20641 ;; send the table if necessary. If the table has
20642 ;; a `table.el' type, just give up. At a table row or cell,
20643 ;; maybe recalculate line but always align table.
20644 (if (eq (org-element-property :type context) 'table.el)
20645 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20646 Use `\\[org-edit-special]' to edit table.el tables"))
20647 (if (or (eq type 'table)
20648 ;; Check if point is at a TBLFM line.
20649 (and (eq type 'table-row)
20650 (= (point) (org-element-property :end context))))
20651 (save-excursion
20652 (if (org-at-TBLFM-p)
20653 (progn (require 'org-table)
20654 (org-table-calc-current-TBLFM))
20655 (goto-char (org-element-property :contents-begin context))
20656 (org-call-with-arg 'org-table-recalculate (or arg t))
20657 (orgtbl-send-table 'maybe)))
20658 (org-table-maybe-eval-formula)
20659 (cond (arg (call-interactively #'org-table-recalculate))
20660 ((org-table-maybe-recalculate-line))
20661 (t (org-table-align))))))
20662 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20663 (org-timestamp-change 0 'day))
20664 ((and `nil (guard (org-at-heading-p)))
20665 ;; When point is on an unsupported object type, we can miss
20666 ;; the fact that it also is at a heading. Handle it here.
20667 (call-interactively #'org-set-tags))
20668 ((guard
20669 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20671 (user-error
20672 (substitute-command-keys
20673 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20675 (defun org-mode-restart ()
20676 (interactive)
20677 (let ((indent-status (bound-and-true-p org-indent-mode)))
20678 (funcall major-mode)
20679 (hack-local-variables)
20680 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20681 (org-indent-mode -1))
20682 (org-reset-file-cache))
20683 (message "%s restarted" major-mode))
20685 (defun org-kill-note-or-show-branches ()
20686 "Abort storing current note, or call `outline-show-branches'."
20687 (interactive)
20688 (if (not org-finish-function)
20689 (progn
20690 (outline-hide-subtree)
20691 (call-interactively 'outline-show-branches))
20692 (let ((org-note-abort t))
20693 (funcall org-finish-function))))
20695 (defun org-delete-indentation (&optional arg)
20696 "Join current line to previous and fix whitespace at join.
20698 If previous line is a headline add to headline title. Otherwise
20699 the function calls `delete-indentation'.
20701 With a non-nil optional argument, join it to the following one."
20702 (interactive "*P")
20703 (if (save-excursion
20704 (beginning-of-line (if arg 1 0))
20705 (let ((case-fold-search nil))
20706 (looking-at org-complex-heading-regexp)))
20707 ;; At headline.
20708 (let ((tags-column (when (match-beginning 5)
20709 (save-excursion (goto-char (match-beginning 5))
20710 (current-column))))
20711 (string (concat " " (progn (when arg (forward-line 1))
20712 (org-trim (delete-and-extract-region
20713 (line-beginning-position)
20714 (line-end-position)))))))
20715 (unless (bobp) (delete-region (point) (1- (point))))
20716 (goto-char (or (match-end 4)
20717 (match-beginning 5)
20718 (match-end 0)))
20719 (skip-chars-backward " \t")
20720 (save-excursion (insert string))
20721 ;; Adjust alignment of tags.
20722 (cond
20723 ((not tags-column)) ;no tags
20724 (org-auto-align-tags (org-set-tags nil t))
20725 (t (org--align-tags-here tags-column)))) ;preserve tags column
20726 (delete-indentation arg)))
20728 (defun org-open-line (n)
20729 "Insert a new row in tables, call `open-line' elsewhere.
20730 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20731 As a special case, when a document starts with a table, allow to
20732 call `open-line' on the very first character."
20733 (interactive "*p")
20734 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20735 (org-table-insert-row)
20736 (open-line n)))
20738 (defun org-return (&optional indent)
20739 "Goto next table row or insert a newline.
20741 Calls `org-table-next-row' or `newline', depending on context.
20743 When optional INDENT argument is non-nil, call
20744 `newline-and-indent' instead of `newline'.
20746 When `org-return-follows-link' is non-nil and point is on
20747 a timestamp or a link, call `org-open-at-point'. However, it
20748 will not happen if point is in a table or on a \"dead\"
20749 object (e.g., within a comment). In these case, you need to use
20750 `org-open-at-point' directly."
20751 (interactive)
20752 (let ((context (if org-return-follows-link (org-element-context)
20753 (org-element-at-point))))
20754 (cond
20755 ;; In a table, call `org-table-next-row'. However, before first
20756 ;; column or after last one, split the table.
20757 ((or (and (eq (org-element-type context) 'table)
20758 (>= (point) (org-element-property :contents-begin context))
20759 (< (point) (org-element-property :contents-end context)))
20760 (org-element-lineage context '(table-row table-cell) t))
20761 (if (or (looking-at-p "[ \t]*$")
20762 (save-excursion (skip-chars-backward " \t") (bolp)))
20763 (insert "\n")
20764 (org-table-justify-field-maybe)
20765 (call-interactively #'org-table-next-row)))
20766 ;; On a link or a timestamp, call `org-open-at-point' if
20767 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20768 ;; locations, e.g., in a comment, as `org-open-at-point'.
20769 ((and org-return-follows-link
20770 (or (org-in-regexp org-ts-regexp-both nil t)
20771 (org-in-regexp org-tsr-regexp-both nil t)
20772 (org-in-regexp org-any-link-re nil t)))
20773 (call-interactively #'org-open-at-point))
20774 ;; Insert newline in heading, but preserve tags.
20775 ((and (not (bolp))
20776 (save-excursion (beginning-of-line)
20777 (let ((case-fold-search nil))
20778 (looking-at org-complex-heading-regexp))))
20779 ;; At headline. Split line. However, if point is on keyword,
20780 ;; priority cookie or tags, do not break any of them: add
20781 ;; a newline after the headline instead.
20782 (let ((tags-column (and (match-beginning 5)
20783 (save-excursion (goto-char (match-beginning 5))
20784 (current-column))))
20785 (string
20786 (when (and (match-end 4) (org-point-in-group (point) 4))
20787 (delete-and-extract-region (point) (match-end 4)))))
20788 ;; Adjust tag alignment.
20789 (cond
20790 ((not (and tags-column string)))
20791 (org-auto-align-tags (org-set-tags nil t))
20792 (t (org--align-tags-here tags-column))) ;preserve tags column
20793 (end-of-line)
20794 (org-show-entry)
20795 (if indent (newline-and-indent) (newline))
20796 (when string (save-excursion (insert (org-trim string))))))
20797 ;; In a list, make sure indenting keeps trailing text within.
20798 ((and indent
20799 (not (eolp))
20800 (org-element-lineage context '(item)))
20801 (let ((trailing-data
20802 (delete-and-extract-region (point) (line-end-position))))
20803 (newline-and-indent)
20804 (save-excursion (insert trailing-data))))
20805 (t (if indent (newline-and-indent) (newline))))))
20807 (defun org-return-indent ()
20808 "Goto next table row or insert a newline and indent.
20809 Calls `org-table-next-row' or `newline-and-indent', depending on
20810 context. See the individual commands for more information."
20811 (interactive)
20812 (org-return t))
20814 (defun org-ctrl-c-tab (&optional _arg)
20815 "Toggle columns width in a table, or show children.
20816 Call `org-table-toggle-column-width' if point is in a table.
20817 Otherwise, call `org-show-children'."
20818 (interactive "p")
20819 (call-interactively
20820 (if (org-at-table-p) #'org-table-toggle-column-width
20821 #'org-show-children)))
20823 (defun org-ctrl-c-star ()
20824 "Compute table, or change heading status of lines.
20825 Calls `org-table-recalculate' or `org-toggle-heading',
20826 depending on context."
20827 (interactive)
20828 (cond
20829 ((org-at-table-p)
20830 (call-interactively 'org-table-recalculate))
20832 ;; Convert all lines in region to list items
20833 (call-interactively 'org-toggle-heading))))
20835 (defun org-ctrl-c-minus ()
20836 "Insert separator line in table or modify bullet status of line.
20837 Also turns a plain line or a region of lines into list items.
20838 Calls `org-table-insert-hline', `org-toggle-item', or
20839 `org-cycle-list-bullet', depending on context."
20840 (interactive)
20841 (cond
20842 ((org-at-table-p)
20843 (call-interactively 'org-table-insert-hline))
20844 ((org-region-active-p)
20845 (call-interactively 'org-toggle-item))
20846 ((org-in-item-p)
20847 (call-interactively 'org-cycle-list-bullet))
20849 (call-interactively 'org-toggle-item))))
20851 (defun org-toggle-heading (&optional nstars)
20852 "Convert headings to normal text, or items or text to headings.
20853 If there is no active region, only convert the current line.
20855 With a `\\[universal-argument]' prefix, convert the whole list at
20856 point into heading.
20858 In a region:
20860 - If the first non blank line is a headline, remove the stars
20861 from all headlines in the region.
20863 - If it is a normal line, turn each and every normal line (i.e.,
20864 not an heading or an item) in the region into headings. If you
20865 want to convert only the first line of this region, use one
20866 universal prefix argument.
20868 - If it is a plain list item, turn all plain list items into headings.
20870 When converting a line into a heading, the number of stars is chosen
20871 such that the lines become children of the current entry. However,
20872 when a numeric prefix argument is given, its value determines the
20873 number of stars to add."
20874 (interactive "P")
20875 (let ((skip-blanks
20876 (function
20877 ;; Return beginning of first non-blank line, starting from
20878 ;; line at POS.
20879 (lambda (pos)
20880 (save-excursion
20881 (goto-char pos)
20882 (while (org-at-comment-p) (forward-line))
20883 (skip-chars-forward " \r\t\n")
20884 (point-at-bol)))))
20885 beg end toggled)
20886 ;; Determine boundaries of changes. If a universal prefix has
20887 ;; been given, put the list in a region. If region ends at a bol,
20888 ;; do not consider the last line to be in the region.
20890 (when (and current-prefix-arg (org-at-item-p))
20891 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20892 (org-mark-element))
20894 (if (org-region-active-p)
20895 (setq beg (funcall skip-blanks (region-beginning))
20896 end (copy-marker (save-excursion
20897 (goto-char (region-end))
20898 (if (bolp) (point) (point-at-eol)))))
20899 (setq beg (funcall skip-blanks (point-at-bol))
20900 end (copy-marker (point-at-eol))))
20901 ;; Ensure inline tasks don't count as headings.
20902 (org-with-limited-levels
20903 (save-excursion
20904 (goto-char beg)
20905 (cond
20906 ;; Case 1. Started at an heading: de-star headings.
20907 ((org-at-heading-p)
20908 (while (< (point) end)
20909 (when (org-at-heading-p t)
20910 (looking-at org-outline-regexp) (replace-match "")
20911 (setq toggled t))
20912 (forward-line)))
20913 ;; Case 2. Started at an item: change items into headlines.
20914 ;; One star will be added by `org-list-to-subtree'.
20915 ((org-at-item-p)
20916 (while (< (point) end)
20917 (when (org-at-item-p)
20918 ;; Pay attention to cases when region ends before list.
20919 (let* ((struct (org-list-struct))
20920 (list-end
20921 (min (org-list-get-bottom-point struct) (1+ end))))
20922 (save-restriction
20923 (narrow-to-region (point) list-end)
20924 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20925 (setq toggled t))
20926 (forward-line)))
20927 ;; Case 3. Started at normal text: make every line an heading,
20928 ;; skipping headlines and items.
20929 (t (let* ((stars
20930 (make-string
20931 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20932 (add-stars
20933 (cond (nstars "") ; stars from prefix only
20934 ((equal stars "") "*") ; before first heading
20935 (org-odd-levels-only "**") ; inside heading, odd
20936 (t "*"))) ; inside heading, oddeven
20937 (rpl (concat stars add-stars " "))
20938 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20939 (while (< (point) (if (equal nstars '(4)) lend end))
20940 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20941 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20942 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20943 (forward-line)))))))
20944 (unless toggled (message "Cannot toggle heading from here"))))
20946 (defun org-meta-return (&optional arg)
20947 "Insert a new heading or wrap a region in a table.
20948 Calls `org-insert-heading', `org-insert-item' or
20949 `org-table-wrap-region', depending on context. When called with
20950 an argument, unconditionally call `org-insert-heading'."
20951 (interactive "P")
20952 (org-check-before-invisible-edit 'insert)
20953 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20954 (call-interactively (cond (arg #'org-insert-heading)
20955 ((org-at-table-p) #'org-table-wrap-region)
20956 ((org-in-item-p) #'org-insert-item)
20957 (t #'org-insert-heading)))))
20959 ;;; Menu entries
20961 (defsubst org-in-subtree-not-table-p ()
20962 "Are we in a subtree and not in a table?"
20963 (and (not (org-before-first-heading-p))
20964 (not (org-at-table-p))))
20966 ;; Define the Org mode menus
20967 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20968 '("Tbl"
20969 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20970 ["Next Field" org-cycle (org-at-table-p)]
20971 ["Previous Field" org-shifttab (org-at-table-p)]
20972 ["Next Row" org-return (org-at-table-p)]
20973 "--"
20974 ["Blank Field" org-table-blank-field (org-at-table-p)]
20975 ["Edit Field" org-table-edit-field (org-at-table-p)]
20976 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20977 "--"
20978 ("Column"
20979 ["Move Column Left" org-metaleft (org-at-table-p)]
20980 ["Move Column Right" org-metaright (org-at-table-p)]
20981 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20982 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20983 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20984 ("Row"
20985 ["Move Row Up" org-metaup (org-at-table-p)]
20986 ["Move Row Down" org-metadown (org-at-table-p)]
20987 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20988 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20989 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20990 "--"
20991 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20992 ("Rectangle"
20993 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20994 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20995 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20996 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20997 "--"
20998 ("Calculate"
20999 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21000 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21001 ["Edit Formulas" org-edit-special (org-at-table-p)]
21002 "--"
21003 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21004 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21005 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21006 "--"
21007 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21008 "--"
21009 ["Sum Column/Rectangle" org-table-sum
21010 (or (org-at-table-p) (org-region-active-p))]
21011 ["Which Column?" org-table-current-column (org-at-table-p)])
21012 ["Debug Formulas"
21013 org-table-toggle-formula-debugger
21014 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21015 ["Show Col/Row Numbers"
21016 org-table-toggle-coordinate-overlays
21017 :style toggle
21018 :selected (bound-and-true-p org-table-overlay-coordinates)]
21019 "--"
21020 ["Create" org-table-create (not (org-at-table-p))]
21021 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21022 ["Import from File" org-table-import (not (org-at-table-p))]
21023 ["Export to File" org-table-export (org-at-table-p)]
21024 "--"
21025 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21026 "--"
21027 ("Plot"
21028 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21029 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21031 (easy-menu-define org-org-menu org-mode-map "Org menu"
21032 '("Org"
21033 ("Show/Hide"
21034 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21035 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21036 ["Sparse Tree..." org-sparse-tree t]
21037 ["Reveal Context" org-reveal t]
21038 ["Show All" outline-show-all t]
21039 "--"
21040 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21041 "--"
21042 ["New Heading" org-insert-heading t]
21043 ("Navigate Headings"
21044 ["Up" outline-up-heading t]
21045 ["Next" outline-next-visible-heading t]
21046 ["Previous" outline-previous-visible-heading t]
21047 ["Next Same Level" outline-forward-same-level t]
21048 ["Previous Same Level" outline-backward-same-level t]
21049 "--"
21050 ["Jump" org-goto t])
21051 ("Edit Structure"
21052 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21053 "--"
21054 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21055 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21056 "--"
21057 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21058 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21059 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21060 "--"
21061 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21062 "--"
21063 ["Copy visible text" org-copy-visible t]
21064 "--"
21065 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21066 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21067 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21068 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21069 "--"
21070 ["Sort Region/Children" org-sort t]
21071 "--"
21072 ["Convert to odd levels" org-convert-to-odd-levels t]
21073 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21074 ("Editing"
21075 ["Emphasis..." org-emphasize t]
21076 ["Edit Source Example" org-edit-special t]
21077 "--"
21078 ["Footnote new/jump" org-footnote-action t]
21079 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21080 ("Archive"
21081 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21082 "--"
21083 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21084 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21085 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21087 "--"
21088 ("Hyperlinks"
21089 ["Store Link (Global)" org-store-link t]
21090 ["Find existing link to here" org-occur-link-in-agenda-files t]
21091 ["Insert Link" org-insert-link t]
21092 ["Follow Link" org-open-at-point t]
21093 "--"
21094 ["Next link" org-next-link t]
21095 ["Previous link" org-previous-link t]
21096 "--"
21097 ["Descriptive Links"
21098 org-toggle-link-display
21099 :style radio
21100 :selected org-descriptive-links
21102 ["Literal Links"
21103 org-toggle-link-display
21104 :style radio
21105 :selected (not org-descriptive-links)])
21106 "--"
21107 ("TODO Lists"
21108 ["TODO/DONE/-" org-todo t]
21109 ("Select keyword"
21110 ["Next keyword" org-shiftright (org-at-heading-p)]
21111 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21112 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21113 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21114 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21115 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21116 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21117 "--"
21118 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21119 :selected org-enforce-todo-dependencies :style toggle :active t]
21120 "Settings for tree at point"
21121 ["Do Children sequentially" org-toggle-ordered-property :style radio
21122 :selected (org-entry-get nil "ORDERED")
21123 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21124 ["Do Children parallel" org-toggle-ordered-property :style radio
21125 :selected (not (org-entry-get nil "ORDERED"))
21126 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21127 "--"
21128 ["Set Priority" org-priority t]
21129 ["Priority Up" org-shiftup t]
21130 ["Priority Down" org-shiftdown t]
21131 "--"
21132 ["Get news from all feeds" org-feed-update-all t]
21133 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21134 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21135 ("TAGS and Properties"
21136 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21137 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21138 "--"
21139 ["Set property" org-set-property (not (org-before-first-heading-p))]
21140 ["Column view of properties" org-columns t]
21141 ["Insert Column View DBlock" org-columns-insert-dblock t])
21142 ("Dates and Scheduling"
21143 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21144 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21145 ("Change Date"
21146 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21147 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21148 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21149 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21150 ["Compute Time Range" org-evaluate-time-range t]
21151 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21152 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21153 "--"
21154 ["Custom time format" org-toggle-time-stamp-overlays
21155 :style radio :selected org-display-custom-times]
21156 "--"
21157 ["Goto Calendar" org-goto-calendar t]
21158 ["Date from Calendar" org-date-from-calendar t]
21159 "--"
21160 ["Start/Restart Timer" org-timer-start t]
21161 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21162 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21163 ["Insert Timer String" org-timer t]
21164 ["Insert Timer Item" org-timer-item t])
21165 ("Logging work"
21166 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21167 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21168 ["Clock out" org-clock-out t]
21169 ["Clock cancel" org-clock-cancel t]
21170 "--"
21171 ["Mark as default task" org-clock-mark-default-task t]
21172 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21173 ["Goto running clock" org-clock-goto t]
21174 "--"
21175 ["Display times" org-clock-display t]
21176 ["Create clock table" org-clock-report t]
21177 "--"
21178 ["Record DONE time"
21179 (progn (setq org-log-done (not org-log-done))
21180 (message "Switching to %s will %s record a timestamp"
21181 (car org-done-keywords)
21182 (if org-log-done "automatically" "not")))
21183 :style toggle :selected org-log-done])
21184 "--"
21185 ["Agenda Command..." org-agenda t]
21186 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21187 ("File List for Agenda")
21188 ("Special views current file"
21189 ["TODO Tree" org-show-todo-tree t]
21190 ["Check Deadlines" org-check-deadlines t]
21191 ["Tags/Property tree" org-match-sparse-tree t])
21192 "--"
21193 ["Export/Publish..." org-export-dispatch t]
21194 ("LaTeX"
21195 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21196 :style toggle :selected org-cdlatex-mode]
21197 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21198 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21199 ["Modify math symbol" org-cdlatex-math-modify
21200 (org-inside-LaTeX-fragment-p)]
21201 ["Insert citation" org-reftex-citation t])
21202 "--"
21203 ("MobileOrg"
21204 ["Push Files and Views" org-mobile-push t]
21205 ["Get Captured and Flagged" org-mobile-pull t]
21206 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21207 "--"
21208 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21209 "--"
21210 ("Documentation"
21211 ["Show Version" org-version t]
21212 ["Info Documentation" org-info t])
21213 ("Customize"
21214 ["Browse Org Group" org-customize t]
21215 "--"
21216 ["Expand This Menu" org-create-customize-menu
21217 (fboundp 'customize-menu-create)])
21218 ["Send bug report" org-submit-bug-report t]
21219 "--"
21220 ("Refresh/Reload"
21221 ["Refresh setup current buffer" org-mode-restart t]
21222 ["Reload Org (after update)" org-reload t]
21223 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21226 (defun org-info (&optional node)
21227 "Read documentation for Org in the info system.
21228 With optional NODE, go directly to that node."
21229 (interactive)
21230 (info (format "(org)%s" (or node ""))))
21232 ;;;###autoload
21233 (defun org-submit-bug-report ()
21234 "Submit a bug report on Org via mail.
21236 Don't hesitate to report any problems or inaccurate documentation.
21238 If you don't have setup sending mail from (X)Emacs, please copy the
21239 output buffer into your mail program, as it gives us important
21240 information about your Org version and configuration."
21241 (interactive)
21242 (require 'reporter)
21243 (defvar reporter-prompt-for-summary-p)
21244 (org-load-modules-maybe)
21245 (org-require-autoloaded-modules)
21246 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21247 (reporter-submit-bug-report
21248 "emacs-orgmode@gnu.org"
21249 (org-version nil 'full)
21250 (let (list)
21251 (save-window-excursion
21252 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21253 (delete-other-windows)
21254 (erase-buffer)
21255 (insert "You are about to submit a bug report to the Org mailing list.
21257 We would like to add your full Org and Outline configuration to the
21258 bug report. This greatly simplifies the work of the maintainer and
21259 other experts on the mailing list.
21261 HOWEVER, some variables you have customized may contain private
21262 information. The names of customers, colleagues, or friends, might
21263 appear in the form of file names, tags, todo states, or search strings.
21264 If you answer yes to the prompt, you might want to check and remove
21265 such private information before sending the email.")
21266 (add-text-properties (point-min) (point-max) '(face org-warning))
21267 (when (yes-or-no-p "Include your Org configuration ")
21268 (mapatoms
21269 (lambda (v)
21270 (and (boundp v)
21271 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21272 (or (and (symbol-value v)
21273 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21274 (and
21275 (get v 'custom-type) (get v 'standard-value)
21276 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21277 (push v list)))))
21278 (kill-buffer (get-buffer "*Warn about privacy*"))
21279 list))
21280 nil nil
21281 "Remember to cover the basics, that is, what you expected to happen and
21282 what in fact did happen. You don't know how to make a good report? See
21284 http://orgmode.org/manual/Feedback.html#Feedback
21286 Your bug report will be posted to the Org mailing list.
21287 ------------------------------------------------------------------------")
21288 (save-excursion
21289 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21290 (replace-match "\\1Bug: \\3 [\\2]")))))
21293 (defun org-install-agenda-files-menu ()
21294 (let ((bl (buffer-list)))
21295 (save-excursion
21296 (while bl
21297 (set-buffer (pop bl))
21298 (when (derived-mode-p 'org-mode) (setq bl nil)))
21299 (when (derived-mode-p 'org-mode)
21300 (easy-menu-change
21301 '("Org") "File List for Agenda"
21302 (append
21303 (list
21304 ["Edit File List" (org-edit-agenda-file-list) t]
21305 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21306 ["Remove Current File from List" org-remove-file t]
21307 ["Cycle through agenda files" org-cycle-agenda-files t]
21308 ["Occur in all agenda files" org-occur-in-agenda-files t]
21309 "--")
21310 (mapcar 'org-file-menu-entry
21311 ;; Prevent initialization from failing.
21312 (ignore-errors (org-agenda-files t)))))))))
21314 ;;;; Documentation
21316 (defun org-require-autoloaded-modules ()
21317 (interactive)
21318 (mapc #'require
21319 '(org-agenda org-archive org-attach org-clock org-colview org-id
21320 org-table org-timer)))
21322 ;;;###autoload
21323 (defun org-reload (&optional uncompiled)
21324 "Reload all org lisp files.
21325 With prefix arg UNCOMPILED, load the uncompiled versions."
21326 (interactive "P")
21327 (require 'loadhist)
21328 (let* ((org-dir (org-find-library-dir "org"))
21329 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21330 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21331 (remove-re (format "\\`%s\\'"
21332 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21333 (feats (delete-dups
21334 (mapcar 'file-name-sans-extension
21335 (mapcar 'file-name-nondirectory
21336 (delq nil
21337 (mapcar 'feature-file
21338 features))))))
21339 (lfeat (append
21340 (sort
21341 (setq feats
21342 (delq nil (mapcar
21343 (lambda (f)
21344 (if (and (string-match feature-re f)
21345 (not (string-match remove-re f)))
21346 f nil))
21347 feats)))
21348 'string-lessp)
21349 (list "org-version" "org")))
21350 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21351 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21352 load-uncore load-misses)
21353 (setq load-misses
21354 (delq 't
21355 (mapcar (lambda (f)
21356 (or (org-load-noerror-mustsuffix (concat org-dir f))
21357 (and (string= org-dir contrib-dir)
21358 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21359 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21360 (add-to-list 'load-uncore f 'append)
21363 lfeat)))
21364 (when load-uncore
21365 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21366 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21367 (if load-misses
21368 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21369 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21370 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21372 ;;;###autoload
21373 (defun org-customize ()
21374 "Call the customize function with org as argument."
21375 (interactive)
21376 (org-load-modules-maybe)
21377 (org-require-autoloaded-modules)
21378 (customize-browse 'org))
21380 (defun org-create-customize-menu ()
21381 "Create a full customization menu for Org mode, insert it into the menu."
21382 (interactive)
21383 (org-load-modules-maybe)
21384 (org-require-autoloaded-modules)
21385 (if (fboundp 'customize-menu-create)
21386 (progn
21387 (easy-menu-change
21388 '("Org") "Customize"
21389 `(["Browse Org group" org-customize t]
21390 "--"
21391 ,(customize-menu-create 'org)
21392 ["Set" Custom-set t]
21393 ["Save" Custom-save t]
21394 ["Reset to Current" Custom-reset-current t]
21395 ["Reset to Saved" Custom-reset-saved t]
21396 ["Reset to Standard Settings" Custom-reset-standard t]))
21397 (message "\"Org\"-menu now contains full customization menu"))
21398 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21400 ;;;; Miscellaneous stuff
21402 ;;; Generally useful functions
21404 (defun org-link-display-format (s)
21405 "Replace links in string S with their description.
21406 If there is no description, use the link target."
21407 (save-match-data
21408 (replace-regexp-in-string
21409 org-bracket-link-analytic-regexp
21410 (lambda (m)
21411 (if (match-end 5) (match-string 5 m)
21412 (concat (match-string 1 m) (match-string 3 m))))
21413 s nil t)))
21415 (defun org-toggle-link-display ()
21416 "Toggle the literal or descriptive display of links."
21417 (interactive)
21418 (if org-descriptive-links
21419 (progn (org-remove-from-invisibility-spec '(org-link))
21420 (org-restart-font-lock)
21421 (setq org-descriptive-links nil))
21422 (progn (add-to-invisibility-spec '(org-link))
21423 (org-restart-font-lock)
21424 (setq org-descriptive-links t))))
21426 (defun org-in-clocktable-p ()
21427 "Check if the cursor is in a clocktable."
21428 (let ((pos (point)) start)
21429 (save-excursion
21430 (end-of-line 1)
21431 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21432 (setq start (match-beginning 0))
21433 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21434 (>= (match-end 0) pos)
21435 start))))
21437 (defun org-in-verbatim-emphasis ()
21438 (save-match-data
21439 (and (org-in-regexp org-verbatim-re 2)
21440 (>= (point) (match-beginning 3))
21441 (<= (point) (match-end 4)))))
21443 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21444 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21445 (if (and marker (marker-buffer marker)
21446 (buffer-live-p (marker-buffer marker)))
21447 (progn
21448 (pop-to-buffer-same-window (marker-buffer marker))
21449 (when (or (> marker (point-max)) (< marker (point-min)))
21450 (widen))
21451 (goto-char marker)
21452 (org-show-context 'org-goto))
21453 (if bookmark
21454 (bookmark-jump bookmark)
21455 (error "Cannot find location"))))
21457 (defun org-quote-csv-field (s)
21458 "Quote field for inclusion in CSV material."
21459 (if (string-match "[\",]" s)
21460 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21463 (defun org-force-self-insert (N)
21464 "Needed to enforce self-insert under remapping."
21465 (interactive "p")
21466 (self-insert-command N))
21468 (defun org-get-indentation (&optional line)
21469 "Get the indentation of the current line, interpreting tabs.
21470 When LINE is given, assume it represents a line and compute its indentation."
21471 (if line
21472 (when (string-match "^ *" (org-remove-tabs line))
21473 (match-end 0))
21474 (save-excursion
21475 (beginning-of-line 1)
21476 (skip-chars-forward " \t")
21477 (current-column))))
21479 (defun org-get-string-indentation (s)
21480 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21481 (let ((n -1) (i 0) (w tab-width) c)
21482 (catch 'exit
21483 (while (< (setq n (1+ n)) (length s))
21484 (setq c (aref s n))
21485 (cond ((= c ?\ ) (setq i (1+ i)))
21486 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21487 (t (throw 'exit t)))))
21490 (defun org-fix-indentation (line ind)
21491 "Fix indentation in LINE.
21492 IND is a cons cell with target and minimum indentation.
21493 If the current indentation in LINE is smaller than the minimum,
21494 leave it alone. If it is larger than ind, set it to the target."
21495 (let* ((l (org-remove-tabs line))
21496 (i (org-get-indentation l))
21497 (i1 (car ind)) (i2 (cdr ind)))
21498 (when (>= i i2) (setq l (substring line i2)))
21499 (if (> i1 0)
21500 (concat (make-string i1 ?\ ) l)
21501 l)))
21503 (defun org-fill-template (template alist)
21504 "Find each %key of ALIST in TEMPLATE and replace it."
21505 (let ((case-fold-search nil))
21506 (dolist (entry (sort (copy-sequence alist)
21507 (lambda (a b) (< (length (car a)) (length (car b))))))
21508 (setq template
21509 (replace-regexp-in-string
21510 (concat "%" (regexp-quote (car entry)))
21511 (or (cdr entry) "") template t t)))
21512 template))
21514 (defun org-quote-vert (s)
21515 "Replace \"|\" with \"\\vert\"."
21516 (while (string-match "|" s)
21517 (setq s (replace-match "\\vert" t t s)))
21520 (defun org-uuidgen-p (s)
21521 "Is S an ID created by UUIDGEN?"
21522 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21524 (defun org-in-src-block-p (&optional inside)
21525 "Whether point is in a code source block.
21526 When INSIDE is non-nil, don't consider we are within a src block
21527 when point is at #+BEGIN_SRC or #+END_SRC."
21528 (let ((case-fold-search t))
21529 (or (and (eq (get-char-property (point) 'src-block) t))
21530 (and (not inside)
21531 (save-match-data
21532 (save-excursion
21533 (beginning-of-line)
21534 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21536 (defun org-context ()
21537 "Return a list of contexts of the current cursor position.
21538 If several contexts apply, all are returned.
21539 Each context entry is a list with a symbol naming the context, and
21540 two positions indicating start and end of the context. Possible
21541 contexts are:
21543 :headline anywhere in a headline
21544 :headline-stars on the leading stars in a headline
21545 :todo-keyword on a TODO keyword (including DONE) in a headline
21546 :tags on the TAGS in a headline
21547 :priority on the priority cookie in a headline
21548 :item on the first line of a plain list item
21549 :item-bullet on the bullet/number of a plain list item
21550 :checkbox on the checkbox in a plain list item
21551 :table in an Org table
21552 :table-special on a special filed in a table
21553 :table-table in a table.el table
21554 :clocktable in a clocktable
21555 :src-block in a source block
21556 :link on a hyperlink
21557 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21558 :target on a <<target>>
21559 :radio-target on a <<<radio-target>>>
21560 :latex-fragment on a LaTeX fragment
21561 :latex-preview on a LaTeX fragment with overlaid preview image
21563 This function expects the position to be visible because it uses font-lock
21564 faces as a help to recognize the following contexts: :table-special, :link,
21565 and :keyword."
21566 (let* ((f (get-text-property (point) 'face))
21567 (faces (if (listp f) f (list f)))
21568 (case-fold-search t)
21569 (p (point)) clist o)
21570 ;; First the large context
21571 (cond
21572 ((org-at-heading-p t)
21573 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21574 (when (progn
21575 (beginning-of-line 1)
21576 (looking-at org-todo-line-tags-regexp))
21577 (push (org-point-in-group p 1 :headline-stars) clist)
21578 (push (org-point-in-group p 2 :todo-keyword) clist)
21579 (push (org-point-in-group p 4 :tags) clist))
21580 (goto-char p)
21581 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21582 (when (looking-at "\\[#[A-Z0-9]\\]")
21583 (push (org-point-in-group p 0 :priority) clist)))
21585 ((org-at-item-p)
21586 (push (org-point-in-group p 2 :item-bullet) clist)
21587 (push (list :item (point-at-bol)
21588 (save-excursion (org-end-of-item) (point)))
21589 clist)
21590 (and (org-at-item-checkbox-p)
21591 (push (org-point-in-group p 0 :checkbox) clist)))
21593 ((org-at-table-p)
21594 (push (list :table (org-table-begin) (org-table-end)) clist)
21595 (when (memq 'org-formula faces)
21596 (push (list :table-special
21597 (previous-single-property-change p 'face)
21598 (next-single-property-change p 'face)) clist)))
21599 ((org-at-table-p 'any)
21600 (push (list :table-table) clist)))
21601 (goto-char p)
21603 (let ((case-fold-search t))
21604 ;; New the "medium" contexts: clocktables, source blocks
21605 (cond ((org-in-clocktable-p)
21606 (push (list :clocktable
21607 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21608 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21609 (match-beginning 1))
21610 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21611 (match-end 0))) clist))
21612 ((org-in-src-block-p)
21613 (push (list :src-block
21614 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21615 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21616 (match-beginning 1))
21617 (and (search-forward "#+END_SRC" nil t)
21618 (match-beginning 0))) clist))))
21619 (goto-char p)
21621 ;; Now the small context
21622 (cond
21623 ((org-at-timestamp-p)
21624 (push (org-point-in-group p 0 :timestamp) clist))
21625 ((memq 'org-link faces)
21626 (push (list :link
21627 (previous-single-property-change p 'face)
21628 (next-single-property-change p 'face)) clist))
21629 ((memq 'org-special-keyword faces)
21630 (push (list :keyword
21631 (previous-single-property-change p 'face)
21632 (next-single-property-change p 'face)) clist))
21633 ((org-at-target-p)
21634 (push (org-point-in-group p 0 :target) clist)
21635 (goto-char (1- (match-beginning 0)))
21636 (when (looking-at org-radio-target-regexp)
21637 (push (org-point-in-group p 0 :radio-target) clist))
21638 (goto-char p))
21639 ((setq o (cl-some
21640 (lambda (o)
21641 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21643 (overlays-at (point))))
21644 (push (list :latex-fragment
21645 (overlay-start o) (overlay-end o)) clist)
21646 (push (list :latex-preview
21647 (overlay-start o) (overlay-end o)) clist))
21648 ((org-inside-LaTeX-fragment-p)
21649 ;; FIXME: positions wrong.
21650 (push (list :latex-fragment (point) (point)) clist)))
21652 (setq clist (nreverse (delq nil clist)))
21653 clist))
21655 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21656 "Non-nil when point is between matches of START-RE and END-RE.
21658 Also return a non-nil value when point is on one of the matches.
21660 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21661 buffer positions. Default values are the positions of headlines
21662 surrounding the point.
21664 The functions returns a cons cell whose car (resp. cdr) is the
21665 position before START-RE (resp. after END-RE)."
21666 (save-match-data
21667 (let ((pos (point))
21668 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21669 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21670 beg end)
21671 (save-excursion
21672 ;; Point is on a block when on START-RE or if START-RE can be
21673 ;; found before it...
21674 (and (or (org-in-regexp start-re)
21675 (re-search-backward start-re limit-up t))
21676 (setq beg (match-beginning 0))
21677 ;; ... and END-RE after it...
21678 (goto-char (match-end 0))
21679 (re-search-forward end-re limit-down t)
21680 (> (setq end (match-end 0)) pos)
21681 ;; ... without another START-RE in-between.
21682 (goto-char (match-beginning 0))
21683 (not (re-search-backward start-re (1+ beg) t))
21684 ;; Return value.
21685 (cons beg end))))))
21687 (defun org-in-block-p (names)
21688 "Non-nil when point belongs to a block whose name belongs to NAMES.
21690 NAMES is a list of strings containing names of blocks.
21692 Return first block name matched, or nil. Beware that in case of
21693 nested blocks, the returned name may not belong to the closest
21694 block from point."
21695 (save-match-data
21696 (catch 'exit
21697 (let ((case-fold-search t)
21698 (lim-up (save-excursion (outline-previous-heading)))
21699 (lim-down (save-excursion (outline-next-heading))))
21700 (dolist (name names)
21701 (let ((n (regexp-quote name)))
21702 (when (org-between-regexps-p
21703 (concat "^[ \t]*#\\+begin_" n)
21704 (concat "^[ \t]*#\\+end_" n)
21705 lim-up lim-down)
21706 (throw 'exit n)))))
21707 nil)))
21709 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21710 "Call `multi-occur' with buffers for all agenda files."
21711 (interactive "sOrg-files matching: ")
21712 (let* ((files (org-agenda-files))
21713 (tnames (mapcar #'file-truename files))
21714 (extra org-agenda-text-search-extra-files))
21715 (when (eq (car extra) 'agenda-archives)
21716 (setq extra (cdr extra))
21717 (setq files (org-add-archive-files files)))
21718 (dolist (f extra)
21719 (unless (member (file-truename f) tnames)
21720 (unless (member f files) (setq files (append files (list f))))
21721 (setq tnames (append tnames (list (file-truename f))))))
21722 (multi-occur
21723 (mapcar (lambda (x)
21724 (with-current-buffer
21725 ;; FIXME: Why not just (find-file-noselect x)?
21726 ;; Is it to avoid the "revert buffer" prompt?
21727 (or (get-file-buffer x) (find-file-noselect x))
21728 (widen)
21729 (current-buffer)))
21730 files)
21731 regexp)))
21733 (add-hook 'occur-mode-find-occurrence-hook
21734 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21736 (defun org-occur-link-in-agenda-files ()
21737 "Create a link and search for it in the agendas.
21738 The link is not stored in `org-stored-links', it is just created
21739 for the search purpose."
21740 (interactive)
21741 (let ((link (condition-case nil
21742 (org-store-link nil)
21743 (error "Unable to create a link to here"))))
21744 (org-occur-in-agenda-files (regexp-quote link))))
21746 (defun org-back-over-empty-lines ()
21747 "Move backwards over whitespace, to the beginning of the first empty line.
21748 Returns the number of empty lines passed."
21749 (let ((pos (point)))
21750 (if (cdr (assq 'heading org-blank-before-new-entry))
21751 (skip-chars-backward " \t\n\r")
21752 (unless (eobp)
21753 (forward-line -1)))
21754 (beginning-of-line 2)
21755 (goto-char (min (point) pos))
21756 (count-lines (point) pos)))
21758 (defun org-switch-to-buffer-other-window (&rest args)
21759 "Switch to buffer in a second window on the current frame.
21760 In particular, do not allow pop-up frames.
21761 Returns the newly created buffer."
21762 (org-no-popups
21763 (apply 'switch-to-buffer-other-window args)))
21765 (defun org-replace-escapes (string table)
21766 "Replace %-escapes in STRING with values in TABLE.
21767 TABLE is an association list with keys like \"%a\" and string values.
21768 The sequences in STRING may contain normal field width and padding information,
21769 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21770 so values can contain further %-escapes if they are define later in TABLE."
21771 (let ((tbl (copy-alist table))
21772 (case-fold-search nil)
21773 (pchg 0)
21774 re rpl)
21775 (dolist (e tbl)
21776 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21777 (when (and (cdr e) (string-match re (cdr e)))
21778 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21779 (safe "SREF"))
21780 (add-text-properties 0 3 (list 'sref sref) safe)
21781 (setcdr e (replace-match safe t t (cdr e)))))
21782 (while (string-match re string)
21783 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21784 (cdr e)))
21785 (setq string (replace-match rpl t t string))))
21786 (while (setq pchg (next-property-change pchg string))
21787 (let ((sref (get-text-property pchg 'sref string)))
21788 (when (and sref (string-match "SREF" string pchg))
21789 (setq string (replace-match sref t t string)))))
21790 string))
21792 ;;; TODO: Only called once, from ox-odt which should probably use
21793 ;;; org-export-inline-image-p or something.
21794 (defun org-file-image-p (file)
21795 "Return non-nil if FILE is an image."
21796 (save-match-data
21797 (string-match (image-file-name-regexp) file)))
21799 (defun org-get-cursor-date (&optional with-time)
21800 "Return the date at cursor in as a time.
21801 This works in the calendar and in the agenda, anywhere else it just
21802 returns the current time.
21803 If WITH-TIME is non-nil, returns the time of the event at point (in
21804 the agenda) or the current time of the day."
21805 (let (date day defd tp hod mod)
21806 (when with-time
21807 (setq tp (get-text-property (point) 'time))
21808 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21809 (setq hod (string-to-number (match-string 1 tp))
21810 mod (string-to-number (match-string 2 tp))))
21811 (or tp (let ((now (decode-time)))
21812 (setq hod (nth 2 now)
21813 mod (nth 1 now)))))
21814 (cond
21815 ((eq major-mode 'calendar-mode)
21816 (setq date (calendar-cursor-to-date)
21817 defd (encode-time 0 (or mod 0) (or hod 0)
21818 (nth 1 date) (nth 0 date) (nth 2 date))))
21819 ((eq major-mode 'org-agenda-mode)
21820 (setq day (get-text-property (point) 'day))
21821 (when day
21822 (setq date (calendar-gregorian-from-absolute day)
21823 defd (encode-time 0 (or mod 0) (or hod 0)
21824 (nth 1 date) (nth 0 date) (nth 2 date))))))
21825 (or defd (current-time))))
21827 (defun org-mark-subtree (&optional up)
21828 "Mark the current subtree.
21829 This puts point at the start of the current subtree, and mark at
21830 the end. If a numeric prefix UP is given, move up into the
21831 hierarchy of headlines by UP levels before marking the subtree."
21832 (interactive "P")
21833 (org-with-limited-levels
21834 (cond ((org-at-heading-p) (beginning-of-line))
21835 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21836 (t (outline-previous-visible-heading 1))))
21837 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21838 (if (called-interactively-p 'any)
21839 (call-interactively 'org-mark-element)
21840 (org-mark-element)))
21842 (defun org-file-newer-than-p (file time)
21843 "Non-nil if FILE is newer than TIME.
21844 FILE is a filename, as a string, TIME is a list of integers, as
21845 returned by, e.g., `current-time'."
21846 (and (file-exists-p file)
21847 ;; Only compare times up to whole seconds as some file-systems
21848 ;; (e.g. HFS+) do not retain any finer granularity. As
21849 ;; a consequence, make sure we return non-nil when the two
21850 ;; times are equal.
21851 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21852 (cl-subseq time 0 2)))))
21854 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21855 "Compile a SOURCE file using PROCESS.
21857 PROCESS is either a function or a list of shell commands, as
21858 strings. EXT is a file extension, without the leading dot, as
21859 a string. It is used to check if the process actually succeeded.
21861 PROCESS must create a file with the same base name and directory
21862 as SOURCE, but ending with EXT. The function then returns its
21863 filename. Otherwise, it raises an error. The error message can
21864 then be refined by providing string ERR-MSG, which is appended to
21865 the standard message.
21867 If PROCESS is a function, it is called with a single argument:
21868 the SOURCE file.
21870 If it is a list of commands, each of them is called using
21871 `shell-command'. By default, in each command, %b, %f, %F, %o and
21872 %O are replaced with, respectively, SOURCE base name, name, full
21873 name, directory and absolute output file name. It is possible,
21874 however, to use more place-holders by specifying them in optional
21875 argument SPEC, as an alist following the pattern
21877 (CHARACTER . REPLACEMENT-STRING).
21879 When PROCESS is a list of commands, optional argument LOG-BUF can
21880 be set to a buffer or a buffer name. `shell-command' then uses
21881 it for output."
21882 (let* ((base-name (file-name-base source))
21883 (full-name (file-truename source))
21884 (out-dir (or (file-name-directory source) "./"))
21885 (output (expand-file-name (concat base-name "." ext) out-dir))
21886 (time (current-time))
21887 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21888 (save-window-excursion
21889 (pcase process
21890 ((pred functionp) (funcall process (shell-quote-argument source)))
21891 ((pred consp)
21892 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21893 (spec (append spec
21894 `((?b . ,(shell-quote-argument base-name))
21895 (?f . ,(shell-quote-argument source))
21896 (?F . ,(shell-quote-argument full-name))
21897 (?o . ,(shell-quote-argument out-dir))
21898 (?O . ,(shell-quote-argument output))))))
21899 (dolist (command process)
21900 (shell-command (format-spec command spec) log-buf))
21901 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21902 (_ (error "No valid command to process %S%s" source err-msg))))
21903 ;; Check for process failure. Output file is expected to be
21904 ;; located in the same directory as SOURCE.
21905 (unless (org-file-newer-than-p output time)
21906 (error (format "File %S wasn't produced%s" output err-msg)))
21907 output))
21909 ;;; Indentation
21911 (defvar org-element-greater-elements)
21912 (defun org--get-expected-indentation (element contentsp)
21913 "Expected indentation column for current line, according to ELEMENT.
21914 ELEMENT is an element containing point. CONTENTSP is non-nil
21915 when indentation is to be computed according to contents of
21916 ELEMENT."
21917 (let ((type (org-element-type element))
21918 (start (org-element-property :begin element))
21919 (post-affiliated (org-element-property :post-affiliated element)))
21920 (org-with-wide-buffer
21921 (cond
21922 (contentsp
21923 (cl-case type
21924 ((diary-sexp footnote-definition) 0)
21925 ((headline inlinetask nil)
21926 (if (not org-adapt-indentation) 0
21927 (let ((level (org-current-level)))
21928 (if level (1+ level) 0))))
21929 ((item plain-list) (org-list-item-body-column post-affiliated))
21931 (goto-char start)
21932 (org-get-indentation))))
21933 ((memq type '(headline inlinetask nil))
21934 (if (org-match-line "[ \t]*$")
21935 (org--get-expected-indentation element t)
21937 ((memq type '(diary-sexp footnote-definition)) 0)
21938 ;; First paragraph of a footnote definition or an item.
21939 ;; Indent like parent.
21940 ((< (line-beginning-position) start)
21941 (org--get-expected-indentation
21942 (org-element-property :parent element) t))
21943 ;; At first line: indent according to previous sibling, if any,
21944 ;; ignoring footnote definitions and inline tasks, or parent's
21945 ;; contents.
21946 ((= (line-beginning-position) start)
21947 (catch 'exit
21948 (while t
21949 (if (= (point-min) start) (throw 'exit 0)
21950 (goto-char (1- start))
21951 (let* ((previous (org-element-at-point))
21952 (parent previous))
21953 (while (and parent (<= (org-element-property :end parent) start))
21954 (setq previous parent
21955 parent (org-element-property :parent parent)))
21956 (cond
21957 ((not previous) (throw 'exit 0))
21958 ((> (org-element-property :end previous) start)
21959 (throw 'exit (org--get-expected-indentation previous t)))
21960 ((memq (org-element-type previous)
21961 '(footnote-definition inlinetask))
21962 (setq start (org-element-property :begin previous)))
21963 (t (goto-char (org-element-property :begin previous))
21964 (throw 'exit
21965 (if (bolp) (org-get-indentation)
21966 ;; At first paragraph in an item or
21967 ;; a footnote definition.
21968 (org--get-expected-indentation
21969 (org-element-property :parent previous) t))))))))))
21970 ;; Otherwise, move to the first non-blank line above.
21972 (beginning-of-line)
21973 (let ((pos (point)))
21974 (skip-chars-backward " \r\t\n")
21975 (cond
21976 ;; Two blank lines end a footnote definition or a plain
21977 ;; list. When we indent an empty line after them, the
21978 ;; containing list or footnote definition is over, so it
21979 ;; qualifies as a previous sibling. Therefore, we indent
21980 ;; like its first line.
21981 ((and (memq type '(footnote-definition plain-list))
21982 (> (count-lines (point) pos) 2))
21983 (goto-char start)
21984 (org-get-indentation))
21985 ;; Line above is the first one of a paragraph at the
21986 ;; beginning of an item or a footnote definition. Indent
21987 ;; like parent.
21988 ((< (line-beginning-position) start)
21989 (org--get-expected-indentation
21990 (org-element-property :parent element) t))
21991 ;; Line above is the beginning of an element, i.e., point
21992 ;; was originally on the blank lines between element's start
21993 ;; and contents.
21994 ((= (line-beginning-position) post-affiliated)
21995 (org--get-expected-indentation element t))
21996 ;; POS is after contents in a greater element. Indent like
21997 ;; the beginning of the element.
21998 ((and (memq type org-element-greater-elements)
21999 (let ((cend (org-element-property :contents-end element)))
22000 (and cend (<= cend pos))))
22001 ;; As a special case, if point is at the end of a footnote
22002 ;; definition or an item, indent like the very last element
22003 ;; within. If that last element is an item, indent like
22004 ;; its contents.
22005 (if (memq type '(footnote-definition item plain-list))
22006 (let ((last (org-element-at-point)))
22007 (goto-char pos)
22008 (org--get-expected-indentation
22009 last (eq (org-element-type last) 'item)))
22010 (goto-char start)
22011 (org-get-indentation)))
22012 ;; In any other case, indent like the current line.
22013 (t (org-get-indentation)))))))))
22015 (defun org--align-node-property ()
22016 "Align node property at point.
22017 Alignment is done according to `org-property-format', which see."
22018 (when (save-excursion
22019 (beginning-of-line)
22020 (looking-at org-property-re))
22021 (replace-match
22022 (concat (match-string 4)
22023 (org-trim
22024 (format org-property-format (match-string 1) (match-string 3))))
22025 t t)))
22027 (defun org-indent-line ()
22028 "Indent line depending on context.
22030 Indentation is done according to the following rules:
22032 - Footnote definitions, diary sexps, headlines and inline tasks
22033 have to start at column 0.
22035 - On the very first line of an element, consider, in order, the
22036 next rules until one matches:
22038 1. If there's a sibling element before, ignoring footnote
22039 definitions and inline tasks, indent like its first line.
22041 2. If element has a parent, indent like its contents. More
22042 precisely, if parent is an item, indent after the
22043 description part, if any, or the bullet (see
22044 `org-list-description-max-indent'). Else, indent like
22045 parent's first line.
22047 3. Otherwise, indent relatively to current level, if
22048 `org-adapt-indentation' is non-nil, or to left margin.
22050 - On a blank line at the end of an element, indent according to
22051 the type of the element. More precisely
22053 1. If element is a plain list, an item, or a footnote
22054 definition, indent like the very last element within.
22056 2. If element is a paragraph, indent like its last non blank
22057 line.
22059 3. Otherwise, indent like its very first line.
22061 - In the code part of a source block, use language major mode
22062 to indent current line if `org-src-tab-acts-natively' is
22063 non-nil. If it is nil, do nothing.
22065 - Otherwise, indent like the first non-blank line above.
22067 The function doesn't indent an item as it could break the whole
22068 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22069 `\\[org-shiftmetaright]'.
22071 Also align node properties according to `org-property-format'."
22072 (interactive)
22073 (cond
22074 (orgstruct-is-++
22075 (let ((indent-line-function
22076 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22077 (indent-according-to-mode)))
22078 ((org-at-heading-p) 'noindent)
22080 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22081 (type (org-element-type element)))
22082 (cond ((and (memq type '(plain-list item))
22083 (= (line-beginning-position)
22084 (org-element-property :post-affiliated element)))
22085 'noindent)
22086 ((and (eq type 'latex-environment)
22087 (>= (point) (org-element-property :post-affiliated element))
22088 (< (point) (org-with-wide-buffer
22089 (goto-char (org-element-property :end element))
22090 (skip-chars-backward " \r\t\n")
22091 (line-beginning-position 2))))
22092 'noindent)
22093 ((and (eq type 'src-block)
22094 org-src-tab-acts-natively
22095 (> (line-beginning-position)
22096 (org-element-property :post-affiliated element))
22097 (< (line-beginning-position)
22098 (org-with-wide-buffer
22099 (goto-char (org-element-property :end element))
22100 (skip-chars-backward " \r\t\n")
22101 (line-beginning-position))))
22102 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22104 (let ((column (org--get-expected-indentation element nil)))
22105 ;; Preserve current column.
22106 (if (<= (current-column) (current-indentation))
22107 (indent-line-to column)
22108 (save-excursion (indent-line-to column))))
22109 ;; Align node property. Also preserve current column.
22110 (when (eq type 'node-property)
22111 (let ((column (current-column)))
22112 (org--align-node-property)
22113 (org-move-to-column column)))))))))
22115 (defun org-indent-region (start end)
22116 "Indent each non-blank line in the region.
22117 Called from a program, START and END specify the region to
22118 indent. The function will not indent contents of example blocks,
22119 verse blocks and export blocks as leading white spaces are
22120 assumed to be significant there."
22121 (interactive "r")
22122 (save-excursion
22123 (goto-char start)
22124 (skip-chars-forward " \r\t\n")
22125 (unless (eobp) (beginning-of-line))
22126 (let ((indent-to
22127 (lambda (ind pos)
22128 ;; Set IND as indentation for all lines between point and
22129 ;; POS. Blank lines are ignored. Leave point after POS
22130 ;; once done.
22131 (let ((limit (copy-marker pos)))
22132 (while (< (point) limit)
22133 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22134 (forward-line))
22135 (set-marker limit nil))))
22136 (end (copy-marker end)))
22137 (while (< (point) end)
22138 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22139 (let* ((element (org-element-at-point))
22140 (type (org-element-type element))
22141 (element-end (copy-marker (org-element-property :end element)))
22142 (ind (org--get-expected-indentation element nil)))
22143 (cond
22144 ;; Element indented as a single block. Example blocks
22145 ;; preserving indentation are a special case since the
22146 ;; "contents" must not be indented whereas the block
22147 ;; boundaries can.
22148 ((or (memq type '(export-block latex-environment))
22149 (and (eq type 'example-block)
22150 (not
22151 (or org-src-preserve-indentation
22152 (org-element-property :preserve-indent element)))))
22153 (let ((offset (- ind (org-get-indentation))))
22154 (unless (zerop offset)
22155 (indent-rigidly (org-element-property :begin element)
22156 (org-element-property :end element)
22157 offset)))
22158 (goto-char element-end))
22159 ;; Elements indented line wise. Be sure to exclude
22160 ;; example blocks (preserving indentation) and source
22161 ;; blocks from this category as they are treated
22162 ;; specially later.
22163 ((or (memq type '(paragraph table table-row))
22164 (not (or (org-element-property :contents-begin element)
22165 (memq type '(example-block src-block)))))
22166 (when (eq type 'node-property)
22167 (org--align-node-property)
22168 (beginning-of-line))
22169 (funcall indent-to ind (min element-end end)))
22170 ;; Elements consisting of three parts: before the
22171 ;; contents, the contents, and after the contents. The
22172 ;; contents are treated specially, according to the
22173 ;; element type, or not indented at all. Other parts are
22174 ;; indented as a single block.
22176 (let* ((post (copy-marker
22177 (org-element-property :post-affiliated element)))
22178 (cbeg
22179 (copy-marker
22180 (cond
22181 ((not (org-element-property :contents-begin element))
22182 ;; Fake contents for source blocks.
22183 (org-with-wide-buffer
22184 (goto-char post)
22185 (line-beginning-position 2)))
22186 ((memq type '(footnote-definition item plain-list))
22187 ;; Contents in these elements could start on
22188 ;; the same line as the beginning of the
22189 ;; element. Make sure we start indenting
22190 ;; from the second line.
22191 (org-with-wide-buffer
22192 (goto-char post)
22193 (end-of-line)
22194 (skip-chars-forward " \r\t\n")
22195 (if (eobp) (point) (line-beginning-position))))
22196 (t (org-element-property :contents-begin element)))))
22197 (cend (copy-marker
22198 (or (org-element-property :contents-end element)
22199 ;; Fake contents for source blocks.
22200 (org-with-wide-buffer
22201 (goto-char element-end)
22202 (skip-chars-backward " \r\t\n")
22203 (line-beginning-position)))
22204 t)))
22205 ;; Do not change items indentation individually as it
22206 ;; might break the list as a whole. On the other
22207 ;; hand, when at a plain list, indent it as a whole.
22208 (cond ((eq type 'plain-list)
22209 (let ((offset (- ind (org-get-indentation))))
22210 (unless (zerop offset)
22211 (indent-rigidly (org-element-property :begin element)
22212 (org-element-property :end element)
22213 offset))
22214 (goto-char cbeg)))
22215 ((eq type 'item) (goto-char cbeg))
22216 (t (funcall indent-to ind (min cbeg end))))
22217 (when (< (point) end)
22218 (cl-case type
22219 ((example-block verse-block))
22220 (src-block
22221 ;; In a source block, indent source code
22222 ;; according to language major mode, but only if
22223 ;; `org-src-tab-acts-natively' is non-nil.
22224 (when (and (< (point) end) org-src-tab-acts-natively)
22225 (ignore-errors
22226 (org-babel-do-in-edit-buffer
22227 (indent-region (point-min) (point-max))))))
22228 (t (org-indent-region (point) (min cend end))))
22229 (goto-char (min cend end))
22230 (when (< (point) end)
22231 (funcall indent-to ind (min element-end end))))
22232 (set-marker post nil)
22233 (set-marker cbeg nil)
22234 (set-marker cend nil))))
22235 (set-marker element-end nil))))
22236 (set-marker end nil))))
22238 (defun org-indent-drawer ()
22239 "Indent the drawer at point."
22240 (interactive)
22241 (unless (save-excursion
22242 (beginning-of-line)
22243 (looking-at-p org-drawer-regexp))
22244 (user-error "Not at a drawer"))
22245 (let ((element (org-element-at-point)))
22246 (unless (memq (org-element-type element) '(drawer property-drawer))
22247 (user-error "Not at a drawer"))
22248 (org-with-wide-buffer
22249 (org-indent-region (org-element-property :begin element)
22250 (org-element-property :end element))))
22251 (message "Drawer at point indented"))
22253 (defun org-indent-block ()
22254 "Indent the block at point."
22255 (interactive)
22256 (unless (save-excursion
22257 (beginning-of-line)
22258 (let ((case-fold-search t))
22259 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22260 (user-error "Not at a block"))
22261 (let ((element (org-element-at-point)))
22262 (unless (memq (org-element-type element)
22263 '(comment-block center-block dynamic-block example-block
22264 export-block quote-block special-block
22265 src-block verse-block))
22266 (user-error "Not at a block"))
22267 (org-with-wide-buffer
22268 (org-indent-region (org-element-property :begin element)
22269 (org-element-property :end element))))
22270 (message "Block at point indented"))
22273 ;;; Filling
22275 ;; We use our own fill-paragraph and auto-fill functions.
22277 ;; `org-fill-paragraph' relies on adaptive filling and context
22278 ;; checking. Appropriate `fill-prefix' is computed with
22279 ;; `org-adaptive-fill-function'.
22281 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22282 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22283 ;; `org-adaptive-fill-function' value. Internally,
22284 ;; `org-comment-line-break-function' breaks the line.
22286 ;; `org-setup-filling' installs filling and auto-filling related
22287 ;; variables during `org-mode' initialization.
22289 (defun org-setup-filling ()
22290 (require 'org-element)
22291 ;; Prevent auto-fill from inserting unwanted new items.
22292 (when (boundp 'fill-nobreak-predicate)
22293 (setq-local
22294 fill-nobreak-predicate
22295 (org-uniquify
22296 (append fill-nobreak-predicate
22297 '(org-fill-line-break-nobreak-p
22298 org-fill-n-macro-as-item-nobreak-p
22299 org-fill-paragraph-with-timestamp-nobreak-p)))))
22300 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22301 (setq-local paragraph-start paragraph-ending)
22302 (setq-local paragraph-separate paragraph-ending))
22303 (setq-local fill-paragraph-function 'org-fill-paragraph)
22304 (setq-local auto-fill-inhibit-regexp nil)
22305 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22306 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22307 (setq-local comment-line-break-function 'org-comment-line-break-function))
22309 (defun org-fill-line-break-nobreak-p ()
22310 "Non-nil when a new line at point would create an Org line break."
22311 (save-excursion
22312 (skip-chars-backward "[ \t]")
22313 (skip-chars-backward "\\\\")
22314 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22316 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22317 "Non-nil when a new line at point would split a timestamp."
22318 (and (org-at-timestamp-p 'lax)
22319 (not (looking-at org-ts-regexp-both))))
22321 (defun org-fill-n-macro-as-item-nobreak-p ()
22322 "Non-nil when a new line at point would create a new list."
22323 ;; During export, a "n" macro followed by a dot or a closing
22324 ;; parenthesis can end up being parsed as a new list item.
22325 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22327 (declare-function message-in-body-p "message" ())
22328 (defvar orgtbl-line-start-regexp) ; From org-table.el
22329 (defun org-adaptive-fill-function ()
22330 "Compute a fill prefix for the current line.
22331 Return fill prefix, as a string, or nil if current line isn't
22332 meant to be filled. For convenience, if `adaptive-fill-regexp'
22333 matches in paragraphs or comments, use it."
22334 (catch 'exit
22335 (when (derived-mode-p 'message-mode)
22336 (save-excursion
22337 (beginning-of-line)
22338 (cond ((not (message-in-body-p)) (throw 'exit nil))
22339 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22340 ((looking-at message-cite-prefix-regexp)
22341 (throw 'exit (match-string-no-properties 0)))
22342 ((looking-at org-outline-regexp)
22343 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22344 (org-with-wide-buffer
22345 (unless (org-at-heading-p)
22346 (let* ((p (line-beginning-position))
22347 (element (save-excursion
22348 (beginning-of-line)
22349 (org-element-at-point)))
22350 (type (org-element-type element))
22351 (post-affiliated (org-element-property :post-affiliated element)))
22352 (unless (< p post-affiliated)
22353 (cl-case type
22354 (comment
22355 (save-excursion
22356 (beginning-of-line)
22357 (looking-at "[ \t]*")
22358 (concat (match-string 0) "# ")))
22359 (footnote-definition "")
22360 ((item plain-list)
22361 (make-string (org-list-item-body-column post-affiliated) ?\s))
22362 (paragraph
22363 ;; Fill prefix is usually the same as the current line,
22364 ;; unless the paragraph is at the beginning of an item.
22365 (let ((parent (org-element-property :parent element)))
22366 (save-excursion
22367 (beginning-of-line)
22368 (cond ((eq (org-element-type parent) 'item)
22369 (make-string (org-list-item-body-column
22370 (org-element-property :begin parent))
22371 ?\s))
22372 ((and adaptive-fill-regexp
22373 ;; Locally disable
22374 ;; `adaptive-fill-function' to let
22375 ;; `fill-context-prefix' handle
22376 ;; `adaptive-fill-regexp' variable.
22377 (let (adaptive-fill-function)
22378 (fill-context-prefix
22379 post-affiliated
22380 (org-element-property :end element)))))
22381 ((looking-at "[ \t]+") (match-string 0))
22382 (t "")))))
22383 (comment-block
22384 ;; Only fill contents if P is within block boundaries.
22385 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22386 (forward-line)
22387 (point)))
22388 (cend (save-excursion
22389 (goto-char (org-element-property :end element))
22390 (skip-chars-backward " \r\t\n")
22391 (line-beginning-position))))
22392 (when (and (>= p cbeg) (< p cend))
22393 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22394 (match-string 0)
22395 "")))))))))))
22397 (declare-function message-goto-body "message" ())
22398 (defvar message-cite-prefix-regexp) ; From message.el
22400 (defun org-fill-element (&optional justify)
22401 "Fill element at point, when applicable.
22403 This function only applies to comment blocks, comments, example
22404 blocks and paragraphs. Also, as a special case, re-align table
22405 when point is at one.
22407 If JUSTIFY is non-nil (interactively, with prefix argument),
22408 justify as well. If `sentence-end-double-space' is non-nil, then
22409 period followed by one space does not end a sentence, so don't
22410 break a line there. The variable `fill-column' controls the
22411 width for filling.
22413 For convenience, when point is at a plain list, an item or
22414 a footnote definition, try to fill the first paragraph within."
22415 (with-syntax-table org-mode-transpose-word-syntax-table
22416 ;; Move to end of line in order to get the first paragraph within
22417 ;; a plain list or a footnote definition.
22418 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22419 ;; First check if point is in a blank line at the beginning of
22420 ;; the buffer. In that case, ignore filling.
22421 (cl-case (org-element-type element)
22422 ;; Use major mode filling function is src blocks.
22423 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22424 ;; Align Org tables, leave table.el tables as-is.
22425 (table-row (org-table-align) t)
22426 (table
22427 (when (eq (org-element-property :type element) 'org)
22428 (save-excursion
22429 (goto-char (org-element-property :post-affiliated element))
22430 (org-table-align)))
22432 (paragraph
22433 ;; Paragraphs may contain `line-break' type objects.
22434 (let ((beg (max (point-min)
22435 (org-element-property :contents-begin element)))
22436 (end (min (point-max)
22437 (org-element-property :contents-end element))))
22438 ;; Do nothing if point is at an affiliated keyword.
22439 (if (< (line-end-position) beg) t
22440 (when (derived-mode-p 'message-mode)
22441 ;; In `message-mode', do not fill following citation
22442 ;; in current paragraph nor text before message body.
22443 (let ((body-start (save-excursion (message-goto-body))))
22444 (when body-start (setq beg (max body-start beg))))
22445 (when (save-excursion
22446 (re-search-forward
22447 (concat "^" message-cite-prefix-regexp) end t))
22448 (setq end (match-beginning 0))))
22449 ;; Fill paragraph, taking line breaks into account.
22450 (save-excursion
22451 (goto-char beg)
22452 (let ((cuts (list beg)))
22453 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22454 (when (eq 'line-break
22455 (org-element-type
22456 (save-excursion (backward-char)
22457 (org-element-context))))
22458 (push (point) cuts)))
22459 (dolist (c (delq end cuts))
22460 (fill-region-as-paragraph c end justify)
22461 (setq end c))))
22462 t)))
22463 ;; Contents of `comment-block' type elements should be
22464 ;; filled as plain text, but only if point is within block
22465 ;; markers.
22466 (comment-block
22467 (let* ((case-fold-search t)
22468 (beg (save-excursion
22469 (goto-char (org-element-property :begin element))
22470 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22471 (forward-line)
22472 (point)))
22473 (end (save-excursion
22474 (goto-char (org-element-property :end element))
22475 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22476 (line-beginning-position))))
22477 (if (or (< (point) beg) (> (point) end)) t
22478 (fill-region-as-paragraph
22479 (save-excursion (end-of-line)
22480 (re-search-backward "^[ \t]*$" beg 'move)
22481 (line-beginning-position))
22482 (save-excursion (beginning-of-line)
22483 (re-search-forward "^[ \t]*$" end 'move)
22484 (line-beginning-position))
22485 justify))))
22486 ;; Fill comments.
22487 (comment
22488 (let ((begin (org-element-property :post-affiliated element))
22489 (end (org-element-property :end element)))
22490 (when (and (>= (point) begin) (<= (point) end))
22491 (let ((begin (save-excursion
22492 (end-of-line)
22493 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22494 (progn (forward-line) (point))
22495 begin)))
22496 (end (save-excursion
22497 (end-of-line)
22498 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22499 (1- (line-beginning-position))
22500 (skip-chars-backward " \r\t\n")
22501 (line-end-position)))))
22502 ;; Do not fill comments when at a blank line.
22503 (when (> end begin)
22504 (let ((fill-prefix
22505 (save-excursion
22506 (beginning-of-line)
22507 (looking-at "[ \t]*#")
22508 (let ((comment-prefix (match-string 0)))
22509 (goto-char (match-end 0))
22510 (if (looking-at adaptive-fill-regexp)
22511 (concat comment-prefix (match-string 0))
22512 (concat comment-prefix " "))))))
22513 (save-excursion
22514 (fill-region-as-paragraph begin end justify))))))
22516 ;; Ignore every other element.
22517 (otherwise t)))))
22519 (defun org-fill-paragraph (&optional justify region)
22520 "Fill element at point, when applicable.
22522 This function only applies to comment blocks, comments, example
22523 blocks and paragraphs. Also, as a special case, re-align table
22524 when point is at one.
22526 For convenience, when point is at a plain list, an item or
22527 a footnote definition, try to fill the first paragraph within.
22529 If JUSTIFY is non-nil (interactively, with prefix argument),
22530 justify as well. If `sentence-end-double-space' is non-nil, then
22531 period followed by one space does not end a sentence, so don't
22532 break a line there. The variable `fill-column' controls the
22533 width for filling.
22535 The REGION argument is non-nil if called interactively; in that
22536 case, if Transient Mark mode is enabled and the mark is active,
22537 fill each of the elements in the active region, instead of just
22538 filling the current element."
22539 (interactive (progn
22540 (barf-if-buffer-read-only)
22541 (list (if current-prefix-arg 'full) t)))
22542 (cond
22543 ((and (derived-mode-p 'message-mode)
22544 (or (not (message-in-body-p))
22545 (save-excursion (move-beginning-of-line 1)
22546 (looking-at message-cite-prefix-regexp))))
22547 ;; First ensure filling is correct in message-mode.
22548 (let ((fill-paragraph-function
22549 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22550 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22551 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22552 (paragraph-separate
22553 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22554 (fill-paragraph nil)))
22555 ((and region transient-mark-mode mark-active
22556 (not (eq (region-beginning) (region-end))))
22557 (let ((origin (point-marker))
22558 (start (region-beginning)))
22559 (unwind-protect
22560 (progn
22561 (goto-char (region-end))
22562 (while (> (point) start)
22563 (org-backward-paragraph)
22564 (org-fill-element justify)))
22565 (goto-char origin)
22566 (set-marker origin nil))))
22567 (t (org-fill-element justify))))
22568 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22570 (defun org-auto-fill-function ()
22571 "Auto-fill function."
22572 ;; Check if auto-filling is meaningful.
22573 (let ((fc (current-fill-column)))
22574 (when (and fc (> (current-column) fc))
22575 (let* ((fill-prefix (org-adaptive-fill-function))
22576 ;; Enforce empty fill prefix, if required. Otherwise, it
22577 ;; will be computed again.
22578 (adaptive-fill-mode (not (equal fill-prefix ""))))
22579 (when fill-prefix (do-auto-fill))))))
22581 (defun org-comment-line-break-function (&optional soft)
22582 "Break line at point and indent, continuing comment if within one.
22583 The inserted newline is marked hard if variable
22584 `use-hard-newlines' is true, unless optional argument SOFT is
22585 non-nil."
22586 (if soft (insert-and-inherit ?\n) (newline 1))
22587 (save-excursion (forward-char -1) (delete-horizontal-space))
22588 (delete-horizontal-space)
22589 (indent-to-left-margin)
22590 (insert-before-markers-and-inherit fill-prefix))
22593 ;;; Fixed Width Areas
22595 (defun org-toggle-fixed-width ()
22596 "Toggle fixed-width markup.
22598 Add or remove fixed-width markup on current line, whenever it
22599 makes sense. Return an error otherwise.
22601 If a region is active and if it contains only fixed-width areas
22602 or blank lines, remove all fixed-width markup in it. If the
22603 region contains anything else, convert all non-fixed-width lines
22604 to fixed-width ones.
22606 Blank lines at the end of the region are ignored unless the
22607 region only contains such lines."
22608 (interactive)
22609 (if (not (org-region-active-p))
22610 ;; No region:
22612 ;; Remove fixed width marker only in a fixed-with element.
22614 ;; Add fixed width maker in paragraphs, in blank lines after
22615 ;; elements or at the beginning of a headline or an inlinetask,
22616 ;; and before any one-line elements (e.g., a clock).
22617 (progn
22618 (beginning-of-line)
22619 (let* ((element (org-element-at-point))
22620 (type (org-element-type element)))
22621 (cond
22622 ((and (eq type 'fixed-width)
22623 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22624 (replace-match
22625 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22626 ((and (memq type '(babel-call clock comment diary-sexp headline
22627 horizontal-rule keyword paragraph
22628 planning))
22629 (<= (org-element-property :post-affiliated element) (point)))
22630 (skip-chars-forward " \t")
22631 (insert ": "))
22632 ((and (looking-at-p "[ \t]*$")
22633 (or (eq type 'inlinetask)
22634 (save-excursion
22635 (skip-chars-forward " \r\t\n")
22636 (<= (org-element-property :end element) (point)))))
22637 (delete-region (point) (line-end-position))
22638 (org-indent-line)
22639 (insert ": "))
22640 (t (user-error "Cannot insert a fixed-width line here")))))
22641 ;; Region active.
22642 (let* ((begin (save-excursion
22643 (goto-char (region-beginning))
22644 (line-beginning-position)))
22645 (end (copy-marker
22646 (save-excursion
22647 (goto-char (region-end))
22648 (unless (eolp) (beginning-of-line))
22649 (if (save-excursion (re-search-backward "\\S-" begin t))
22650 (progn (skip-chars-backward " \r\t\n") (point))
22651 (point)))))
22652 (all-fixed-width-p
22653 (catch 'not-all-p
22654 (save-excursion
22655 (goto-char begin)
22656 (skip-chars-forward " \r\t\n")
22657 (when (eobp) (throw 'not-all-p nil))
22658 (while (< (point) end)
22659 (let ((element (org-element-at-point)))
22660 (if (eq (org-element-type element) 'fixed-width)
22661 (goto-char (org-element-property :end element))
22662 (throw 'not-all-p nil))))
22663 t))))
22664 (if all-fixed-width-p
22665 (save-excursion
22666 (goto-char begin)
22667 (while (< (point) end)
22668 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22669 (replace-match
22670 "" nil nil nil
22671 (if (= (line-end-position) (match-end 0)) 0 1)))
22672 (forward-line)))
22673 (let ((min-ind (point-max)))
22674 ;; Find minimum indentation across all lines.
22675 (save-excursion
22676 (goto-char begin)
22677 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22678 (setq min-ind 0)
22679 (catch 'zerop
22680 (while (< (point) end)
22681 (unless (looking-at-p "[ \t]*$")
22682 (let ((ind (org-get-indentation)))
22683 (setq min-ind (min min-ind ind))
22684 (when (zerop ind) (throw 'zerop t))))
22685 (forward-line)))))
22686 ;; Loop over all lines and add fixed-width markup everywhere
22687 ;; but in fixed-width lines.
22688 (save-excursion
22689 (goto-char begin)
22690 (while (< (point) end)
22691 (cond
22692 ((org-at-heading-p)
22693 (insert ": ")
22694 (forward-line)
22695 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22696 (insert ":")
22697 (forward-line)))
22698 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22699 (let* ((element (org-element-at-point))
22700 (element-end (org-element-property :end element)))
22701 (if (eq (org-element-type element) 'fixed-width)
22702 (progn (goto-char element-end)
22703 (skip-chars-backward " \r\t\n")
22704 (forward-line))
22705 (let ((limit (min end element-end)))
22706 (while (< (point) limit)
22707 (org-move-to-column min-ind t)
22708 (insert ": ")
22709 (forward-line))))))
22711 (org-move-to-column min-ind t)
22712 (insert ": ")
22713 (forward-line)))))))
22714 (set-marker end nil))))
22717 ;;; Comments
22719 ;; Org comments syntax is quite complex. It requires the entire line
22720 ;; to be just a comment. Also, even with the right syntax at the
22721 ;; beginning of line, some elements (e.g., verse-block or
22722 ;; example-block) don't accept comments. Usual Emacs comment commands
22723 ;; cannot cope with those requirements. Therefore, Org replaces them.
22725 ;; Org still relies on `comment-dwim', but cannot trust
22726 ;; `comment-only-p'. So, `comment-region-function' and
22727 ;; `uncomment-region-function' both point
22728 ;; to`org-comment-or-uncomment-region'. Eventually,
22729 ;; `org-insert-comment' takes care of insertion of comments at the
22730 ;; beginning of line.
22732 ;; `org-setup-comments-handling' install comments related variables
22733 ;; during `org-mode' initialization.
22735 (defun org-setup-comments-handling ()
22736 (interactive)
22737 (setq-local comment-use-syntax nil)
22738 (setq-local comment-start "# ")
22739 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22740 (setq-local comment-insert-comment-function 'org-insert-comment)
22741 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22742 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22744 (defun org-insert-comment ()
22745 "Insert an empty comment above current line.
22746 If the line is empty, insert comment at its beginning. When
22747 point is within a source block, comment according to the related
22748 major mode."
22749 (if (let ((element (org-element-at-point)))
22750 (and (eq (org-element-type element) 'src-block)
22751 (< (save-excursion
22752 (goto-char (org-element-property :post-affiliated element))
22753 (line-end-position))
22754 (point))
22755 (> (save-excursion
22756 (goto-char (org-element-property :end element))
22757 (skip-chars-backward " \r\t\n")
22758 (line-beginning-position))
22759 (point))))
22760 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22761 (beginning-of-line)
22762 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22763 (open-line 1))
22764 (org-indent-line)
22765 (insert "# ")))
22767 (defvar comment-empty-lines) ; From newcomment.el.
22768 (defun org-comment-or-uncomment-region (beg end &rest _)
22769 "Comment or uncomment each non-blank line in the region.
22770 Uncomment each non-blank line between BEG and END if it only
22771 contains commented lines. Otherwise, comment them. If region is
22772 strictly within a source block, use appropriate comment syntax."
22773 (if (let ((element (org-element-at-point)))
22774 (and (eq (org-element-type element) 'src-block)
22775 (< (save-excursion
22776 (goto-char (org-element-property :post-affiliated element))
22777 (line-end-position))
22778 beg)
22779 (>= (save-excursion
22780 (goto-char (org-element-property :end element))
22781 (skip-chars-backward " \r\t\n")
22782 (line-beginning-position))
22783 end)))
22784 ;; Translate region boundaries for the Org buffer to the source
22785 ;; buffer.
22786 (let ((offset (- end beg)))
22787 (save-excursion
22788 (goto-char beg)
22789 (org-babel-do-in-edit-buffer
22790 (comment-or-uncomment-region (point) (+ offset (point))))))
22791 (save-restriction
22792 ;; Restrict region
22793 (narrow-to-region (save-excursion (goto-char beg)
22794 (skip-chars-forward " \r\t\n" end)
22795 (line-beginning-position))
22796 (save-excursion (goto-char end)
22797 (skip-chars-backward " \r\t\n" beg)
22798 (line-end-position)))
22799 (let ((uncommentp
22800 ;; UNCOMMENTP is non-nil when every non blank line between
22801 ;; BEG and END is a comment.
22802 (save-excursion
22803 (goto-char (point-min))
22804 (while (and (not (eobp))
22805 (let ((element (org-element-at-point)))
22806 (and (eq (org-element-type element) 'comment)
22807 (goto-char (min (point-max)
22808 (org-element-property
22809 :end element)))))))
22810 (eobp))))
22811 (if uncommentp
22812 ;; Only blank lines and comments in region: uncomment it.
22813 (save-excursion
22814 (goto-char (point-min))
22815 (while (not (eobp))
22816 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22817 (replace-match "" nil nil nil 1))
22818 (forward-line)))
22819 ;; Comment each line in region.
22820 (let ((min-indent (point-max)))
22821 ;; First find the minimum indentation across all lines.
22822 (save-excursion
22823 (goto-char (point-min))
22824 (while (and (not (eobp)) (not (zerop min-indent)))
22825 (unless (looking-at "[ \t]*$")
22826 (setq min-indent (min min-indent (current-indentation))))
22827 (forward-line)))
22828 ;; Then loop over all lines.
22829 (save-excursion
22830 (goto-char (point-min))
22831 (while (not (eobp))
22832 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22833 ;; Don't get fooled by invisible text (e.g. link path)
22834 ;; when moving to column MIN-INDENT.
22835 (let ((buffer-invisibility-spec nil))
22836 (org-move-to-column min-indent t))
22837 (insert comment-start))
22838 (forward-line)))))))))
22840 (defun org-comment-dwim (_arg)
22841 "Call the comment command you mean.
22842 Call `org-toggle-comment' if on a heading, otherwise call
22843 `comment-dwim', within a source edit buffer if needed."
22844 (interactive "*P")
22845 (cond ((org-at-heading-p)
22846 (call-interactively #'org-toggle-comment))
22847 ((org-in-src-block-p)
22848 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22849 (t (call-interactively #'comment-dwim))))
22852 ;;; Timestamps API
22854 ;; This section contains tools to operate on timestamp objects, as
22855 ;; returned by, e.g. `org-element-context'.
22857 (defun org-timestamp--to-internal-time (timestamp &optional end)
22858 "Encode TIMESTAMP object into Emacs internal time.
22859 Use end of date range or time range when END is non-nil."
22860 (apply #'encode-time
22861 (cons 0
22862 (mapcar
22863 (lambda (prop) (or (org-element-property prop timestamp) 0))
22864 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22865 '(:minute-start :hour-start :day-start :month-start
22866 :year-start))))))
22868 (defun org-timestamp-has-time-p (timestamp)
22869 "Non-nil when TIMESTAMP has a time specified."
22870 (org-element-property :hour-start timestamp))
22872 (defun org-timestamp-format (timestamp format &optional end utc)
22873 "Format a TIMESTAMP object into a string.
22875 FORMAT is a format specifier to be passed to
22876 `format-time-string'.
22878 When optional argument END is non-nil, use end of date-range or
22879 time-range, if possible.
22881 When optional argument UTC is non-nil, time will be expressed as
22882 Universal Time."
22883 (format-time-string
22884 format (org-timestamp--to-internal-time timestamp end)
22885 (and utc t)))
22887 (defun org-timestamp-split-range (timestamp &optional end)
22888 "Extract a TIMESTAMP object from a date or time range.
22890 END, when non-nil, means extract the end of the range.
22891 Otherwise, extract its start.
22893 Return a new timestamp object."
22894 (let ((type (org-element-property :type timestamp)))
22895 (if (memq type '(active inactive diary)) timestamp
22896 (let ((split-ts (org-element-copy timestamp)))
22897 ;; Set new type.
22898 (org-element-put-property
22899 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22900 ;; Copy start properties over end properties if END is
22901 ;; non-nil. Otherwise, copy end properties over `start' ones.
22902 (let ((p-alist '((:minute-start . :minute-end)
22903 (:hour-start . :hour-end)
22904 (:day-start . :day-end)
22905 (:month-start . :month-end)
22906 (:year-start . :year-end))))
22907 (dolist (p-cell p-alist)
22908 (org-element-put-property
22909 split-ts
22910 (funcall (if end #'car #'cdr) p-cell)
22911 (org-element-property
22912 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22913 ;; Eventually refresh `:raw-value'.
22914 (org-element-put-property split-ts :raw-value nil)
22915 (org-element-put-property
22916 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22918 (defun org-timestamp-translate (timestamp &optional boundary)
22919 "Translate TIMESTAMP object to custom format.
22921 Format string is defined in `org-time-stamp-custom-formats',
22922 which see.
22924 When optional argument BOUNDARY is non-nil, it is either the
22925 symbol `start' or `end'. In this case, only translate the
22926 starting or ending part of TIMESTAMP if it is a date or time
22927 range. Otherwise, translate both parts.
22929 Return timestamp as-is if `org-display-custom-times' is nil or if
22930 it has a `diary' type."
22931 (let ((type (org-element-property :type timestamp)))
22932 (if (or (not org-display-custom-times) (eq type 'diary))
22933 (org-element-interpret-data timestamp)
22934 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22935 org-time-stamp-custom-formats)))
22936 (if (and (not boundary) (memq type '(active-range inactive-range)))
22937 (concat (org-timestamp-format timestamp fmt)
22938 "--"
22939 (org-timestamp-format timestamp fmt t))
22940 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22944 ;;; Other stuff.
22946 (defvar reftex-docstruct-symbol)
22947 (defvar org--rds)
22949 (defun org-reftex-citation ()
22950 "Use reftex-citation to insert a citation into the buffer.
22951 This looks for a line like
22953 #+BIBLIOGRAPHY: foo plain option:-d
22955 and derives from it that foo.bib is the bibliography file relevant
22956 for this document. It then installs the necessary environment for RefTeX
22957 to work in this buffer and calls `reftex-citation' to insert a citation
22958 into the buffer.
22960 Export of such citations to both LaTeX and HTML is handled by the contributed
22961 package ox-bibtex by Taru Karttunen."
22962 (interactive)
22963 (let ((reftex-docstruct-symbol 'org--rds)
22964 org--rds bib)
22965 (org-with-wide-buffer
22966 (let ((case-fold-search t)
22967 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22968 (if (not (save-excursion
22969 (or (re-search-forward re nil t)
22970 (re-search-backward re nil t))))
22971 (user-error "No bibliography defined in file")
22972 (setq bib (concat (match-string 1) ".bib")
22973 org--rds (list (list 'bib bib))))))
22974 (call-interactively 'reftex-citation)))
22976 ;;;; Functions extending outline functionality
22978 (defun org-beginning-of-line (&optional n)
22979 "Go to the beginning of the current visible line.
22981 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22982 tags on the first attempt, and only move to after the tags when
22983 the cursor is already beyond the end of the headline.
22985 With argument N not nil or 1, move forward N - 1 lines first."
22986 (interactive "^p")
22987 (let ((origin (point))
22988 (special (pcase org-special-ctrl-a/e
22989 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22990 deactivate-mark)
22991 ;; First move to a visible line.
22992 (if (bound-and-true-p visual-line-mode)
22993 (beginning-of-visual-line n)
22994 (move-beginning-of-line n)
22995 ;; `move-beginning-of-line' may leave point after invisible
22996 ;; characters if line starts with such of these (e.g., with
22997 ;; a link at column 0). Really move to the beginning of the
22998 ;; current visible line.
22999 (beginning-of-line))
23000 (cond
23001 ;; No special behavior. Point is already at the beginning of
23002 ;; a line, logical or visual.
23003 ((not special))
23004 ;; `beginning-of-visual-line' left point before logical beginning
23005 ;; of line: point is at the beginning of a visual line. Bail
23006 ;; out.
23007 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23008 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23009 ;; At a headline, special position is before the title, but
23010 ;; after any TODO keyword or priority cookie.
23011 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23012 (line-end-position)))
23013 (bol (point)))
23014 (if (eq special 'reversed)
23015 (when (and (= origin bol) (eq last-command this-command))
23016 (goto-char refpos))
23017 (when (or (> origin refpos) (= origin bol))
23018 (goto-char refpos)))))
23019 ((and (looking-at org-list-full-item-re)
23020 (memq (org-element-type (save-match-data (org-element-at-point)))
23021 '(item plain-list)))
23022 ;; Set special position at first white space character after
23023 ;; bullet, and check-box, if any.
23024 (let ((after-bullet
23025 (let ((box (match-end 3)))
23026 (cond ((not box) (match-end 1))
23027 ((eq (char-after box) ?\s) (1+ box))
23028 (t box)))))
23029 (if (eq special 'reversed)
23030 (when (and (= (point) origin) (eq last-command this-command))
23031 (goto-char after-bullet))
23032 (when (or (> origin after-bullet) (= (point) origin))
23033 (goto-char after-bullet)))))
23034 ;; No special context. Point is already at beginning of line.
23035 (t nil))))
23037 (defun org-end-of-line (&optional n)
23038 "Go to the end of the line, but before ellipsis, if any.
23040 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23041 tags on the first attempt, and only move to after the tags when
23042 the cursor is already beyond the end of the headline.
23044 With argument N not nil or 1, move forward N - 1 lines first."
23045 (interactive "^p")
23046 (let ((origin (point))
23047 (special (pcase org-special-ctrl-a/e
23048 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23049 deactivate-mark)
23050 ;; First move to a visible line.
23051 (if (bound-and-true-p visual-line-mode)
23052 (beginning-of-visual-line n)
23053 (move-beginning-of-line n))
23054 (cond
23055 ;; At a headline, with tags.
23056 ((and special
23057 (save-excursion
23058 (beginning-of-line)
23059 (let ((case-fold-search nil))
23060 (looking-at org-complex-heading-regexp)))
23061 (match-end 5))
23062 (let ((tags (save-excursion
23063 (goto-char (match-beginning 5))
23064 (skip-chars-backward " \t")
23065 (point)))
23066 (visual-end (and (bound-and-true-p visual-line-mode)
23067 (save-excursion
23068 (end-of-visual-line)
23069 (point)))))
23070 ;; If `end-of-visual-line' brings us before end of line or
23071 ;; even tags, i.e., the headline spans over multiple visual
23072 ;; lines, move there.
23073 (cond ((and visual-end
23074 (< visual-end tags)
23075 (<= origin visual-end))
23076 (goto-char visual-end))
23077 ((eq special 'reversed)
23078 (if (and (= origin (line-end-position))
23079 (eq this-command last-command))
23080 (goto-char tags)
23081 (end-of-line)))
23083 (if (or (< origin tags) (= origin (line-end-position)))
23084 (goto-char tags)
23085 (end-of-line))))))
23086 ((bound-and-true-p visual-line-mode)
23087 (let ((bol (line-beginning-position)))
23088 (end-of-visual-line)
23089 ;; If `end-of-visual-line' gets us past the ellipsis at the
23090 ;; end of a line, backtrack and use `end-of-line' instead.
23091 (when (/= bol (line-beginning-position))
23092 (goto-char bol)
23093 (end-of-line))))
23094 (t (end-of-line)))))
23096 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23097 (define-key org-mode-map "\C-e" 'org-end-of-line)
23099 (defun org-backward-sentence (&optional _arg)
23100 "Go to beginning of sentence, or beginning of table field.
23101 This will call `backward-sentence' or `org-table-beginning-of-field',
23102 depending on context."
23103 (interactive)
23104 (let* ((element (org-element-at-point))
23105 (contents-begin (org-element-property :contents-begin element))
23106 (table (org-element-lineage element '(table) t)))
23107 (if (and table
23108 (> (point) contents-begin)
23109 (<= (point) (org-element-property :contents-end table)))
23110 (call-interactively #'org-table-beginning-of-field)
23111 (save-restriction
23112 (when (and contents-begin
23113 (< (point-min) contents-begin)
23114 (> (point) contents-begin))
23115 (narrow-to-region contents-begin
23116 (org-element-property :contents-end element)))
23117 (call-interactively #'backward-sentence)))))
23119 (defun org-forward-sentence (&optional _arg)
23120 "Go to end of sentence, or end of table field.
23121 This will call `forward-sentence' or `org-table-end-of-field',
23122 depending on context."
23123 (interactive)
23124 (if (and (org-at-heading-p)
23125 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23126 (save-restriction
23127 (narrow-to-region (line-beginning-position) (line-end-position))
23128 (call-interactively #'forward-sentence))
23129 (let* ((element (org-element-at-point))
23130 (contents-end (org-element-property :contents-end element))
23131 (table (org-element-lineage element '(table) t)))
23132 (if (and table
23133 (>= (point) (org-element-property :contents-begin table))
23134 (< (point) contents-end))
23135 (call-interactively #'org-table-end-of-field)
23136 (save-restriction
23137 (when (and contents-end
23138 (> (point-max) contents-end)
23139 ;; Skip blank lines between elements.
23140 (< (org-element-property :end element)
23141 (save-excursion (goto-char contents-end)
23142 (skip-chars-forward " \r\t\n"))))
23143 (narrow-to-region (org-element-property :contents-begin element)
23144 contents-end))
23145 ;; End of heading is considered as the end of a sentence.
23146 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23147 (call-interactively #'forward-sentence)))))))
23149 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23150 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23152 (defun org-kill-line (&optional _arg)
23153 "Kill line, to tags or end of line."
23154 (interactive)
23155 (cond
23156 ((or (not org-special-ctrl-k)
23157 (bolp)
23158 (not (org-at-heading-p)))
23159 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23160 org-ctrl-k-protect-subtree
23161 (or (eq org-ctrl-k-protect-subtree 'error)
23162 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23163 (user-error "C-k aborted as it would kill a hidden subtree"))
23164 (call-interactively
23165 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23166 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23167 (kill-region (point) (match-beginning 1))
23168 (org-set-tags nil t))
23169 (t (kill-region (point) (point-at-eol)))))
23171 (define-key org-mode-map "\C-k" 'org-kill-line)
23173 (defun org-yank (&optional arg)
23174 "Yank. If the kill is a subtree, treat it specially.
23175 This command will look at the current kill and check if is a single
23176 subtree, or a series of subtrees[1]. If it passes the test, and if the
23177 cursor is at the beginning of a line or after the stars of a currently
23178 empty headline, then the yank is handled specially. How exactly depends
23179 on the value of the following variables.
23181 `org-yank-folded-subtrees'
23182 By default, this variable is non-nil, which results in
23183 subtree(s) being folded after insertion, except if doing so
23184 would swallow text after the yanked text.
23186 `org-yank-adjusted-subtrees'
23187 When non-nil (the default value is nil), the subtree will be
23188 promoted or demoted in order to fit into the local outline tree
23189 structure, which means that the level will be adjusted so that it
23190 becomes the smaller one of the two *visible* surrounding headings.
23192 Any prefix to this command will cause `yank' to be called directly with
23193 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23194 will just
23195 plainly yank the text as it is.
23197 \[1] The test checks if the first non-white line is a heading
23198 and if there are no other headings with fewer stars."
23199 (interactive "P")
23200 (org-yank-generic 'yank arg))
23202 (defun org-yank-generic (command arg)
23203 "Perform some yank-like command.
23205 This function implements the behavior described in the `org-yank'
23206 documentation. However, it has been generalized to work for any
23207 interactive command with similar behavior."
23209 ;; pretend to be command COMMAND
23210 (setq this-command command)
23212 (if arg
23213 (call-interactively command)
23215 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23216 (and (org-kill-is-subtree-p)
23217 (or (bolp)
23218 (and (looking-at "[ \t]*$")
23219 (string-match
23220 "\\`\\*+\\'"
23221 (buffer-substring (point-at-bol) (point)))))))
23222 swallowp)
23223 (cond
23224 ((and subtreep org-yank-folded-subtrees)
23225 (let ((beg (point))
23226 end)
23227 (if (and subtreep org-yank-adjusted-subtrees)
23228 (org-paste-subtree nil nil 'for-yank)
23229 (call-interactively command))
23231 (setq end (point))
23232 (goto-char beg)
23233 (when (and (bolp) subtreep
23234 (not (setq swallowp
23235 (org-yank-folding-would-swallow-text beg end))))
23236 (org-with-limited-levels
23237 (or (looking-at org-outline-regexp)
23238 (re-search-forward org-outline-regexp-bol end t))
23239 (while (and (< (point) end) (looking-at org-outline-regexp))
23240 (outline-hide-subtree)
23241 (org-cycle-show-empty-lines 'folded)
23242 (condition-case nil
23243 (outline-forward-same-level 1)
23244 (error (goto-char end))))))
23245 (when swallowp
23246 (message
23247 "Inserted text not folded because that would swallow text"))
23249 (goto-char end)
23250 (skip-chars-forward " \t\n\r")
23251 (beginning-of-line 1)
23252 (push-mark beg 'nomsg)))
23253 ((and subtreep org-yank-adjusted-subtrees)
23254 (let ((beg (point-at-bol)))
23255 (org-paste-subtree nil nil 'for-yank)
23256 (push-mark beg 'nomsg)))
23258 (call-interactively command))))))
23260 (defun org-yank-folding-would-swallow-text (beg end)
23261 "Would hide-subtree at BEG swallow any text after END?"
23262 (let (level)
23263 (org-with-limited-levels
23264 (save-excursion
23265 (goto-char beg)
23266 (when (or (looking-at org-outline-regexp)
23267 (re-search-forward org-outline-regexp-bol end t))
23268 (setq level (org-outline-level)))
23269 (goto-char end)
23270 (skip-chars-forward " \t\r\n\v\f")
23271 (not (or (eobp)
23272 (and (bolp) (looking-at-p org-outline-regexp)
23273 (<= (org-outline-level) level))))))))
23275 (define-key org-mode-map "\C-y" 'org-yank)
23277 (defun org-back-to-heading (&optional invisible-ok)
23278 "Call `outline-back-to-heading', but provide a better error message."
23279 (condition-case nil
23280 (outline-back-to-heading invisible-ok)
23281 (error (error "Before first headline at position %d in buffer %s"
23282 (point) (current-buffer)))))
23284 (defun org-before-first-heading-p ()
23285 "Before first heading?"
23286 (save-excursion
23287 (end-of-line)
23288 (null (re-search-backward org-outline-regexp-bol nil t))))
23290 (defun org-at-heading-p (&optional ignored)
23291 (outline-on-heading-p t))
23293 (defun org-in-commented-heading-p (&optional no-inheritance)
23294 "Non-nil if point is under a commented heading.
23295 This function also checks ancestors of the current headline,
23296 unless optional argument NO-INHERITANCE is non-nil."
23297 (cond
23298 ((org-before-first-heading-p) nil)
23299 ((let ((headline (nth 4 (org-heading-components))))
23300 (and headline
23301 (let ((case-fold-search nil))
23302 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23303 headline)))))
23304 (no-inheritance nil)
23306 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23308 (defun org-at-comment-p nil
23309 "Is cursor in a commented line?"
23310 (save-excursion
23311 (save-match-data
23312 (beginning-of-line)
23313 (looking-at "^[ \t]*# "))))
23315 (defun org-at-drawer-p nil
23316 "Is cursor at a drawer keyword?"
23317 (save-excursion
23318 (move-beginning-of-line 1)
23319 (looking-at org-drawer-regexp)))
23321 (defun org-at-block-p nil
23322 "Is cursor at a block keyword?"
23323 (save-excursion
23324 (move-beginning-of-line 1)
23325 (looking-at org-block-regexp)))
23327 (defun org-point-at-end-of-empty-headline ()
23328 "If point is at the end of an empty headline, return t, else nil.
23329 If the heading only contains a TODO keyword, it is still still considered
23330 empty."
23331 (let ((case-fold-search nil))
23332 (and (looking-at "[ \t]*$")
23333 org-todo-line-regexp
23334 (save-excursion
23335 (beginning-of-line)
23336 (looking-at org-todo-line-regexp)
23337 (string= (match-string 3) "")))))
23339 (defun org-at-heading-or-item-p ()
23340 (or (org-at-heading-p) (org-at-item-p)))
23342 (defun org-at-target-p ()
23343 (or (org-in-regexp org-radio-target-regexp)
23344 (org-in-regexp org-target-regexp)))
23345 ;; Compatibility alias with Org versions < 7.8.03
23346 (defalias 'org-on-target-p 'org-at-target-p)
23348 (defun org-up-heading-all (arg)
23349 "Move to the heading line of which the present line is a subheading.
23350 This function considers both visible and invisible heading lines.
23351 With argument, move up ARG levels."
23352 (outline-up-heading arg t))
23354 (defun org-up-heading-safe ()
23355 "Move to the heading line of which the present line is a subheading.
23356 This version will not throw an error. It will return the level of the
23357 headline found, or nil if no higher level is found.
23359 Also, this function will be a lot faster than `outline-up-heading',
23360 because it relies on stars being the outline starters. This can really
23361 make a significant difference in outlines with very many siblings."
23362 (when (ignore-errors (org-back-to-heading t))
23363 (let ((level-up (1- (funcall outline-level))))
23364 (and (> level-up 0)
23365 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23366 (funcall outline-level)))))
23368 (defun org-first-sibling-p ()
23369 "Is this heading the first child of its parents?"
23370 (interactive)
23371 (let ((re org-outline-regexp-bol)
23372 level l)
23373 (unless (org-at-heading-p t)
23374 (user-error "Not at a heading"))
23375 (setq level (funcall outline-level))
23376 (save-excursion
23377 (if (not (re-search-backward re nil t))
23379 (setq l (funcall outline-level))
23380 (< l level)))))
23382 (defun org-goto-sibling (&optional previous)
23383 "Goto the next sibling, even if it is invisible.
23384 When PREVIOUS is set, go to the previous sibling instead. Returns t
23385 when a sibling was found. When none is found, return nil and don't
23386 move point."
23387 (let ((fun (if previous 're-search-backward 're-search-forward))
23388 (pos (point))
23389 (re org-outline-regexp-bol)
23390 level l)
23391 (when (ignore-errors (org-back-to-heading t))
23392 (setq level (funcall outline-level))
23393 (catch 'exit
23394 (or previous (forward-char 1))
23395 (while (funcall fun re nil t)
23396 (setq l (funcall outline-level))
23397 (when (< l level) (goto-char pos) (throw 'exit nil))
23398 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23399 (goto-char pos)
23400 nil))))
23402 (defun org-show-siblings ()
23403 "Show all siblings of the current headline."
23404 (save-excursion
23405 (while (org-goto-sibling) (org-flag-heading nil)))
23406 (save-excursion
23407 (while (org-goto-sibling 'previous)
23408 (org-flag-heading nil))))
23410 (defun org-goto-first-child ()
23411 "Goto the first child, even if it is invisible.
23412 Return t when a child was found. Otherwise don't move point and
23413 return nil."
23414 (let (level (pos (point)) (re org-outline-regexp-bol))
23415 (when (ignore-errors (org-back-to-heading t))
23416 (setq level (outline-level))
23417 (forward-char 1)
23418 (if (and (re-search-forward re nil t) (> (outline-level) level))
23419 (progn (goto-char (match-beginning 0)) t)
23420 (goto-char pos) nil))))
23422 (defun org-show-hidden-entry ()
23423 "Show an entry where even the heading is hidden."
23424 (save-excursion
23425 (org-show-entry)))
23427 (defun org-flag-heading (flag &optional entry)
23428 "Flag the current heading. FLAG non-nil means make invisible.
23429 When ENTRY is non-nil, show the entire entry."
23430 (save-excursion
23431 (org-back-to-heading t)
23432 ;; Check if we should show the entire entry
23433 (if entry
23434 (progn
23435 (org-show-entry)
23436 (save-excursion
23437 (and (outline-next-heading)
23438 (org-flag-heading nil))))
23439 (outline-flag-region (max (point-min) (1- (point)))
23440 (save-excursion (outline-end-of-heading) (point))
23441 flag))))
23443 (defun org-get-next-sibling ()
23444 "Move to next heading of the same level, and return point.
23445 If there is no such heading, return nil.
23446 This is like outline-next-sibling, but invisible headings are ok."
23447 (let ((level (funcall outline-level)))
23448 (outline-next-heading)
23449 (while (and (not (eobp)) (> (funcall outline-level) level))
23450 (outline-next-heading))
23451 (unless (or (eobp) (< (funcall outline-level) level))
23452 (point))))
23454 (defun org-get-last-sibling ()
23455 "Move to previous heading of the same level, and return point.
23456 If there is no such heading, return nil."
23457 (let ((opoint (point))
23458 (level (funcall outline-level)))
23459 (outline-previous-heading)
23460 (when (and (/= (point) opoint) (outline-on-heading-p t))
23461 (while (and (> (funcall outline-level) level)
23462 (not (bobp)))
23463 (outline-previous-heading))
23464 (unless (< (funcall outline-level) level)
23465 (point)))))
23467 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23468 "Goto to the end of a subtree."
23469 ;; This contains an exact copy of the original function, but it uses
23470 ;; `org-back-to-heading', to make it work also in invisible
23471 ;; trees. And is uses an invisible-ok argument.
23472 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23473 ;; Furthermore, when used inside Org, finding the end of a large subtree
23474 ;; with many children and grandchildren etc, this can be much faster
23475 ;; than the outline version.
23476 (org-back-to-heading invisible-ok)
23477 (let ((first t)
23478 (level (funcall outline-level)))
23479 (if (and (derived-mode-p 'org-mode) (< level 1000))
23480 ;; A true heading (not a plain list item), in Org
23481 ;; This means we can easily find the end by looking
23482 ;; only for the right number of stars. Using a regexp to do
23483 ;; this is so much faster than using a Lisp loop.
23484 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23485 (forward-char 1)
23486 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23487 ;; something else, do it the slow way
23488 (while (and (not (eobp))
23489 (or first (> (funcall outline-level) level)))
23490 (setq first nil)
23491 (outline-next-heading)))
23492 (unless to-heading
23493 (when (memq (preceding-char) '(?\n ?\^M))
23494 ;; Go to end of line before heading
23495 (forward-char -1)
23496 (when (memq (preceding-char) '(?\n ?\^M))
23497 ;; leave blank line before heading
23498 (forward-char -1)))))
23499 (point))
23501 (defun org-end-of-meta-data (&optional full)
23502 "Skip planning line and properties drawer in current entry.
23503 When optional argument FULL is non-nil, also skip empty lines,
23504 clocking lines and regular drawers at the beginning of the
23505 entry."
23506 (org-back-to-heading t)
23507 (forward-line)
23508 (when (looking-at-p org-planning-line-re) (forward-line))
23509 (when (looking-at org-property-drawer-re)
23510 (goto-char (match-end 0))
23511 (forward-line))
23512 (when (and full (not (org-at-heading-p)))
23513 (catch 'exit
23514 (let ((end (save-excursion (outline-next-heading) (point)))
23515 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23516 (while (not (eobp))
23517 (cond ((looking-at-p org-drawer-regexp)
23518 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23519 (forward-line)
23520 (throw 'exit t)))
23521 ((looking-at-p re) (forward-line))
23522 (t (throw 'exit t))))))))
23524 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23525 "Move forward to the ARG'th subheading at same level as this one.
23526 Stop at the first and last subheadings of a superior heading.
23527 Normally this only looks at visible headings, but when INVISIBLE-OK is
23528 non-nil it will also look at invisible ones."
23529 (interactive "p")
23530 (let ((backward? (and arg (< arg 0))))
23531 (if (org-before-first-heading-p)
23532 (if backward? (goto-char (point-min)) (outline-next-heading))
23533 (org-back-to-heading invisible-ok)
23534 (unless backward? (end-of-line)) ;do not match current headline
23535 (let ((level (- (match-end 0) (match-beginning 0) 1))
23536 (f (if backward? #'re-search-backward #'re-search-forward))
23537 (count (if arg (abs arg) 1))
23538 (result (point)))
23539 (while (and (> count 0)
23540 (funcall f org-outline-regexp-bol nil 'move))
23541 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23542 (cond ((< l level) (setq count 0))
23543 ((and (= l level)
23544 (or invisible-ok
23545 (not (org-invisible-p
23546 (line-beginning-position)))))
23547 (cl-decf count)
23548 (when (= l level) (setq result (point)))))))
23549 (goto-char result))
23550 (beginning-of-line))))
23552 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23553 "Move backward to the ARG'th subheading at same level as this one.
23554 Stop at the first and last subheadings of a superior heading."
23555 (interactive "p")
23556 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23558 (defun org-next-visible-heading (arg)
23559 "Move to the next visible heading.
23561 This function wraps `outline-next-visible-heading' with
23562 `org-with-limited-levels' in order to skip over inline tasks and
23563 respect customization of `org-odd-levels-only'."
23564 (interactive "p")
23565 (org-with-limited-levels
23566 (outline-next-visible-heading arg)))
23568 (defun org-previous-visible-heading (arg)
23569 "Move to the previous visible heading.
23571 This function wraps `outline-previous-visible-heading' with
23572 `org-with-limited-levels' in order to skip over inline tasks and
23573 respect customization of `org-odd-levels-only'."
23574 (interactive "p")
23575 (org-with-limited-levels
23576 (outline-previous-visible-heading arg)))
23578 (defun org-next-block (arg &optional backward block-regexp)
23579 "Jump to the next block.
23581 With a prefix argument ARG, jump forward ARG many blocks.
23583 When BACKWARD is non-nil, jump to the previous block.
23585 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23586 Match data is set according to this regexp when the function
23587 returns.
23589 Return point at beginning of the opening line of found block.
23590 Throw an error if no block is found."
23591 (interactive "p")
23592 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23593 (case-fold-search t)
23594 (search-fn (if backward #'re-search-backward #'re-search-forward))
23595 (count (or arg 1))
23596 (origin (point))
23597 last-element)
23598 (if backward (beginning-of-line) (end-of-line))
23599 (while (and (> count 0) (funcall search-fn re nil t))
23600 (let ((element (save-excursion
23601 (goto-char (match-beginning 0))
23602 (save-match-data (org-element-at-point)))))
23603 (when (and (memq (org-element-type element)
23604 '(center-block comment-block dynamic-block
23605 example-block export-block quote-block
23606 special-block src-block verse-block))
23607 (<= (match-beginning 0)
23608 (org-element-property :post-affiliated element)))
23609 (setq last-element element)
23610 (cl-decf count))))
23611 (if (= count 0)
23612 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23613 (save-match-data (org-show-context)))
23614 (goto-char origin)
23615 (user-error "No %s code blocks" (if backward "previous" "further")))))
23617 (defun org-previous-block (arg &optional block-regexp)
23618 "Jump to the previous block.
23619 With a prefix argument ARG, jump backward ARG many source blocks.
23620 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23621 (interactive "p")
23622 (org-next-block arg t block-regexp))
23624 (defun org-forward-paragraph ()
23625 "Move forward to beginning of next paragraph or equivalent.
23627 The function moves point to the beginning of the next visible
23628 structural element, which can be a paragraph, a table, a list
23629 item, etc. It also provides some special moves for convenience:
23631 - On an affiliated keyword, jump to the beginning of the
23632 relative element.
23633 - On an item or a footnote definition, move to the second
23634 element inside, if any.
23635 - On a table or a property drawer, jump after it.
23636 - On a verse or source block, stop after blank lines."
23637 (interactive)
23638 (unless (eobp)
23639 (let* ((deactivate-mark nil)
23640 (element (org-element-at-point))
23641 (type (org-element-type element))
23642 (post-affiliated (org-element-property :post-affiliated element))
23643 (contents-begin (org-element-property :contents-begin element))
23644 (contents-end (org-element-property :contents-end element))
23645 (end (let ((end (org-element-property :end element)) (parent element))
23646 (while (and (setq parent (org-element-property :parent parent))
23647 (= (org-element-property :contents-end parent) end))
23648 (setq end (org-element-property :end parent)))
23649 end)))
23650 (cond ((not element)
23651 (skip-chars-forward " \r\t\n")
23652 (or (eobp) (beginning-of-line)))
23653 ;; On affiliated keywords, move to element's beginning.
23654 ((< (point) post-affiliated)
23655 (goto-char post-affiliated))
23656 ;; At a table row, move to the end of the table. Similarly,
23657 ;; at a node property, move to the end of the property
23658 ;; drawer.
23659 ((memq type '(node-property table-row))
23660 (goto-char (org-element-property
23661 :end (org-element-property :parent element))))
23662 ((memq type '(property-drawer table)) (goto-char end))
23663 ;; Consider blank lines as separators in verse and source
23664 ;; blocks to ease editing.
23665 ((memq type '(src-block verse-block))
23666 (when (eq type 'src-block)
23667 (setq contents-end
23668 (save-excursion (goto-char end)
23669 (skip-chars-backward " \r\t\n")
23670 (line-beginning-position))))
23671 (beginning-of-line)
23672 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23673 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23674 (goto-char end)
23675 (skip-chars-forward " \r\t\n")
23676 (if (= (point) contents-end) (goto-char end)
23677 (beginning-of-line))))
23678 ;; With no contents, just skip element.
23679 ((not contents-begin) (goto-char end))
23680 ;; If contents are invisible, skip the element altogether.
23681 ((org-invisible-p (line-end-position))
23682 (cl-case type
23683 (headline
23684 (org-with-limited-levels (outline-next-visible-heading 1)))
23685 ;; At a plain list, make sure we move to the next item
23686 ;; instead of skipping the whole list.
23687 (plain-list (forward-char)
23688 (org-forward-paragraph))
23689 (otherwise (goto-char end))))
23690 ((>= (point) contents-end) (goto-char end))
23691 ((>= (point) contents-begin)
23692 ;; This can only happen on paragraphs and plain lists.
23693 (cl-case type
23694 (paragraph (goto-char end))
23695 ;; At a plain list, try to move to second element in
23696 ;; first item, if possible.
23697 (plain-list (end-of-line)
23698 (org-forward-paragraph))))
23699 ;; When contents start on the middle of a line (e.g. in
23700 ;; items and footnote definitions), try to reach first
23701 ;; element starting after current line.
23702 ((> (line-end-position) contents-begin)
23703 (end-of-line)
23704 (org-forward-paragraph))
23705 (t (goto-char contents-begin))))))
23707 (defun org-backward-paragraph ()
23708 "Move backward to start of previous paragraph or equivalent.
23710 The function moves point to the beginning of the current
23711 structural element, which can be a paragraph, a table, a list
23712 item, etc., or to the beginning of the previous visible one if
23713 point is already there. It also provides some special moves for
23714 convenience:
23716 - On an affiliated keyword, jump to the first one.
23717 - On a table or a property drawer, move to its beginning.
23718 - On comment, example, export, src and verse blocks, stop
23719 before blank lines."
23720 (interactive)
23721 (unless (bobp)
23722 (let* ((deactivate-mark nil)
23723 (element (org-element-at-point))
23724 (type (org-element-type element))
23725 (contents-end (org-element-property :contents-end element))
23726 (post-affiliated (org-element-property :post-affiliated element))
23727 (begin (org-element-property :begin element))
23728 (special? ;blocks handled specially
23729 (memq type '(comment-block example-block export-block src-block
23730 verse-block)))
23731 (contents-begin
23732 (if special?
23733 ;; These types have no proper contents. Fake line
23734 ;; below the block opening line as contents beginning.
23735 (save-excursion (goto-char begin) (line-beginning-position 2))
23736 (org-element-property :contents-begin element))))
23737 (cond
23738 ((not element) (goto-char (point-min)))
23739 ((= (point) begin)
23740 (backward-char)
23741 (org-backward-paragraph))
23742 ((<= (point) post-affiliated) (goto-char begin))
23743 ;; Special behavior: on a table or a property drawer, move to
23744 ;; its beginning.
23745 ((memq type '(node-property table-row))
23746 (goto-char (org-element-property
23747 :post-affiliated (org-element-property :parent element))))
23748 (special?
23749 (if (<= (point) contents-begin) (goto-char post-affiliated)
23750 ;; Inside a verse block, see blank lines as paragraph
23751 ;; separators.
23752 (let ((origin (point)))
23753 (skip-chars-backward " \r\t\n" contents-begin)
23754 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23755 (skip-chars-forward " \r\t\n" origin)
23756 (if (= (point) origin) (goto-char contents-begin)
23757 (beginning-of-line))))))
23758 ((eq type 'paragraph) (goto-char contents-begin)
23759 ;; When at first paragraph in an item or a footnote definition,
23760 ;; move directly to beginning of line.
23761 (let ((parent-contents
23762 (org-element-property
23763 :contents-begin (org-element-property :parent element))))
23764 (when (and parent-contents (= parent-contents contents-begin))
23765 (beginning-of-line))))
23766 ;; At the end of a greater element, move to the beginning of
23767 ;; the last element within.
23768 ((and contents-end (>= (point) contents-end))
23769 (goto-char (1- contents-end))
23770 (org-backward-paragraph))
23771 (t (goto-char (or post-affiliated begin))))
23772 ;; Ensure we never leave point invisible.
23773 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23775 (defun org-forward-element ()
23776 "Move forward by one element.
23777 Move to the next element at the same level, when possible."
23778 (interactive)
23779 (cond ((eobp) (user-error "Cannot move further down"))
23780 ((org-with-limited-levels (org-at-heading-p))
23781 (let ((origin (point)))
23782 (goto-char (org-end-of-subtree nil t))
23783 (unless (org-with-limited-levels (org-at-heading-p))
23784 (goto-char origin)
23785 (user-error "Cannot move further down"))))
23787 (let* ((elem (org-element-at-point))
23788 (end (org-element-property :end elem))
23789 (parent (org-element-property :parent elem)))
23790 (cond ((and parent (= (org-element-property :contents-end parent) end))
23791 (goto-char (org-element-property :end parent)))
23792 ((integer-or-marker-p end) (goto-char end))
23793 (t (message "No element at point")))))))
23795 (defun org-backward-element ()
23796 "Move backward by one element.
23797 Move to the previous element at the same level, when possible."
23798 (interactive)
23799 (cond ((bobp) (user-error "Cannot move further up"))
23800 ((org-with-limited-levels (org-at-heading-p))
23801 ;; At a headline, move to the previous one, if any, or stay
23802 ;; here.
23803 (let ((origin (point)))
23804 (org-with-limited-levels (org-backward-heading-same-level 1))
23805 ;; When current headline has no sibling above, move to its
23806 ;; parent.
23807 (when (= (point) origin)
23808 (or (org-with-limited-levels (org-up-heading-safe))
23809 (progn (goto-char origin)
23810 (user-error "Cannot move further up"))))))
23812 (let* ((elem (org-element-at-point))
23813 (beg (org-element-property :begin elem)))
23814 (cond
23815 ;; Move to beginning of current element if point isn't
23816 ;; there already.
23817 ((null beg) (message "No element at point"))
23818 ((/= (point) beg) (goto-char beg))
23819 (t (goto-char beg)
23820 (skip-chars-backward " \r\t\n")
23821 (unless (bobp)
23822 (let ((prev (org-element-at-point)))
23823 (goto-char (org-element-property :begin prev))
23824 (while (and (setq prev (org-element-property :parent prev))
23825 (<= (org-element-property :end prev) beg))
23826 (goto-char (org-element-property :begin prev)))))))))))
23828 (defun org-up-element ()
23829 "Move to upper element."
23830 (interactive)
23831 (if (org-with-limited-levels (org-at-heading-p))
23832 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23833 (let* ((elem (org-element-at-point))
23834 (parent (org-element-property :parent elem)))
23835 (if parent (goto-char (org-element-property :begin parent))
23836 (if (org-with-limited-levels (org-before-first-heading-p))
23837 (user-error "No surrounding element")
23838 (org-with-limited-levels (org-back-to-heading)))))))
23840 (defun org-down-element ()
23841 "Move to inner element."
23842 (interactive)
23843 (let ((element (org-element-at-point)))
23844 (cond
23845 ((memq (org-element-type element) '(plain-list table))
23846 (goto-char (org-element-property :contents-begin element))
23847 (forward-char))
23848 ((memq (org-element-type element) org-element-greater-elements)
23849 ;; If contents are hidden, first disclose them.
23850 (when (org-invisible-p (line-end-position)) (org-cycle))
23851 (goto-char (or (org-element-property :contents-begin element)
23852 (user-error "No content for this element"))))
23853 (t (user-error "No inner element")))))
23855 (defun org-drag-element-backward ()
23856 "Move backward element at point."
23857 (interactive)
23858 (let ((elem (or (org-element-at-point)
23859 (user-error "No element at point"))))
23860 (if (eq (org-element-type elem) 'headline)
23861 ;; Preserve point when moving a whole tree, even if point was
23862 ;; on blank lines below the headline.
23863 (let ((offset (skip-chars-backward " \t\n")))
23864 (unwind-protect (org-move-subtree-up)
23865 (forward-char (- offset))))
23866 (let ((prev-elem
23867 (save-excursion
23868 (goto-char (org-element-property :begin elem))
23869 (skip-chars-backward " \r\t\n")
23870 (unless (bobp)
23871 (let* ((beg (org-element-property :begin elem))
23872 (prev (org-element-at-point))
23873 (up prev))
23874 (while (and (setq up (org-element-property :parent up))
23875 (<= (org-element-property :end up) beg))
23876 (setq prev up))
23877 prev)))))
23878 ;; Error out if no previous element or previous element is
23879 ;; a parent of the current one.
23880 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23881 (user-error "Cannot drag element backward")
23882 (let ((pos (point)))
23883 (org-element-swap-A-B prev-elem elem)
23884 (goto-char (+ (org-element-property :begin prev-elem)
23885 (- pos (org-element-property :begin elem))))))))))
23887 (defun org-drag-element-forward ()
23888 "Move forward element at point."
23889 (interactive)
23890 (let* ((pos (point))
23891 (elem (or (org-element-at-point)
23892 (user-error "No element at point"))))
23893 (when (= (point-max) (org-element-property :end elem))
23894 (user-error "Cannot drag element forward"))
23895 (goto-char (org-element-property :end elem))
23896 (let ((next-elem (org-element-at-point)))
23897 (when (or (org-element-nested-p elem next-elem)
23898 (and (eq (org-element-type next-elem) 'headline)
23899 (not (eq (org-element-type elem) 'headline))))
23900 (goto-char pos)
23901 (user-error "Cannot drag element forward"))
23902 ;; Compute new position of point: it's shifted by NEXT-ELEM
23903 ;; body's length (without final blanks) and by the length of
23904 ;; blanks between ELEM and NEXT-ELEM.
23905 (let ((size-next (- (save-excursion
23906 (goto-char (org-element-property :end next-elem))
23907 (skip-chars-backward " \r\t\n")
23908 (forward-line)
23909 ;; Small correction if buffer doesn't end
23910 ;; with a newline character.
23911 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23912 (org-element-property :begin next-elem)))
23913 (size-blank (- (org-element-property :end elem)
23914 (save-excursion
23915 (goto-char (org-element-property :end elem))
23916 (skip-chars-backward " \r\t\n")
23917 (forward-line)
23918 (point)))))
23919 (org-element-swap-A-B elem next-elem)
23920 (goto-char (+ pos size-next size-blank))))))
23922 (defun org-drag-line-forward (arg)
23923 "Drag the line at point ARG lines forward."
23924 (interactive "p")
23925 (dotimes (_ (abs arg))
23926 (let ((c (current-column)))
23927 (if (< 0 arg)
23928 (progn
23929 (beginning-of-line 2)
23930 (transpose-lines 1)
23931 (beginning-of-line 0))
23932 (transpose-lines 1)
23933 (beginning-of-line -1))
23934 (org-move-to-column c))))
23936 (defun org-drag-line-backward (arg)
23937 "Drag the line at point ARG lines backward."
23938 (interactive "p")
23939 (org-drag-line-forward (- arg)))
23941 (defun org-mark-element ()
23942 "Put point at beginning of this element, mark at end.
23944 Interactively, if this command is repeated or (in Transient Mark
23945 mode) if the mark is active, it marks the next element after the
23946 ones already marked."
23947 (interactive)
23948 (let (deactivate-mark)
23949 (if (and (called-interactively-p 'any)
23950 (or (and (eq last-command this-command) (mark t))
23951 (and transient-mark-mode mark-active)))
23952 (set-mark
23953 (save-excursion
23954 (goto-char (mark))
23955 (goto-char (org-element-property :end (org-element-at-point)))))
23956 (let ((element (org-element-at-point)))
23957 (end-of-line)
23958 (push-mark (org-element-property :end element) t t)
23959 (goto-char (org-element-property :begin element))))))
23961 (defun org-narrow-to-element ()
23962 "Narrow buffer to current element."
23963 (interactive)
23964 (let ((elem (org-element-at-point)))
23965 (cond
23966 ((eq (car elem) 'headline)
23967 (narrow-to-region
23968 (org-element-property :begin elem)
23969 (org-element-property :end elem)))
23970 ((memq (car elem) org-element-greater-elements)
23971 (narrow-to-region
23972 (org-element-property :contents-begin elem)
23973 (org-element-property :contents-end elem)))
23975 (narrow-to-region
23976 (org-element-property :begin elem)
23977 (org-element-property :end elem))))))
23979 (defun org-transpose-element ()
23980 "Transpose current and previous elements, keeping blank lines between.
23981 Point is moved after both elements."
23982 (interactive)
23983 (org-skip-whitespace)
23984 (let ((end (org-element-property :end (org-element-at-point))))
23985 (org-drag-element-backward)
23986 (goto-char end)))
23988 (defun org-unindent-buffer ()
23989 "Un-indent the visible part of the buffer.
23990 Relative indentation (between items, inside blocks, etc.) isn't
23991 modified."
23992 (interactive)
23993 (unless (eq major-mode 'org-mode)
23994 (user-error "Cannot un-indent a buffer not in Org mode"))
23995 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23996 (unindent-tree
23997 (lambda (contents)
23998 (dolist (element (reverse contents))
23999 (if (memq (org-element-type element) '(headline section))
24000 (funcall unindent-tree (org-element-contents element))
24001 (save-excursion
24002 (save-restriction
24003 (narrow-to-region
24004 (org-element-property :begin element)
24005 (org-element-property :end element))
24006 (org-do-remove-indentation))))))))
24007 (funcall unindent-tree (org-element-contents parse-tree))))
24009 (defun org-show-children (&optional level)
24010 "Show all direct subheadings of this heading.
24011 Prefix arg LEVEL is how many levels below the current level
24012 should be shown. Default is enough to cause the following
24013 heading to appear."
24014 (interactive "p")
24015 ;; If `orgstruct-mode' is active, use the slower version.
24016 (if orgstruct-mode (call-interactively #'outline-show-children)
24017 (save-excursion
24018 (org-back-to-heading t)
24019 (let* ((current-level (funcall outline-level))
24020 (max-level (org-get-valid-level
24021 current-level
24022 (if level (prefix-numeric-value level) 1)))
24023 (end (save-excursion (org-end-of-subtree t t)))
24024 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24025 (past-first-child nil)
24026 ;; Make sure to skip inlinetasks.
24027 (re (format regexp-fmt
24028 current-level
24029 (cond
24030 ((not (featurep 'org-inlinetask)) "")
24031 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24033 (t (1- org-inlinetask-min-level))))))
24034 ;; Display parent heading.
24035 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24036 (forward-line)
24037 ;; Display children. First child may be deeper than expected
24038 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24039 ;; MAX-LEVEL accordingly.
24040 (while (re-search-forward re end t)
24041 (unless past-first-child
24042 (setq re (format regexp-fmt
24043 current-level
24044 (max (funcall outline-level) max-level)))
24045 (setq past-first-child t))
24046 (outline-flag-region
24047 (line-end-position 0) (line-end-position) nil))))))
24049 (defun org-show-subtree ()
24050 "Show everything after this heading at deeper levels."
24051 (interactive)
24052 (outline-flag-region
24053 (point)
24054 (save-excursion
24055 (org-end-of-subtree t t))
24056 nil))
24058 (defun org-show-entry ()
24059 "Show the body directly following this heading.
24060 Show the heading too, if it is currently invisible."
24061 (interactive)
24062 (save-excursion
24063 (ignore-errors
24064 (org-back-to-heading t)
24065 (outline-flag-region
24066 (max (point-min) (1- (point)))
24067 (save-excursion
24068 (if (re-search-forward
24069 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24070 (match-beginning 1)
24071 (point-max)))
24072 nil)
24073 (org-cycle-hide-drawers 'children))))
24075 (defun org-make-options-regexp (kwds &optional extra)
24076 "Make a regular expression for keyword lines.
24077 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24078 when non-nil, is a regexp matching keywords names."
24079 (concat "^[ \t]*#\\+\\("
24080 (regexp-opt kwds)
24081 (and extra (concat (and kwds "\\|") extra))
24082 "\\):[ \t]*\\(.*\\)"))
24084 ;;;; Finish up
24086 (provide 'org)
24088 (run-hooks 'org-load-hook)
24090 ;;; org.el ends here