Change `org-get-tags' specifications
[org-mode/org-tableheadings.git] / lisp / org.el
blob77c6a1a476b9cfecb7bdcf261cf12cbb3c46bb62
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: https://orgmode.org
10 ;; Version: 9.1.10
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
46 ;; webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; https://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; https://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (defvar org-inlinetask-min-level)
72 ;;;; Require other packages
74 (require 'cl-lib)
76 (eval-when-compile (require 'gnus-sum))
78 (require 'calendar)
79 (require 'find-func)
80 (require 'format-spec)
82 (or (eq this-command 'eval-buffer)
83 (condition-case nil
84 (load (concat (file-name-directory load-file-name)
85 "org-loaddefs.el")
86 nil t t t)
87 (error
88 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
89 (sit-for 3)
90 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
91 (sit-for 3))))
93 (require 'org-macs)
94 (require 'org-compat)
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 (defvar org-outline-regexp "\\*+ "
99 "Regexp to match Org headlines.")
101 (defvar org-outline-regexp-bol "^\\*+ "
102 "Regexp to match Org headlines.
103 This is similar to `org-outline-regexp' but additionally makes
104 sure that we are at the beginning of the line.")
106 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
107 "Matches a headline, putting stars and text into groups.
108 Stars are put in group 1 and the trimmed body in group 2.")
110 (declare-function calendar-check-holidays "holidays" (date))
111 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
112 (declare-function cdlatex-math-symbol "ext:cdlatex")
113 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocking-buffer "org-clock" ())
130 (declare-function org-clocktable-shift "org-clock" (dir n))
131 (declare-function
132 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-link-parser "org-element" ())
142 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
143 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
144 (declare-function org-element-property "org-element" (property element))
145 (declare-function org-element-put-property "org-element" (element property value))
146 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
147 (declare-function org-element-type "org-element" (element))
148 (declare-function org-element-update-syntax "org-element" ())
149 (declare-function org-id-find-id-file "org-id" (id))
150 (declare-function org-id-get-create "org-id" (&optional force))
151 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
152 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
153 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
154 (declare-function org-plot/gnuplot "org-plot" (&optional params))
155 (declare-function org-table-align "org-table" ())
156 (declare-function org-table-begin "org-table" (&optional table-type))
157 (declare-function org-table-beginning-of-field "org-table" (&optional n))
158 (declare-function org-table-blank-field "org-table" ())
159 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
160 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
161 (declare-function org-table-cut-region "org-table" (beg end))
162 (declare-function org-table-edit-field "org-table" (arg))
163 (declare-function org-table-end "org-table" (&optional table-type))
164 (declare-function org-table-end-of-field "org-table" (&optional n))
165 (declare-function org-table-insert-row "org-table" (&optional arg))
166 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
167 (declare-function org-table-maybe-eval-formula "org-table" ())
168 (declare-function org-table-maybe-recalculate-line "org-table" ())
169 (declare-function org-table-next-row "org-table" ())
170 (declare-function org-table-paste-rectangle "org-table" ())
171 (declare-function org-table-recalculate "org-table" (&optional all noalign))
172 (declare-function
173 org-table-sort-lines "org-table"
174 (&optional with-case sorting-type getkey-func compare-func interactive?))
175 (declare-function org-table-shrink "org-table" (&optional begin end))
176 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp)
186 (defvar org-element-paragraph-separate)
188 ;; load languages based on value of `org-babel-load-languages'
189 (defvar org-babel-load-languages)
191 ;;;###autoload
192 (defun org-babel-do-load-languages (sym value)
193 "Load the languages defined in `org-babel-load-languages'."
194 (set-default sym value)
195 (dolist (pair org-babel-load-languages)
196 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
197 (if active
198 (require (intern (concat "ob-" lang)))
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-execute:" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-expand-body:" lang)))))))
204 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
205 ;;;###autoload
206 (defun org-babel-load-file (file &optional compile)
207 "Load Emacs Lisp source code blocks in the Org FILE.
208 This function exports the source code using `org-babel-tangle'
209 and then loads the resulting file using `load-file'. With prefix
210 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
211 file to byte-code before it is loaded."
212 (interactive "fFile to load: \nP")
213 (let* ((age (lambda (file)
214 (float-time
215 (time-subtract (current-time)
216 (nth 5 (or (file-attributes (file-truename file))
217 (file-attributes file)))))))
218 (base-name (file-name-sans-extension file))
219 (exported-file (concat base-name ".el")))
220 ;; tangle if the Org file is newer than the elisp file
221 (unless (and (file-exists-p exported-file)
222 (> (funcall age file) (funcall age exported-file)))
223 ;; Tangle-file traversal returns reversed list of tangled files
224 ;; and we want to evaluate the first target.
225 (setq exported-file
226 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
227 (message "%s %s"
228 (if compile
229 (progn (byte-compile-file exported-file 'load)
230 "Compiled and loaded")
231 (progn (load-file exported-file) "Loaded"))
232 exported-file)))
234 (defcustom org-babel-load-languages '((emacs-lisp . t))
235 "Languages which can be evaluated in Org buffers.
236 This list can be used to load support for any of the languages
237 below, note that each language will depend on a different set of
238 system executables and/or Emacs modes. When a language is
239 \"loaded\", then code blocks in that language can be evaluated
240 with `org-babel-execute-src-block' bound by default to C-c
241 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
242 be set to remove code block evaluation from the C-c C-c
243 keybinding. By default only Emacs Lisp (which has no
244 requirements) is loaded."
245 :group 'org-babel
246 :set 'org-babel-do-load-languages
247 :version "24.1"
248 :type '(alist :tag "Babel Languages"
249 :key-type
250 (choice
251 (const :tag "Awk" awk)
252 (const :tag "C" C)
253 (const :tag "R" R)
254 (const :tag "Asymptote" asymptote)
255 (const :tag "Calc" calc)
256 (const :tag "Clojure" clojure)
257 (const :tag "CSS" css)
258 (const :tag "Ditaa" ditaa)
259 (const :tag "Dot" dot)
260 (const :tag "Ebnf2ps" ebnf2ps)
261 (const :tag "Emacs Lisp" emacs-lisp)
262 (const :tag "Forth" forth)
263 (const :tag "Fortran" fortran)
264 (const :tag "Gnuplot" gnuplot)
265 (const :tag "Haskell" haskell)
266 (const :tag "hledger" hledger)
267 (const :tag "IO" io)
268 (const :tag "J" J)
269 (const :tag "Java" java)
270 (const :tag "Javascript" js)
271 (const :tag "LaTeX" latex)
272 (const :tag "Ledger" ledger)
273 (const :tag "Lilypond" lilypond)
274 (const :tag "Lisp" lisp)
275 (const :tag "Makefile" makefile)
276 (const :tag "Maxima" maxima)
277 (const :tag "Matlab" matlab)
278 (const :tag "Mscgen" mscgen)
279 (const :tag "Ocaml" ocaml)
280 (const :tag "Octave" octave)
281 (const :tag "Org" org)
282 (const :tag "Perl" perl)
283 (const :tag "Pico Lisp" picolisp)
284 (const :tag "PlantUML" plantuml)
285 (const :tag "Python" python)
286 (const :tag "Ruby" ruby)
287 (const :tag "Sass" sass)
288 (const :tag "Scala" scala)
289 (const :tag "Scheme" scheme)
290 (const :tag "Screen" screen)
291 (const :tag "Shell Script" shell)
292 (const :tag "Shen" shen)
293 (const :tag "Sql" sql)
294 (const :tag "Sqlite" sqlite)
295 (const :tag "Stan" stan)
296 (const :tag "Vala" vala))
297 :value-type (boolean :tag "Activate" :value t)))
299 ;;;; Customization variables
300 (defcustom org-clone-delete-id nil
301 "Remove ID property of clones of a subtree.
302 When non-nil, clones of a subtree don't inherit the ID property.
303 Otherwise they inherit the ID property with a new unique
304 identifier."
305 :type 'boolean
306 :version "24.1"
307 :group 'org-id)
309 ;;; Version
310 (org-check-version)
312 ;;;###autoload
313 (defun org-version (&optional here full message)
314 "Show the Org version.
315 Interactively, or when MESSAGE is non-nil, show it in echo area.
316 With prefix argument, or when HERE is non-nil, insert it at point.
317 In non-interactive uses, a reduced version string is output unless
318 FULL is given."
319 (interactive (list current-prefix-arg t (not current-prefix-arg)))
320 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
321 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
322 (load-suffixes (list ".el"))
323 (org-install-dir
324 (ignore-errors (org-find-library-dir "org-loaddefs"))))
325 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
326 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
327 (let* ((load-suffixes save-load-suffixes)
328 (release (org-release))
329 (git-version (org-git-version))
330 (version (format "Org mode version %s (%s @ %s)"
331 release
332 git-version
333 (if org-install-dir
334 (if (string= org-dir org-install-dir)
335 org-install-dir
336 (concat "mixed installation! "
337 org-install-dir
338 " and "
339 org-dir))
340 "org-loaddefs.el can not be found!")))
341 (version1 (if full version release)))
342 (when here (insert version1))
343 (when message (message "%s" version1))
344 version1)))
346 (defconst org-version (org-version))
349 ;;; Syntax Constants
351 ;;;; Block
353 (defconst org-block-regexp
354 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
355 "Regular expression for hiding blocks.")
357 (defconst org-dblock-start-re
358 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
359 "Matches the start line of a dynamic block, with parameters.")
361 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
362 "Matches the end of a dynamic block.")
364 ;;;; Clock and Planning
366 (defconst org-clock-string "CLOCK:"
367 "String used as prefix for timestamps clocking work hours on an item.")
369 (defvar org-closed-string "CLOSED:"
370 "String used as the prefix for timestamps logging closing a TODO entry.")
372 (defvar org-deadline-string "DEADLINE:"
373 "String to mark deadline entries.
374 \\<org-mode-map>
375 A deadline is this string, followed by a time stamp. It must be
376 a word, terminated by a colon. You can insert a schedule keyword
377 and a timestamp with `\\[org-deadline]'.")
379 (defvar org-scheduled-string "SCHEDULED:"
380 "String to mark scheduled TODO entries.
381 \\<org-mode-map>
382 A schedule is this string, followed by a time stamp. It must be
383 a word, terminated by a colon. You can insert a schedule keyword
384 and a timestamp with `\\[org-schedule]'.")
386 (defconst org-ds-keyword-length
387 (+ 2
388 (apply #'max
389 (mapcar #'length
390 (list org-deadline-string org-scheduled-string
391 org-clock-string org-closed-string))))
392 "Maximum length of the DEADLINE and SCHEDULED keywords.")
394 (defconst org-planning-line-re
395 (concat "^[ \t]*"
396 (regexp-opt
397 (list org-closed-string org-deadline-string org-scheduled-string)
399 "Matches a line with planning info.
400 Matched keyword is in group 1.")
402 (defconst org-clock-line-re
403 (concat "^[ \t]*" org-clock-string)
404 "Matches a line with clock info.")
406 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
407 "Matches the DEADLINE keyword.")
409 (defconst org-deadline-time-regexp
410 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
411 "Matches the DEADLINE keyword together with a time stamp.")
413 (defconst org-deadline-time-hour-regexp
414 (concat "\\<" org-deadline-string
415 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
416 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
418 (defconst org-deadline-line-regexp
419 (concat "\\<\\(" org-deadline-string "\\).*")
420 "Matches the DEADLINE keyword and the rest of the line.")
422 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
423 "Matches the SCHEDULED keyword.")
425 (defconst org-scheduled-time-regexp
426 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
427 "Matches the SCHEDULED keyword together with a time stamp.")
429 (defconst org-scheduled-time-hour-regexp
430 (concat "\\<" org-scheduled-string
431 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
432 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
434 (defconst org-closed-time-regexp
435 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
436 "Matches the CLOSED keyword together with a time stamp.")
438 (defconst org-keyword-time-regexp
439 (concat "\\<"
440 (regexp-opt
441 (list org-scheduled-string org-deadline-string org-closed-string
442 org-clock-string)
444 " *[[<]\\([^]>]+\\)[]>]")
445 "Matches any of the 4 keywords, together with the time stamp.")
447 (defconst org-keyword-time-not-clock-regexp
448 (concat
449 "\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string) t)
452 " *[[<]\\([^]>]+\\)[]>]")
453 "Matches any of the 3 keywords, together with the time stamp.")
455 (defconst org-maybe-keyword-time-regexp
456 (concat "\\(\\<"
457 (regexp-opt
458 (list org-scheduled-string org-deadline-string org-closed-string
459 org-clock-string)
461 "\\)?"
462 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
463 "\\|"
464 "<%%([^\r\n>]*>\\)")
465 "Matches a timestamp, possibly preceded by a keyword.")
467 (defconst org-all-time-keywords
468 (mapcar (lambda (w) (substring w 0 -1))
469 (list org-scheduled-string org-deadline-string
470 org-clock-string org-closed-string))
471 "List of time keywords.")
473 ;;;; Drawer
475 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
476 "Matches first or last line of a hidden block.
477 Group 1 contains drawer's name or \"END\".")
479 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
480 "Regular expression matching the first line of a property drawer.")
482 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
483 "Regular expression matching the last line of a property drawer.")
485 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
486 "Regular expression matching the first line of a clock drawer.")
488 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
489 "Regular expression matching the last line of a clock drawer.")
491 (defconst org-property-drawer-re
492 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
493 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
494 "[ \t]*:END:[ \t]*$")
495 "Matches an entire property drawer.")
497 (defconst org-clock-drawer-re
498 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
499 org-clock-drawer-end-re "\\)\n?")
500 "Matches an entire clock drawer.")
502 ;;;; Headline
504 (defconst org-heading-keyword-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline with some keyword.
507 This regexp will match the headline of any node which has the
508 exact keyword that is put into the format. The keyword isn't in
509 any group by default, but the stars and the body are.")
511 (defconst org-heading-keyword-maybe-regexp-format
512 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
513 "Printf format for a regexp matching a headline, possibly with some keyword.
514 This regexp can match any headline with the specified keyword, or
515 without a keyword. The keyword isn't in any group by default,
516 but the stars and the body are.")
518 (defconst org-archive-tag "ARCHIVE"
519 "The tag that marks a subtree as archived.
520 An archived subtree does not open during visibility cycling, and does
521 not contribute to the agenda listings.")
523 (defconst org-tag-line-re
524 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
525 "Regexp matching tags in a headline.
526 Tags are stored in match group 1. Match group 2 stores the tags
527 without the enclosing colons.")
529 (eval-and-compile
530 (defconst org-comment-string "COMMENT"
531 "Entries starting with this keyword will never be exported.
532 \\<org-mode-map>
533 An entry can be toggled between COMMENT and normal with
534 `\\[org-toggle-comment]'."))
537 ;;;; LaTeX Environments and Fragments
539 (defconst org-latex-regexps
540 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
541 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
542 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
543 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
544 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
545 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
546 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
547 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
548 "Regular expressions for matching embedded LaTeX.")
550 ;;;; Node Property
552 (defconst org-effort-property "Effort"
553 "The property that is being used to keep track of effort estimates.
554 Effort estimates given in this property need to have the format H:MM.")
556 ;;;; Table
558 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
559 "Detect an org-type or table-type table.")
561 (defconst org-table-line-regexp "^[ \t]*|"
562 "Detect an org-type table line.")
564 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
565 "Detect an org-type table line.")
567 (defconst org-table-hline-regexp "^[ \t]*|-"
568 "Detect an org-type table hline.")
570 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
571 "Detect a table-type table hline.")
573 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
574 "Detect the first line outside a table when searching from within it.
575 This works for both table types.")
577 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
578 "Detect a #+TBLFM line.")
580 ;;;; Timestamp
582 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
583 "Regular expression for fast time stamp matching.")
585 (defconst org-ts-regexp-inactive
586 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
587 "Regular expression for fast inactive time stamp matching.")
589 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
590 "Regular expression for fast time stamp matching.")
592 (defconst org-ts-regexp0
593 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.
595 This one does not require the space after the date, so it can be used
596 on a string that terminates immediately after the date.")
598 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
599 "Regular expression matching time strings for analysis.")
601 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
602 "Regular expression matching time stamps, with groups.")
604 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
605 "Regular expression matching time stamps (also [..]), with groups.")
607 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
608 "Regular expression matching a time stamp range.")
610 (defconst org-tr-regexp-both
611 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
612 "Regular expression matching a time stamp range.")
614 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
615 org-ts-regexp "\\)?")
616 "Regular expression matching a time stamp or time stamp range.")
618 (defconst org-tsr-regexp-both
619 (concat org-ts-regexp-both "\\(--?-?"
620 org-ts-regexp-both "\\)?")
621 "Regular expression matching a time stamp or time stamp range.
622 The time stamps may be either active or inactive.")
624 (defconst org-repeat-re
625 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
626 "Regular expression for specifying repeated events.
627 After a match, group 1 contains the repeat expression.")
629 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
630 "Formats for `format-time-string' which are used for time stamps.")
633 ;;; The custom variables
635 (defgroup org nil
636 "Outline-based notes management and organizer."
637 :tag "Org"
638 :group 'outlines
639 :group 'calendar)
641 (defcustom org-mode-hook nil
642 "Mode hook for Org mode, run after the mode was turned on."
643 :group 'org
644 :type 'hook)
646 (defcustom org-load-hook nil
647 "Hook that is run after org.el has been loaded."
648 :group 'org
649 :type 'hook)
651 (defcustom org-log-buffer-setup-hook nil
652 "Hook that is run after an Org log buffer is created."
653 :group 'org
654 :version "24.1"
655 :type 'hook)
657 (defvar org-modules) ; defined below
658 (defvar org-modules-loaded nil
659 "Have the modules been loaded already?")
661 (defun org-load-modules-maybe (&optional force)
662 "Load all extensions listed in `org-modules'."
663 (when (or force (not org-modules-loaded))
664 (dolist (ext org-modules)
665 (condition-case nil (require ext)
666 (error (message "Problems while trying to load feature `%s'" ext))))
667 (setq org-modules-loaded t)))
669 (defun org-set-modules (var value)
670 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
671 (set var value)
672 (when (featurep 'org)
673 (org-load-modules-maybe 'force)
674 (org-element-cache-reset 'all)))
676 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
677 "Modules that should always be loaded together with org.el.
679 If a description starts with <C>, the file is not part of Emacs
680 and loading it will require that you have downloaded and properly
681 installed the Org mode distribution.
683 You can also use this system to load external packages (i.e. neither Org
684 core modules, nor modules from the CONTRIB directory). Just add symbols
685 to the end of the list. If the package is called org-xyz.el, then you need
686 to add the symbol `xyz', and the package must have a call to:
688 (provide \\='org-xyz)
690 For export specific modules, see also `org-export-backends'."
691 :group 'org
692 :set 'org-set-modules
693 :version "24.4"
694 :package-version '(Org . "8.0")
695 :type
696 '(set :greedy t
697 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
698 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
699 (const :tag " crypt: Encryption of subtrees" org-crypt)
700 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
701 (const :tag " docview: Links to doc-view buffers" org-docview)
702 (const :tag " eww: Store link to url of eww" org-eww)
703 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
704 (const :tag " habit: Track your consistency with habits" org-habit)
705 (const :tag " id: Global IDs for identifying entries" org-id)
706 (const :tag " info: Links to Info nodes" org-info)
707 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
708 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
709 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
710 (const :tag " mouse: Additional mouse support" org-mouse)
711 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
712 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
713 (const :tag " tempo: Fast completion for structures" org-tempo)
714 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
716 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
717 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
718 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
719 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
720 (const :tag "C collector: Collect properties into tables" org-collector)
721 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
722 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
723 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
724 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
725 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
726 (const :tag "C eval: Include command output as text" org-eval)
727 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
728 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
729 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
730 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
731 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
732 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
733 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
734 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
735 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
736 (const :tag "C man: Support for links to manpages in Org mode" org-man)
737 (const :tag "C mew: Links to Mew folders/messages" org-mew)
738 (const :tag "C mtags: Support for muse-like tags" org-mtags)
739 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
740 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
741 (const :tag "C registry: A registry for Org links" org-registry)
742 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
743 (const :tag "C secretary: Team management with Org" org-secretary)
744 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
745 (const :tag "C toc: Table of contents for Org buffer" org-toc)
746 (const :tag "C track: Keep up with Org mode development" org-track)
747 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
748 (const :tag "C vm: Links to VM folders/messages" org-vm)
749 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
750 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
751 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
753 (defvar org-export-registered-backends) ; From ox.el.
754 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
755 (declare-function org-export-backend-name "ox" (backend) t)
756 (defcustom org-export-backends '(ascii html icalendar latex odt)
757 "List of export back-ends that should be always available.
759 If a description starts with <C>, the file is not part of Emacs
760 and loading it will require that you have downloaded and properly
761 installed the Org mode distribution.
763 Unlike to `org-modules', libraries in this list will not be
764 loaded along with Org, but only once the export framework is
765 needed.
767 This variable needs to be set before org.el is loaded. If you
768 need to make a change while Emacs is running, use the customize
769 interface or run the following code, where VAL stands for the new
770 value of the variable, after updating it:
772 (progn
773 (setq org-export-registered-backends
774 (cl-remove-if-not
775 (lambda (backend)
776 (let ((name (org-export-backend-name backend)))
777 (or (memq name val)
778 (catch \\='parentp
779 (dolist (b val)
780 (and (org-export-derived-backend-p b name)
781 (throw \\='parentp t)))))))
782 org-export-registered-backends))
783 (let ((new-list (mapcar #\\='org-export-backend-name
784 org-export-registered-backends)))
785 (dolist (backend val)
786 (cond
787 ((not (load (format \"ox-%s\" backend) t t))
788 (message \"Problems while trying to load export back-end \\=`%s\\='\"
789 backend))
790 ((not (memq backend new-list)) (push backend new-list))))
791 (set-default \\='org-export-backends new-list)))
793 Adding a back-end to this list will also pull the back-end it
794 depends on, if any."
795 :group 'org
796 :group 'org-export
797 :version "26.1"
798 :package-version '(Org . "9.0")
799 :initialize 'custom-initialize-set
800 :set (lambda (var val)
801 (if (not (featurep 'ox)) (set-default var val)
802 ;; Any back-end not required anymore (not present in VAL and not
803 ;; a parent of any back-end in the new value) is removed from the
804 ;; list of registered back-ends.
805 (setq org-export-registered-backends
806 (cl-remove-if-not
807 (lambda (backend)
808 (let ((name (org-export-backend-name backend)))
809 (or (memq name val)
810 (catch 'parentp
811 (dolist (b val)
812 (and (org-export-derived-backend-p b name)
813 (throw 'parentp t)))))))
814 org-export-registered-backends))
815 ;; Now build NEW-LIST of both new back-ends and required
816 ;; parents.
817 (let ((new-list (mapcar #'org-export-backend-name
818 org-export-registered-backends)))
819 (dolist (backend val)
820 (cond
821 ((not (load (format "ox-%s" backend) t t))
822 (message "Problems while trying to load export back-end `%s'"
823 backend))
824 ((not (memq backend new-list)) (push backend new-list))))
825 ;; Set VAR to that list with fixed dependencies.
826 (set-default var new-list))))
827 :type '(set :greedy t
828 (const :tag " ascii Export buffer to ASCII format" ascii)
829 (const :tag " beamer Export buffer to Beamer presentation" beamer)
830 (const :tag " html Export buffer to HTML format" html)
831 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
832 (const :tag " latex Export buffer to LaTeX format" latex)
833 (const :tag " man Export buffer to MAN format" man)
834 (const :tag " md Export buffer to Markdown format" md)
835 (const :tag " odt Export buffer to ODT format" odt)
836 (const :tag " org Export buffer to Org format" org)
837 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
838 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
839 (const :tag "C deck Export buffer to deck.js presentations" deck)
840 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
841 (const :tag "C groff Export buffer to Groff format" groff)
842 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
843 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
844 (const :tag "C s5 Export buffer to s5 presentations" s5)
845 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
847 (eval-after-load 'ox
848 '(dolist (backend org-export-backends)
849 (condition-case nil (require (intern (format "ox-%s" backend)))
850 (error (message "Problems while trying to load export back-end `%s'"
851 backend)))))
853 (defcustom org-support-shift-select nil
854 "Non-nil means make shift-cursor commands select text when possible.
855 \\<org-mode-map>\
857 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
858 start selecting a region, or enlarge regions started in this way.
859 In Org mode, in special contexts, these same keys are used for
860 other purposes, important enough to compete with shift selection.
861 Org tries to balance these needs by supporting `shift-select-mode'
862 outside these special contexts, under control of this variable.
864 The default of this variable is nil, to avoid confusing behavior. Shifted
865 cursor keys will then execute Org commands in the following contexts:
866 - on a headline, changing TODO state (left/right) and priority (up/down)
867 - on a time stamp, changing the time
868 - in a plain list item, changing the bullet type
869 - in a property definition line, switching between allowed values
870 - in the BEGIN line of a clock table (changing the time block).
871 Outside these contexts, the commands will throw an error.
873 When this variable is t and the cursor is not in a special
874 context, Org mode will support shift-selection for making and
875 enlarging regions. To make this more effective, the bullet
876 cycling will no longer happen anywhere in an item line, but only
877 if the cursor is exactly on the bullet.
879 If you set this variable to the symbol `always', then the keys
880 will not be special in headlines, property lines, and item lines,
881 to make shift selection work there as well. If this is what you
882 want, you can use the following alternative commands:
883 `\\[org-todo]' and `\\[org-priority]' \
884 to change TODO state and priority,
885 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
886 can be used to switch TODO sets,
887 `\\[org-ctrl-c-minus]' to cycle item bullet types,
888 and properties can be edited by hand or in column view.
890 However, when the cursor is on a timestamp, shift-cursor commands
891 will still edit the time stamp - this is just too good to give up."
892 :group 'org
893 :type '(choice
894 (const :tag "Never" nil)
895 (const :tag "When outside special context" t)
896 (const :tag "Everywhere except timestamps" always)))
898 (defcustom org-loop-over-headlines-in-active-region nil
899 "Shall some commands act upon headlines in the active region?
901 When set to t, some commands will be performed in all headlines
902 within the active region.
904 When set to `start-level', some commands will be performed in all
905 headlines within the active region, provided that these headlines
906 are of the same level than the first one.
908 When set to a string, those commands will be performed on the
909 matching headlines within the active region. Such string must be
910 a tags/property/todo match as it is used in the agenda tags view.
912 The list of commands is: `org-schedule', `org-deadline',
913 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
914 `org-archive-to-archive-sibling'. The archiving commands skip
915 already archived entries."
916 :type '(choice (const :tag "Don't loop" nil)
917 (const :tag "All headlines in active region" t)
918 (const :tag "In active region, headlines at the same level than the first one" start-level)
919 (string :tag "Tags/Property/Todo matcher"))
920 :version "24.1"
921 :group 'org-todo
922 :group 'org-archive)
924 (defcustom org-startup-folded t
925 "Non-nil means entering Org mode will switch to OVERVIEW.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
930 #+STARTUP: fold (or `overview', this is equivalent)
931 #+STARTUP: nofold (or `showall', this is equivalent)
932 #+STARTUP: content
933 #+STARTUP: showeverything
935 Set `org-agenda-inhibit-startup' to a non-nil value if you want
936 to ignore this option when Org opens agenda files for the first
937 time."
938 :group 'org-startup
939 :type '(choice
940 (const :tag "nofold: show all" nil)
941 (const :tag "fold: overview" t)
942 (const :tag "content: all headlines" content)
943 (const :tag "show everything, even drawers" showeverything)))
945 (defcustom org-startup-truncated t
946 "Non-nil means entering Org mode will set `truncate-lines'.
947 This is useful since some lines containing links can be very long and
948 uninteresting. Also tables look terrible when wrapped.
950 The variable `org-startup-truncated' allows to configure
951 truncation for Org mode different to the other modes that use the
952 variable `truncate-lines' and as a shortcut instead of putting
953 the variable `truncate-lines' into the `org-mode-hook'. If one
954 wants to configure truncation for Org mode not statically but
955 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
956 the variable `truncate-lines' has to be used because in such a
957 case it is too late to set the variable `org-startup-truncated'."
958 :group 'org-startup
959 :type 'boolean)
961 (defcustom org-startup-indented nil
962 "Non-nil means turn on `org-indent-mode' on startup.
963 This can also be configured on a per-file basis by adding one of
964 the following lines anywhere in the buffer:
966 #+STARTUP: indent
967 #+STARTUP: noindent"
968 :group 'org-structure
969 :type '(choice
970 (const :tag "Not" nil)
971 (const :tag "Globally (slow on startup in large files)" t)))
973 (defcustom org-use-sub-superscripts t
974 "Non-nil means interpret \"_\" and \"^\" for display.
976 If you want to control how Org exports those characters, see
977 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
978 used to be an alias for `org-export-with-sub-superscripts' in
979 Org <8.0, it is not anymore.
981 When this option is turned on, you can use TeX-like syntax for
982 sub- and superscripts within the buffer. Several characters after
983 \"_\" or \"^\" will be considered as a single item - so grouping
984 with {} is normally not needed. For example, the following things
985 will be parsed as single sub- or superscripts:
987 10^24 or 10^tau several digits will be considered 1 item.
988 10^-12 or 10^-tau a leading sign with digits or a word
989 x^2-y^3 will be read as x^2 - y^3, because items are
990 terminated by almost any nonword/nondigit char.
991 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
993 Still, ambiguity is possible. So when in doubt, use {} to enclose
994 the sub/superscript. If you set this variable to the symbol `{}',
995 the braces are *required* in order to trigger interpretations as
996 sub/superscript. This can be helpful in documents that need \"_\"
997 frequently in plain text."
998 :group 'org-startup
999 :version "24.4"
1000 :package-version '(Org . "8.0")
1001 :type '(choice
1002 (const :tag "Always interpret" t)
1003 (const :tag "Only with braces" {})
1004 (const :tag "Never interpret" nil)))
1006 (defcustom org-startup-with-beamer-mode nil
1007 "Non-nil means turn on `org-beamer-mode' on startup.
1008 This can also be configured on a per-file basis by adding one of
1009 the following lines anywhere in the buffer:
1011 #+STARTUP: beamer"
1012 :group 'org-startup
1013 :version "24.1"
1014 :type 'boolean)
1016 (defcustom org-startup-align-all-tables nil
1017 "Non-nil means align all tables when visiting a file.
1018 This can also be configured on a per-file basis by adding one of
1019 the following lines anywhere in the buffer:
1020 #+STARTUP: align
1021 #+STARTUP: noalign"
1022 :group 'org-startup
1023 :type 'boolean)
1025 (defcustom org-startup-shrink-all-tables nil
1026 "Non-nil means shrink all table columns with a width cookie.
1027 This can also be configured on a per-file basis by adding one of
1028 the following lines anywhere in the buffer:
1029 #+STARTUP: shrink"
1030 :group 'org-startup
1031 :type 'boolean
1032 :version "27.1"
1033 :package-version '(Org . "9.2")
1034 :safe #'booleanp)
1036 (defcustom org-startup-with-inline-images nil
1037 "Non-nil means show inline images when loading a new Org file.
1038 This can also be configured on a per-file basis by adding one of
1039 the following lines anywhere in the buffer:
1040 #+STARTUP: inlineimages
1041 #+STARTUP: noinlineimages"
1042 :group 'org-startup
1043 :version "24.1"
1044 :type 'boolean)
1046 (defcustom org-startup-with-latex-preview nil
1047 "Non-nil means preview LaTeX fragments when loading a new Org file.
1049 This can also be configured on a per-file basis by adding one of
1050 the following lines anywhere in the buffer:
1051 #+STARTUP: latexpreview
1052 #+STARTUP: nolatexpreview"
1053 :group 'org-startup
1054 :version "24.4"
1055 :package-version '(Org . "8.0")
1056 :type 'boolean)
1058 (defcustom org-insert-mode-line-in-empty-file nil
1059 "Non-nil means insert the first line setting Org mode in empty files.
1060 When the function `org-mode' is called interactively in an empty file, this
1061 normally means that the file name does not automatically trigger Org mode.
1062 To ensure that the file will always be in Org mode in the future, a
1063 line enforcing Org mode will be inserted into the buffer, if this option
1064 has been set."
1065 :group 'org-startup
1066 :type 'boolean)
1068 (defcustom org-replace-disputed-keys nil
1069 "Non-nil means use alternative key bindings for some keys.
1071 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1072 These keys are also used by other packages like Shift Select mode,
1073 CUA mode or Windmove. If you want to use Org mode together with
1074 one of these other modes, or more generally if you would like to
1075 move some Org mode commands to other keys, set this variable and
1076 configure the keys with the variable `org-disputed-keys'.
1078 This option is only relevant at load-time of Org mode, and must be set
1079 *before* org.el is loaded. Changing it requires a restart of Emacs to
1080 become effective."
1081 :group 'org-startup
1082 :type 'boolean)
1084 (defcustom org-use-extra-keys nil
1085 "Non-nil means use extra key sequence definitions for certain commands.
1086 This happens automatically if `window-system' is nil. This
1087 variable lets you do the same manually. You must set it before
1088 loading Org."
1089 :group 'org-startup
1090 :type 'boolean)
1092 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1094 (defcustom org-disputed-keys
1095 '(([(shift up)] . [(meta p)])
1096 ([(shift down)] . [(meta n)])
1097 ([(shift left)] . [(meta -)])
1098 ([(shift right)] . [(meta +)])
1099 ([(control shift right)] . [(meta shift +)])
1100 ([(control shift left)] . [(meta shift -)]))
1101 "Keys for which Org mode and other modes compete.
1102 This is an alist, cars are the default keys, second element specifies
1103 the alternative to use when `org-replace-disputed-keys' is t.
1105 Keys can be specified in any syntax supported by `define-key'.
1106 The value of this option takes effect only at Org mode startup,
1107 therefore you'll have to restart Emacs to apply it after changing."
1108 :group 'org-startup
1109 :type 'alist)
1111 (defun org-key (key)
1112 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1113 Or return the original if not disputed."
1114 (when org-replace-disputed-keys
1115 (let* ((nkey (key-description key))
1116 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1117 org-disputed-keys)))
1118 (setq key (if x (cdr x) key))))
1119 key)
1121 (defun org-defkey (keymap key def)
1122 "Define a key, possibly translated, as returned by `org-key'."
1123 (define-key keymap (org-key key) def))
1125 (defcustom org-ellipsis nil
1126 "The ellipsis to use in the Org mode outline.
1128 When nil, just use the standard three dots. When a non-empty string,
1129 use that string instead.
1131 The change affects only Org mode (which will then use its own display table).
1132 Changing this requires executing `\\[org-mode]' in a buffer to become
1133 effective."
1134 :group 'org-startup
1135 :type '(choice (const :tag "Default" nil)
1136 (string :tag "String" :value "...#"))
1137 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1139 (defvar org-display-table nil
1140 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1142 (defgroup org-keywords nil
1143 "Keywords in Org mode."
1144 :tag "Org Keywords"
1145 :group 'org)
1147 (defcustom org-closed-keep-when-no-todo nil
1148 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1149 :group 'org-todo
1150 :group 'org-keywords
1151 :version "24.4"
1152 :package-version '(Org . "8.0")
1153 :type 'boolean)
1155 (defgroup org-structure nil
1156 "Options concerning the general structure of Org files."
1157 :tag "Org Structure"
1158 :group 'org)
1160 (defgroup org-reveal-location nil
1161 "Options about how to make context of a location visible."
1162 :tag "Org Reveal Location"
1163 :group 'org-structure)
1165 (defcustom org-show-context-detail '((agenda . local)
1166 (bookmark-jump . lineage)
1167 (isearch . lineage)
1168 (default . ancestors))
1169 "Alist between context and visibility span when revealing a location.
1171 \\<org-mode-map>Some actions may move point into invisible
1172 locations. As a consequence, Org always expose a neighborhood
1173 around point. How much is shown depends on the initial action,
1174 or context. Valid contexts are
1176 agenda when exposing an entry from the agenda
1177 org-goto when using the command `org-goto' (`\\[org-goto]')
1178 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1179 tags-tree when constructing a sparse tree based on tags matches
1180 link-search when exposing search matches associated with a link
1181 mark-goto when exposing the jump goal of a mark
1182 bookmark-jump when exposing a bookmark location
1183 isearch when exiting from an incremental search
1184 default default for all contexts not set explicitly
1186 Allowed visibility spans are
1188 minimal show current headline; if point is not on headline,
1189 also show entry
1191 local show current headline, entry and next headline
1193 ancestors show current headline and its direct ancestors; if
1194 point is not on headline, also show entry
1196 lineage show current headline, its direct ancestors and all
1197 their children; if point is not on headline, also show
1198 entry and first child
1200 tree show current headline, its direct ancestors and all
1201 their children; if point is not on headline, also show
1202 entry and all children
1204 canonical show current headline, its direct ancestors along with
1205 their entries and children; if point is not located on
1206 the headline, also show current entry and all children
1208 As special cases, a nil or t value means show all contexts in
1209 `minimal' or `canonical' view, respectively.
1211 Some views can make displayed information very compact, but also
1212 make it harder to edit the location of the match. In such
1213 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1214 more context."
1215 :group 'org-reveal-location
1216 :version "26.1"
1217 :package-version '(Org . "9.0")
1218 :type '(choice
1219 (const :tag "Canonical" t)
1220 (const :tag "Minimal" nil)
1221 (repeat :greedy t :tag "Individual contexts"
1222 (cons
1223 (choice :tag "Context"
1224 (const agenda)
1225 (const org-goto)
1226 (const occur-tree)
1227 (const tags-tree)
1228 (const link-search)
1229 (const mark-goto)
1230 (const bookmark-jump)
1231 (const isearch)
1232 (const default))
1233 (choice :tag "Detail level"
1234 (const minimal)
1235 (const local)
1236 (const ancestors)
1237 (const lineage)
1238 (const tree)
1239 (const canonical))))))
1241 (defcustom org-indirect-buffer-display 'other-window
1242 "How should indirect tree buffers be displayed?
1244 This applies to indirect buffers created with the commands
1245 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1247 Valid values are:
1248 current-window Display in the current window
1249 other-window Just display in another window.
1250 dedicated-frame Create one new frame, and re-use it each time.
1251 new-frame Make a new frame each time. Note that in this case
1252 previously-made indirect buffers are kept, and you need to
1253 kill these buffers yourself."
1254 :group 'org-structure
1255 :group 'org-agenda-windows
1256 :type '(choice
1257 (const :tag "In current window" current-window)
1258 (const :tag "In current frame, other window" other-window)
1259 (const :tag "Each time a new frame" new-frame)
1260 (const :tag "One dedicated frame" dedicated-frame)))
1262 (defcustom org-use-speed-commands nil
1263 "Non-nil means activate single letter commands at beginning of a headline.
1264 This may also be a function to test for appropriate locations where speed
1265 commands should be active.
1267 For example, to activate speed commands when the point is on any
1268 star at the beginning of the headline, you can do this:
1270 (setq org-use-speed-commands
1271 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1272 :group 'org-structure
1273 :type '(choice
1274 (const :tag "Never" nil)
1275 (const :tag "At beginning of headline stars" t)
1276 (function)))
1278 (defcustom org-speed-commands-user nil
1279 "Alist of additional speed commands.
1280 This list will be checked before `org-speed-commands-default'
1281 when the variable `org-use-speed-commands' is non-nil
1282 and when the cursor is at the beginning of a headline.
1283 The car of each entry is a string with a single letter, which must
1284 be assigned to `self-insert-command' in the global map.
1285 The cdr is either a command to be called interactively, a function
1286 to be called, or a form to be evaluated.
1287 An entry that is just a list with a single string will be interpreted
1288 as a descriptive headline that will be added when listing the speed
1289 commands in the Help buffer using the `?' speed command."
1290 :group 'org-structure
1291 :type '(repeat :value ("k" . ignore)
1292 (choice :value ("k" . ignore)
1293 (list :tag "Descriptive Headline" (string :tag "Headline"))
1294 (cons :tag "Letter and Command"
1295 (string :tag "Command letter")
1296 (choice
1297 (function)
1298 (sexp))))))
1300 (defcustom org-bookmark-names-plist
1301 '(:last-capture "org-capture-last-stored"
1302 :last-refile "org-refile-last-stored"
1303 :last-capture-marker "org-capture-last-stored-marker")
1304 "Names for bookmarks automatically set by some Org commands.
1305 This can provide strings as names for a number of bookmarks Org sets
1306 automatically. The following keys are currently implemented:
1307 :last-capture
1308 :last-capture-marker
1309 :last-refile
1310 When a key does not show up in the property list, the corresponding bookmark
1311 is not set."
1312 :group 'org-structure
1313 :type 'plist)
1315 (defgroup org-cycle nil
1316 "Options concerning visibility cycling in Org mode."
1317 :tag "Org Cycle"
1318 :group 'org-structure)
1320 (defcustom org-cycle-skip-children-state-if-no-children t
1321 "Non-nil means skip CHILDREN state in entries that don't have any."
1322 :group 'org-cycle
1323 :type 'boolean)
1325 (defcustom org-cycle-max-level nil
1326 "Maximum level which should still be subject to visibility cycling.
1327 Levels higher than this will, for cycling, be treated as text, not a headline.
1328 When `org-odd-levels-only' is set, a value of N in this variable actually
1329 means 2N-1 stars as the limiting headline.
1330 When nil, cycle all levels.
1331 Note that the limiting level of cycling is also influenced by
1332 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1333 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1334 than its value."
1335 :group 'org-cycle
1336 :type '(choice
1337 (const :tag "No limit" nil)
1338 (integer :tag "Maximum level")))
1340 (defcustom org-hide-block-startup nil
1341 "Non-nil means entering Org mode will fold all blocks.
1342 This can also be set in on a per-file basis with
1344 #+STARTUP: hideblocks
1345 #+STARTUP: showblocks"
1346 :group 'org-startup
1347 :group 'org-cycle
1348 :type 'boolean)
1350 (defcustom org-cycle-global-at-bob nil
1351 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1353 This makes it possible to do global cycling without having to use `S-TAB'
1354 or `\\[universal-argument] TAB'. For this special case to work, the first \
1355 line of the buffer
1356 must not be a headline -- it may be empty or some other text.
1358 When used in this way, `org-cycle-hook' is disabled temporarily to make
1359 sure the cursor stays at the beginning of the buffer.
1361 When this option is nil, don't do anything special at the beginning of
1362 the buffer."
1363 :group 'org-cycle
1364 :type 'boolean)
1366 (defcustom org-cycle-level-after-item/entry-creation t
1367 "Non-nil means cycle entry level or item indentation in new empty entries.
1369 When the cursor is at the end of an empty headline, i.e., with only stars
1370 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1371 and then all possible ancestor states, before returning to the original state.
1372 This makes data entry extremely fast: M-RET to create a new headline,
1373 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1375 When the cursor is at the end of an empty plain list item, one TAB will
1376 make it a subitem, two or more tabs will back up to make this an item
1377 higher up in the item hierarchy."
1378 :group 'org-cycle
1379 :type 'boolean)
1381 (defcustom org-cycle-emulate-tab t
1382 "Where should `org-cycle' emulate TAB.
1383 nil Never
1384 white Only in completely white lines
1385 whitestart Only at the beginning of lines, before the first non-white char
1386 t Everywhere except in headlines
1387 exc-hl-bol Everywhere except at the start of a headline
1388 If TAB is used in a place where it does not emulate TAB, the current subtree
1389 visibility is cycled."
1390 :group 'org-cycle
1391 :type '(choice (const :tag "Never" nil)
1392 (const :tag "Only in completely white lines" white)
1393 (const :tag "Before first char in a line" whitestart)
1394 (const :tag "Everywhere except in headlines" t)
1395 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1397 (defcustom org-cycle-separator-lines 2
1398 "Number of empty lines needed to keep an empty line between collapsed trees.
1399 If you leave an empty line between the end of a subtree and the following
1400 headline, this empty line is hidden when the subtree is folded.
1401 Org mode will leave (exactly) one empty line visible if the number of
1402 empty lines is equal or larger to the number given in this variable.
1403 So the default 2 means at least 2 empty lines after the end of a subtree
1404 are needed to produce free space between a collapsed subtree and the
1405 following headline.
1407 If the number is negative, and the number of empty lines is at least -N,
1408 all empty lines are shown.
1410 Special case: when 0, never leave empty lines in collapsed view."
1411 :group 'org-cycle
1412 :type 'integer)
1413 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1415 (defcustom org-pre-cycle-hook nil
1416 "Hook that is run before visibility cycling is happening.
1417 The function(s) in this hook must accept a single argument which indicates
1418 the new state that will be set right after running this hook. The
1419 argument is a symbol. Before a global state change, it can have the values
1420 `overview', `content', or `all'. Before a local state change, it can have
1421 the values `folded', `children', or `subtree'."
1422 :group 'org-cycle
1423 :type 'hook)
1425 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1426 org-cycle-show-empty-lines
1427 org-optimize-window-after-visibility-change)
1428 "Hook that is run after `org-cycle' has changed the buffer visibility.
1429 The function(s) in this hook must accept a single argument which indicates
1430 the new state that was set by the most recent `org-cycle' command. The
1431 argument is a symbol. After a global state change, it can have the values
1432 `overview', `contents', or `all'. After a local state change, it can have
1433 the values `folded', `children', or `subtree'."
1434 :group 'org-cycle
1435 :type 'hook
1436 :version "26.1"
1437 :package-version '(Org . "8.3"))
1439 (defgroup org-edit-structure nil
1440 "Options concerning structure editing in Org mode."
1441 :tag "Org Edit Structure"
1442 :group 'org-structure)
1444 (defcustom org-odd-levels-only nil
1445 "Non-nil means skip even levels and only use odd levels for the outline.
1446 This has the effect that two stars are being added/taken away in
1447 promotion/demotion commands. It also influences how levels are
1448 handled by the exporters.
1449 Changing it requires restart of `font-lock-mode' to become effective
1450 for fontification also in regions already fontified.
1451 You may also set this on a per-file basis by adding one of the following
1452 lines to the buffer:
1454 #+STARTUP: odd
1455 #+STARTUP: oddeven"
1456 :group 'org-edit-structure
1457 :group 'org-appearance
1458 :type 'boolean)
1460 (defcustom org-adapt-indentation t
1461 "Non-nil means adapt indentation to outline node level.
1463 When this variable is set, Org assumes that you write outlines by
1464 indenting text in each node to align with the headline (after the
1465 stars). The following issues are influenced by this variable:
1467 - The indentation is increased by one space in a demotion
1468 command, and decreased by one in a promotion command. However,
1469 in the latter case, if shifting some line in the entry body
1470 would alter document structure (e.g., insert a new headline),
1471 indentation is not changed at all.
1473 - Property drawers and planning information is inserted indented
1474 when this variable is set. When nil, they will not be indented.
1476 - TAB indents a line relative to current level. The lines below
1477 a headline will be indented when this variable is set.
1479 Note that this is all about true indentation, by adding and
1480 removing space characters. See also \"org-indent.el\" which does
1481 level-dependent indentation in a virtual way, i.e. at display
1482 time in Emacs."
1483 :group 'org-edit-structure
1484 :type 'boolean
1485 :safe #'booleanp)
1487 (defcustom org-special-ctrl-a/e nil
1488 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1490 When t, `C-a' will bring back the cursor to the beginning of the
1491 headline text, i.e. after the stars and after a possible TODO
1492 keyword. In an item, this will be the position after bullet and
1493 check-box, if any. When the cursor is already at that position,
1494 another `C-a' will bring it to the beginning of the line.
1496 `C-e' will jump to the end of the headline, ignoring the presence
1497 of tags in the headline. A second `C-e' will then jump to the
1498 true end of the line, after any tags. This also means that, when
1499 this variable is non-nil, `C-e' also will never jump beyond the
1500 end of the heading of a folded section, i.e. not after the
1501 ellipses.
1503 When set to the symbol `reversed', the first `C-a' or `C-e' works
1504 normally, going to the true line boundary first. Only a directly
1505 following, identical keypress will bring the cursor to the
1506 special positions.
1508 This may also be a cons cell where the behavior for `C-a' and
1509 `C-e' is set separately."
1510 :group 'org-edit-structure
1511 :type '(choice
1512 (const :tag "off" nil)
1513 (const :tag "on: after stars/bullet and before tags first" t)
1514 (const :tag "reversed: true line boundary first" reversed)
1515 (cons :tag "Set C-a and C-e separately"
1516 (choice :tag "Special C-a"
1517 (const :tag "off" nil)
1518 (const :tag "on: after stars/bullet first" t)
1519 (const :tag "reversed: before stars/bullet first" reversed))
1520 (choice :tag "Special C-e"
1521 (const :tag "off" nil)
1522 (const :tag "on: before tags first" t)
1523 (const :tag "reversed: after tags first" reversed)))))
1524 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1526 (defcustom org-special-ctrl-k nil
1527 "Non-nil means `C-k' will behave specially in headlines.
1528 When nil, `C-k' will call the default `kill-line' command.
1529 When t, the following will happen while the cursor is in the headline:
1531 - When the cursor is at the beginning of a headline, kill the entire
1532 line and possible the folded subtree below the line.
1533 - When in the middle of the headline text, kill the headline up to the tags.
1534 - When after the headline text, kill the tags."
1535 :group 'org-edit-structure
1536 :type 'boolean)
1538 (defcustom org-ctrl-k-protect-subtree nil
1539 "Non-nil means, do not delete a hidden subtree with C-k.
1540 When set to the symbol `error', simply throw an error when C-k is
1541 used to kill (part-of) a headline that has hidden text behind it.
1542 Any other non-nil value will result in a query to the user, if it is
1543 OK to kill that hidden subtree. When nil, kill without remorse."
1544 :group 'org-edit-structure
1545 :version "24.1"
1546 :type '(choice
1547 (const :tag "Do not protect hidden subtrees" nil)
1548 (const :tag "Protect hidden subtrees with a security query" t)
1549 (const :tag "Never kill a hidden subtree with C-k" error)))
1551 (defcustom org-special-ctrl-o t
1552 "Non-nil means, make `C-o' insert a row in tables."
1553 :group 'org-edit-structure
1554 :type 'boolean)
1556 (defcustom org-catch-invisible-edits nil
1557 "Check if in invisible region before inserting or deleting a character.
1558 Valid values are:
1560 nil Do not check, so just do invisible edits.
1561 error Throw an error and do nothing.
1562 show Make point visible, and do the requested edit.
1563 show-and-error Make point visible, then throw an error and abort the edit.
1564 smart Make point visible, and do insertion/deletion if it is
1565 adjacent to visible text and the change feels predictable.
1566 Never delete a previously invisible character or add in the
1567 middle or right after an invisible region. Basically, this
1568 allows insertion and backward-delete right before ellipses.
1569 FIXME: maybe in this case we should not even show?"
1570 :group 'org-edit-structure
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Do not check" nil)
1574 (const :tag "Throw error when trying to edit" error)
1575 (const :tag "Unhide, but do not do the edit" show-and-error)
1576 (const :tag "Show invisible part and do the edit" show)
1577 (const :tag "Be smart and do the right thing" smart)))
1579 (defcustom org-yank-folded-subtrees t
1580 "Non-nil means when yanking subtrees, fold them.
1581 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1582 it starts with a heading and all other headings in it are either children
1583 or siblings, then fold all the subtrees. However, do this only if no
1584 text after the yank would be swallowed into a folded tree by this action."
1585 :group 'org-edit-structure
1586 :type 'boolean)
1588 (defcustom org-yank-adjusted-subtrees nil
1589 "Non-nil means when yanking subtrees, adjust the level.
1590 With this setting, `org-paste-subtree' is used to insert the subtree, see
1591 this function for details."
1592 :group 'org-edit-structure
1593 :type 'boolean)
1595 (defcustom org-M-RET-may-split-line '((default . t))
1596 "Non-nil means M-RET will split the line at the cursor position.
1597 When nil, it will go to the end of the line before making a
1598 new line.
1599 You may also set this option in a different way for different
1600 contexts. Valid contexts are:
1602 headline when creating a new headline
1603 item when creating a new item
1604 table in a table field
1605 default the value to be used for all contexts not explicitly
1606 customized"
1607 :group 'org-structure
1608 :group 'org-table
1609 :type '(choice
1610 (const :tag "Always" t)
1611 (const :tag "Never" nil)
1612 (repeat :greedy t :tag "Individual contexts"
1613 (cons
1614 (choice :tag "Context"
1615 (const headline)
1616 (const item)
1617 (const table)
1618 (const default))
1619 (boolean)))))
1622 (defcustom org-insert-heading-respect-content nil
1623 "Non-nil means insert new headings after the current subtree.
1624 \\<org-mode-map>
1625 When nil, the new heading is created directly after the current line.
1626 The commands `\\[org-insert-heading-respect-content]' and \
1627 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1628 for the duration of the command."
1629 :group 'org-structure
1630 :type 'boolean)
1632 (defcustom org-blank-before-new-entry '((heading . auto)
1633 (plain-list-item . auto))
1634 "Should `org-insert-heading' leave a blank line before new heading/item?
1635 The value is an alist, with `heading' and `plain-list-item' as CAR,
1636 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1637 which case Org will look at the surrounding headings/items and try to
1638 make an intelligent decision whether to insert a blank line or not."
1639 :group 'org-edit-structure
1640 :type '(list
1641 (cons (const heading)
1642 (choice (const :tag "Never" nil)
1643 (const :tag "Always" t)
1644 (const :tag "Auto" auto)))
1645 (cons (const plain-list-item)
1646 (choice (const :tag "Never" nil)
1647 (const :tag "Always" t)
1648 (const :tag "Auto" auto)))))
1650 (defcustom org-insert-heading-hook nil
1651 "Hook being run after inserting a new heading."
1652 :group 'org-edit-structure
1653 :type 'hook)
1655 (defcustom org-enable-fixed-width-editor t
1656 "Non-nil means lines starting with \":\" are treated as fixed-width.
1657 This currently only means they are never auto-wrapped.
1658 When nil, such lines will be treated like ordinary lines."
1659 :group 'org-edit-structure
1660 :type 'boolean)
1662 (defgroup org-sparse-trees nil
1663 "Options concerning sparse trees in Org mode."
1664 :tag "Org Sparse Trees"
1665 :group 'org-structure)
1667 (defcustom org-highlight-sparse-tree-matches t
1668 "Non-nil means highlight all matches that define a sparse tree.
1669 The highlights will automatically disappear the next time the buffer is
1670 changed by an edit command."
1671 :group 'org-sparse-trees
1672 :type 'boolean)
1674 (defcustom org-remove-highlights-with-change t
1675 "Non-nil means any change to the buffer will remove temporary highlights.
1676 \\<org-mode-map>\
1677 Such highlights are created by `org-occur' and `org-clock-display'.
1678 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1679 to get rid of the highlights.
1680 The highlights created by `org-toggle-latex-fragment' always need
1681 `\\[org-toggle-latex-fragment]' to be removed."
1682 :group 'org-sparse-trees
1683 :group 'org-time
1684 :type 'boolean)
1686 (defcustom org-occur-case-fold-search t
1687 "Non-nil means `org-occur' should be case-insensitive.
1688 If set to `smart' the search will be case-insensitive only if it
1689 doesn't specify any upper case character."
1690 :group 'org-sparse-trees
1691 :version "26.1"
1692 :type '(choice
1693 (const :tag "Case-sensitive" nil)
1694 (const :tag "Case-insensitive" t)
1695 (const :tag "Case-insensitive for lower case searches only" smart)))
1697 (defcustom org-occur-hook '(org-first-headline-recenter)
1698 "Hook that is run after `org-occur' has constructed a sparse tree.
1699 This can be used to recenter the window to show as much of the structure
1700 as possible."
1701 :group 'org-sparse-trees
1702 :type 'hook)
1704 (defgroup org-table nil
1705 "Options concerning tables in Org mode."
1706 :tag "Org Table"
1707 :group 'org)
1709 (defcustom org-self-insert-cluster-for-undo nil
1710 "Non-nil means cluster self-insert commands for undo when possible.
1711 If this is set, then, like in the Emacs command loop, 20 consecutive
1712 characters will be undone together.
1713 This is configurable, because there is some impact on typing performance."
1714 :group 'org-table
1715 :type 'boolean)
1717 (defcustom org-table-tab-recognizes-table.el t
1718 "Non-nil means TAB will automatically notice a table.el table.
1719 When it sees such a table, it moves point into it and - if necessary -
1720 calls `table-recognize-table'."
1721 :group 'org-table-editing
1722 :type 'boolean)
1724 (defgroup org-link nil
1725 "Options concerning links in Org mode."
1726 :tag "Org Link"
1727 :group 'org)
1729 (defvar-local org-link-abbrev-alist-local nil
1730 "Buffer-local version of `org-link-abbrev-alist', which see.
1731 The value of this is taken from the #+LINK lines.")
1733 (defcustom org-link-parameters
1734 '(("doi" :follow org--open-doi-link)
1735 ("elisp" :follow org--open-elisp-link)
1736 ("file" :complete org-file-complete-link)
1737 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1738 ("help" :follow org--open-help-link)
1739 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1740 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1741 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1742 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1743 ("shell" :follow org--open-shell-link))
1744 "An alist of properties that defines all the links in Org mode.
1745 The key in each association is a string of the link type.
1746 Subsequent optional elements make up a p-list of link properties.
1748 :follow - A function that takes the link path as an argument.
1750 :export - A function that takes the link path, description and
1751 export-backend as arguments.
1753 :store - A function responsible for storing the link. See the
1754 function `org-store-link-functions'.
1756 :complete - A function that inserts a link with completion. The
1757 function takes one optional prefix arg.
1759 :face - A face for the link, or a function that returns a face.
1760 The function takes one argument which is the link path. The
1761 default face is `org-link'.
1763 :mouse-face - The mouse-face. The default is `highlight'.
1765 :display - `full' will not fold the link in descriptive
1766 display. Default is `org-link'.
1768 :help-echo - A string or function that takes (window object position)
1769 as arguments and returns a string.
1771 :keymap - A keymap that is active on the link. The default is
1772 `org-mouse-map'.
1774 :htmlize-link - A function for the htmlize-link. Defaults
1775 to (list :uri \"type:path\")
1777 :activate-func - A function to run at the end of font-lock
1778 activation. The function must accept (link-start link-end path bracketp)
1779 as arguments."
1780 :group 'org-link
1781 :type '(alist :tag "Link display parameters"
1782 :value-type plist)
1783 :version "26.1"
1784 :package-version '(Org . "9.1"))
1786 (defun org-link-get-parameter (type key)
1787 "Get TYPE link property for KEY.
1788 TYPE is a string and KEY is a plist keyword."
1789 (plist-get
1790 (cdr (assoc type org-link-parameters))
1791 key))
1793 (defun org-link-set-parameters (type &rest parameters)
1794 "Set link TYPE properties to PARAMETERS.
1795 PARAMETERS should be :key val pairs."
1796 (let ((data (assoc type org-link-parameters)))
1797 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1798 (push (cons type parameters) org-link-parameters)
1799 (org-make-link-regexps)
1800 (org-element-update-syntax))))
1802 (defun org-link-types ()
1803 "Return a list of known link types."
1804 (mapcar #'car org-link-parameters))
1806 (defcustom org-link-abbrev-alist nil
1807 "Alist of link abbreviations.
1808 The car of each element is a string, to be replaced at the start of a link.
1809 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1810 links in Org buffers can have an optional tag after a double colon, e.g.,
1812 [[linkkey:tag][description]]
1814 The `linkkey' must be a single word, starting with a letter, followed
1815 by letters, numbers, `-' or `_'.
1817 If REPLACE is a string, the tag will simply be appended to create the link.
1818 If the string contains \"%s\", the tag will be inserted there. If the string
1819 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1820 at that point (see the function `url-hexify-string'). If the string contains
1821 the specifier \"%(my-function)\", then the custom function `my-function' will
1822 be invoked: this function takes the tag as its only argument and must return
1823 a string.
1825 REPLACE may also be a function that will be called with the tag as the
1826 only argument to create the link, which should be returned as a string.
1828 See the manual for examples."
1829 :group 'org-link
1830 :type '(repeat
1831 (cons
1832 (string :tag "Protocol")
1833 (choice
1834 (string :tag "Format")
1835 (function)))))
1837 (defcustom org-descriptive-links t
1838 "Non-nil means Org will display descriptive links.
1839 E.g. [[https://orgmode.org][Org website]] will be displayed as
1840 \"Org Website\", hiding the link itself and just displaying its
1841 description. When set to nil, Org will display the full links
1842 literally.
1844 You can interactively set the value of this variable by calling
1845 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1846 :group 'org-link
1847 :type 'boolean)
1849 (defcustom org-link-file-path-type 'adaptive
1850 "How the path name in file links should be stored.
1851 Valid values are:
1853 relative Relative to the current directory, i.e. the directory of the file
1854 into which the link is being inserted.
1855 absolute Absolute path, if possible with ~ for home directory.
1856 noabbrev Absolute path, no abbreviation of home directory.
1857 adaptive Use relative path for files in the current directory and sub-
1858 directories of it. For other files, use an absolute path."
1859 :group 'org-link
1860 :type '(choice
1861 (const relative)
1862 (const absolute)
1863 (const noabbrev)
1864 (const adaptive)))
1866 (defvaralias 'org-activate-links 'org-highlight-links)
1867 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1868 "Types of links that should be highlighted in Org files.
1870 This is a list of symbols, each one of them leading to the
1871 highlighting of a certain link type.
1873 You can still open links that are not highlighted.
1875 In principle, it does not hurt to turn on highlighting for all
1876 link types. There may be a small gain when turning off unused
1877 link types. The types are:
1879 bracket The recommended [[link][description]] or [[link]] links with hiding.
1880 angle Links in angular brackets that may contain whitespace like
1881 <bbdb:Carsten Dominik>.
1882 plain Plain links in normal text, no whitespace, like http://google.com.
1883 radio Text that is matched by a radio target, see manual for details.
1884 tag Tag settings in a headline (link to tag search).
1885 date Time stamps (link to calendar).
1886 footnote Footnote labels.
1888 If you set this variable during an Emacs session, use `org-mode-restart'
1889 in the Org buffer so that the change takes effect."
1890 :group 'org-link
1891 :group 'org-appearance
1892 :type '(set :greedy t
1893 (const :tag "Double bracket links" bracket)
1894 (const :tag "Angular bracket links" angle)
1895 (const :tag "Plain text links" plain)
1896 (const :tag "Radio target matches" radio)
1897 (const :tag "Tags" tag)
1898 (const :tag "Timestamps" date)
1899 (const :tag "Footnotes" footnote)))
1901 (defcustom org-make-link-description-function nil
1902 "Function to use for generating link descriptions from links.
1903 This function must take two parameters: the first one is the
1904 link, the second one is the description generated by
1905 `org-insert-link'. The function should return the description to
1906 use."
1907 :group 'org-link
1908 :type '(choice (const nil) (function)))
1910 (defgroup org-link-store nil
1911 "Options concerning storing links in Org mode."
1912 :tag "Org Store Link"
1913 :group 'org-link)
1915 (defcustom org-url-hexify-p t
1916 "When non-nil, hexify URL when creating a link."
1917 :type 'boolean
1918 :version "24.3"
1919 :group 'org-link-store)
1921 (defcustom org-email-link-description-format "Email %c: %.30s"
1922 "Format of the description part of a link to an email or usenet message.
1923 The following %-escapes will be replaced by corresponding information:
1925 %F full \"From\" field
1926 %f name, taken from \"From\" field, address if no name
1927 %T full \"To\" field
1928 %t first name in \"To\" field, address if no name
1929 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1930 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1931 %s subject
1932 %d date
1933 %m message-id.
1935 You may use normal field width specification between the % and the letter.
1936 This is for example useful to limit the length of the subject.
1938 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1939 :group 'org-link-store
1940 :type 'string)
1942 (defcustom org-from-is-user-regexp
1943 (let (r1 r2)
1944 (when (and user-mail-address (not (string= user-mail-address "")))
1945 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1946 (when (and user-full-name (not (string= user-full-name "")))
1947 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1948 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1949 "Regexp matched against the \"From:\" header of an email or usenet message.
1950 It should match if the message is from the user him/herself."
1951 :group 'org-link-store
1952 :type 'regexp)
1954 (defcustom org-context-in-file-links t
1955 "Non-nil means file links from `org-store-link' contain context.
1956 \\<org-mode-map>
1957 A search string will be added to the file name with :: as separator
1958 and used to find the context when the link is activated by the command
1959 `org-open-at-point'. When this option is t, the entire active region
1960 will be placed in the search string of the file link. If set to a
1961 positive integer, only the first n lines of context will be stored.
1963 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1964 \\[org-store-link]')
1965 negates this setting for the duration of the command."
1966 :group 'org-link-store
1967 :type '(choice boolean integer))
1969 (defcustom org-keep-stored-link-after-insertion nil
1970 "Non-nil means keep link in list for entire session.
1971 \\<org-mode-map>
1972 The command `org-store-link' adds a link pointing to the current
1973 location to an internal list. These links accumulate during a session.
1974 The command `org-insert-link' can be used to insert links into any
1975 Org file (offering completion for all stored links).
1977 When this option is nil, every link which has been inserted once using
1978 `\\[org-insert-link]' will be removed from the list, to make completing the \
1979 unused
1980 links more efficient."
1981 :group 'org-link-store
1982 :type 'boolean)
1984 (defgroup org-link-follow nil
1985 "Options concerning following links in Org mode."
1986 :tag "Org Follow Link"
1987 :group 'org-link)
1989 (defcustom org-link-translation-function nil
1990 "Function to translate links with different syntax to Org syntax.
1991 This can be used to translate links created for example by the Planner
1992 or emacs-wiki packages to Org syntax.
1993 The function must accept two parameters, a TYPE containing the link
1994 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1995 which is everything after the link protocol. It should return a cons
1996 with possibly modified values of type and path.
1997 Org contains a function for this, so if you set this variable to
1998 `org-translate-link-from-planner', you should be able follow many
1999 links created by planner."
2000 :group 'org-link-follow
2001 :type '(choice (const nil) (function)))
2003 (defcustom org-follow-link-hook nil
2004 "Hook that is run after a link has been followed."
2005 :group 'org-link-follow
2006 :type 'hook)
2008 (defcustom org-tab-follows-link nil
2009 "Non-nil means on links TAB will follow the link.
2010 Needs to be set before org.el is loaded.
2011 This really should not be used, it does not make sense, and the
2012 implementation is bad."
2013 :group 'org-link-follow
2014 :type 'boolean)
2016 (defcustom org-return-follows-link nil
2017 "Non-nil means on links RET will follow the link.
2018 In tables, the special behavior of RET has precedence."
2019 :group 'org-link-follow
2020 :type 'boolean)
2022 (defcustom org-mouse-1-follows-link
2023 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2024 "Non-nil means mouse-1 on a link will follow the link.
2025 A longer mouse click will still set point. Needs to be set
2026 before org.el is loaded."
2027 :group 'org-link-follow
2028 :version "26.1"
2029 :package-version '(Org . "8.3")
2030 :type '(choice
2031 (const :tag "A double click follows the link" double)
2032 (const :tag "Unconditionally follow the link with mouse-1" t)
2033 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2035 (defcustom org-mark-ring-length 4
2036 "Number of different positions to be recorded in the ring.
2037 Changing this requires a restart of Emacs to work correctly."
2038 :group 'org-link-follow
2039 :type 'integer)
2041 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2042 "Non-nil means internal fuzzy links can only match headlines.
2044 When nil, the a fuzzy link may point to a target or a named
2045 construct in the document. When set to the special value
2046 `query-to-create', offer to create a new headline when none
2047 matched.
2049 Spaces and statistics cookies are ignored during heading searches."
2050 :group 'org-link-follow
2051 :version "24.1"
2052 :type '(choice
2053 (const :tag "Use fuzzy text search" nil)
2054 (const :tag "Match only exact headline" t)
2055 (const :tag "Match exact headline or query to create it"
2056 query-to-create))
2057 :safe #'symbolp)
2059 (defcustom org-link-frame-setup
2060 '((vm . vm-visit-folder-other-frame)
2061 (vm-imap . vm-visit-imap-folder-other-frame)
2062 (gnus . org-gnus-no-new-news)
2063 (file . find-file-other-window)
2064 (wl . wl-other-frame))
2065 "Setup the frame configuration for following links.
2066 When following a link with Emacs, it may often be useful to display
2067 this link in another window or frame. This variable can be used to
2068 set this up for the different types of links.
2069 For VM, use any of
2070 `vm-visit-folder'
2071 `vm-visit-folder-other-window'
2072 `vm-visit-folder-other-frame'
2073 For Gnus, use any of
2074 `gnus'
2075 `gnus-other-frame'
2076 `org-gnus-no-new-news'
2077 For FILE, use any of
2078 `find-file'
2079 `find-file-other-window'
2080 `find-file-other-frame'
2081 For Wanderlust use any of
2082 `wl'
2083 `wl-other-frame'
2084 For the calendar, use the variable `calendar-setup'.
2085 For BBDB, it is currently only possible to display the matches in
2086 another window."
2087 :group 'org-link-follow
2088 :type '(list
2089 (cons (const vm)
2090 (choice
2091 (const vm-visit-folder)
2092 (const vm-visit-folder-other-window)
2093 (const vm-visit-folder-other-frame)))
2094 (cons (const vm-imap)
2095 (choice
2096 (const vm-visit-imap-folder)
2097 (const vm-visit-imap-folder-other-window)
2098 (const vm-visit-imap-folder-other-frame)))
2099 (cons (const gnus)
2100 (choice
2101 (const gnus)
2102 (const gnus-other-frame)
2103 (const org-gnus-no-new-news)))
2104 (cons (const file)
2105 (choice
2106 (const find-file)
2107 (const find-file-other-window)
2108 (const find-file-other-frame)))
2109 (cons (const wl)
2110 (choice
2111 (const wl)
2112 (const wl-other-frame)))))
2114 (defcustom org-display-internal-link-with-indirect-buffer nil
2115 "Non-nil means use indirect buffer to display infile links.
2116 Activating internal links (from one location in a file to another location
2117 in the same file) normally just jumps to the location. When the link is
2118 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2119 is displayed in
2120 another window. When this option is set, the other window actually displays
2121 an indirect buffer clone of the current buffer, to avoid any visibility
2122 changes to the current buffer."
2123 :group 'org-link-follow
2124 :type 'boolean)
2126 (defcustom org-open-non-existing-files nil
2127 "Non-nil means `org-open-file' will open non-existing files.
2128 When nil, an error will be generated.
2129 This variable applies only to external applications because they
2130 might choke on non-existing files. If the link is to a file that
2131 will be opened in Emacs, the variable is ignored."
2132 :group 'org-link-follow
2133 :type 'boolean)
2135 (defcustom org-open-directory-means-index-dot-org nil
2136 "Non-nil means a link to a directory really means to index.org.
2137 When nil, following a directory link will run dired or open a finder/explorer
2138 window on that directory."
2139 :group 'org-link-follow
2140 :type 'boolean)
2142 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2143 "Non-nil means ask for confirmation before executing shell links.
2144 Shell links can be dangerous: just think about a link
2146 [[shell:rm -rf ~/*][Google Search]]
2148 This link would show up in your Org document as \"Google Search\",
2149 but really it would remove your entire home directory.
2150 Therefore we advise against setting this variable to nil.
2151 Just change it to `y-or-n-p' if you want to confirm with a
2152 single keystroke rather than having to type \"yes\"."
2153 :group 'org-link-follow
2154 :type '(choice
2155 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2156 (const :tag "with y-or-n (faster)" y-or-n-p)
2157 (const :tag "no confirmation (dangerous)" nil)))
2158 (put 'org-confirm-shell-link-function
2159 'safe-local-variable
2160 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2162 (defcustom org-confirm-shell-link-not-regexp ""
2163 "A regexp to skip confirmation for shell links."
2164 :group 'org-link-follow
2165 :version "24.1"
2166 :type 'regexp)
2168 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2169 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2170 Elisp links can be dangerous: just think about a link
2172 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2174 This link would show up in your Org document as \"Google Search\",
2175 but really it would remove your entire home directory.
2176 Therefore we advise against setting this variable to nil.
2177 Just change it to `y-or-n-p' if you want to confirm with a
2178 single keystroke rather than having to type \"yes\"."
2179 :group 'org-link-follow
2180 :type '(choice
2181 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2182 (const :tag "with y-or-n (faster)" y-or-n-p)
2183 (const :tag "no confirmation (dangerous)" nil)))
2184 (put 'org-confirm-shell-link-function
2185 'safe-local-variable
2186 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2188 (defcustom org-confirm-elisp-link-not-regexp ""
2189 "A regexp to skip confirmation for Elisp links."
2190 :group 'org-link-follow
2191 :version "24.1"
2192 :type 'regexp)
2194 (defconst org-file-apps-defaults-gnu
2195 '((remote . emacs)
2196 (system . mailcap)
2197 (t . mailcap))
2198 "Default file applications on a UNIX or GNU/Linux system.
2199 See `org-file-apps'.")
2201 (defconst org-file-apps-defaults-macosx
2202 '((remote . emacs)
2203 (system . "open %s")
2204 ("ps.gz" . "gv %s")
2205 ("eps.gz" . "gv %s")
2206 ("dvi" . "xdvi %s")
2207 ("fig" . "xfig %s")
2208 (t . "open %s"))
2209 "Default file applications on a macOS system.
2210 The system \"open\" is known as a default, but we use X11 applications
2211 for some files for which the OS does not have a good default.
2212 See `org-file-apps'.")
2214 (defconst org-file-apps-defaults-windowsnt
2215 (list '(remote . emacs)
2216 (cons 'system (lambda (file _path)
2217 (with-no-warnings (w32-shell-execute "open" file))))
2218 (cons t (lambda (file _path)
2219 (with-no-warnings (w32-shell-execute "open" file)))))
2220 "Default file applications on a Windows NT system.
2221 The system \"open\" is used for most files.
2222 See `org-file-apps'.")
2224 (defcustom org-file-apps
2225 '((auto-mode . emacs)
2226 ("\\.mm\\'" . default)
2227 ("\\.x?html?\\'" . default)
2228 ("\\.pdf\\'" . default))
2229 "External applications for opening `file:path' items in a document.
2230 \\<org-mode-map>\
2232 Org mode uses system defaults for different file types, but
2233 you can use this variable to set the application for a given file
2234 extension. The entries in this list are cons cells where the car identifies
2235 files and the cdr the corresponding command.
2237 Possible values for the file identifier are:
2239 \"string\" A string as a file identifier can be interpreted in different
2240 ways, depending on its contents:
2242 - Alphanumeric characters only:
2243 Match links with this file extension.
2244 Example: (\"pdf\" . \"evince %s\")
2245 to open PDFs with evince.
2247 - Regular expression: Match links where the
2248 filename matches the regexp. If you want to
2249 use groups here, use shy groups.
2251 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2252 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2253 to open *.html and *.xhtml with firefox.
2255 - Regular expression which contains (non-shy) groups:
2256 Match links where the whole link, including \"::\", and
2257 anything after that, matches the regexp.
2258 In a custom command string, %1, %2, etc. are replaced with
2259 the parts of the link that were matched by the groups.
2260 For backwards compatibility, if a command string is given
2261 that does not use any of the group matches, this case is
2262 handled identically to the second one (i.e. match against
2263 file name only).
2264 In a custom function, you can access the group matches with
2265 (match-string n link).
2267 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2268 \"evince -p %1 %s\")
2269 to open [[file:document.pdf::5]] with evince at page 5.
2271 `directory' Matches a directory
2272 `remote' Matches a remote file, accessible through tramp or efs.
2273 Remote files most likely should be visited through Emacs
2274 because external applications cannot handle such paths.
2275 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2276 so all files Emacs knows how to handle. Using this with
2277 command `emacs' will open most files in Emacs. Beware that this
2278 will also open html files inside Emacs, unless you add
2279 (\"html\" . default) to the list as well.
2280 `system' The system command to open files, like `open' on Windows
2281 and macOS, and mailcap under GNU/Linux. This is the command
2282 that will be selected if you call `org-open-at-point' with a
2283 double prefix argument (`\\[universal-argument] \
2284 \\[universal-argument] \\[org-open-at-point]').
2285 t Default for files not matched by any of the other options.
2287 Possible values for the command are:
2289 `emacs' The file will be visited by the current Emacs process.
2290 `default' Use the default application for this file type, which is the
2291 association for t in the list, most likely in the system-specific
2292 part. This can be used to overrule an unwanted setting in the
2293 system-specific variable.
2294 `system' Use the system command for opening files, like \"open\".
2295 This command is specified by the entry whose car is `system'.
2296 Most likely, the system-specific version of this variable
2297 does define this command, but you can overrule/replace it
2298 here.
2299 `mailcap' Use command specified in the mailcaps.
2300 string A command to be executed by a shell; %s will be replaced
2301 by the path to the file.
2302 function A Lisp function, which will be called with two arguments:
2303 the file path and the original link string, without the
2304 \"file:\" prefix.
2306 For more examples, see the system specific constants
2307 `org-file-apps-defaults-macosx'
2308 `org-file-apps-defaults-windowsnt'
2309 `org-file-apps-defaults-gnu'."
2310 :group 'org-link-follow
2311 :type '(repeat
2312 (cons (choice :value ""
2313 (string :tag "Extension")
2314 (const :tag "System command to open files" system)
2315 (const :tag "Default for unrecognized files" t)
2316 (const :tag "Remote file" remote)
2317 (const :tag "Links to a directory" directory)
2318 (const :tag "Any files that have Emacs modes"
2319 auto-mode))
2320 (choice :value ""
2321 (const :tag "Visit with Emacs" emacs)
2322 (const :tag "Use default" default)
2323 (const :tag "Use the system command" system)
2324 (string :tag "Command")
2325 (function :tag "Function")))))
2327 (defcustom org-doi-server-url "http://dx.doi.org/"
2328 "The URL of the DOI server."
2329 :type 'string
2330 :version "24.3"
2331 :group 'org-link-follow)
2333 (defgroup org-refile nil
2334 "Options concerning refiling entries in Org mode."
2335 :tag "Org Refile"
2336 :group 'org)
2338 (defcustom org-directory "~/org"
2339 "Directory with Org files.
2340 This is just a default location to look for Org files. There is no need
2341 at all to put your files into this directory. It is used in the
2342 following situations:
2344 1. When a capture template specifies a target file that is not an
2345 absolute path. The path will then be interpreted relative to
2346 `org-directory'
2347 2. When the value of variable `org-agenda-files' is a single file, any
2348 relative paths in this file will be taken as relative to
2349 `org-directory'."
2350 :group 'org-refile
2351 :group 'org-capture
2352 :type 'directory)
2354 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2355 "Default target for storing notes.
2356 Used as a fall back file for org-capture.el, for templates that
2357 do not specify a target file."
2358 :group 'org-refile
2359 :group 'org-capture
2360 :type 'file)
2362 (defcustom org-reverse-note-order nil
2363 "Non-nil means store new notes at the beginning of a file or entry.
2364 When nil, new notes will be filed to the end of a file or entry.
2365 This can also be a list with cons cells of regular expressions that
2366 are matched against file names, and values."
2367 :group 'org-capture
2368 :group 'org-refile
2369 :type '(choice
2370 (const :tag "Reverse always" t)
2371 (const :tag "Reverse never" nil)
2372 (repeat :tag "By file name regexp"
2373 (cons regexp boolean))))
2375 (defcustom org-log-refile nil
2376 "Information to record when a task is refiled.
2378 Possible values are:
2380 nil Don't add anything
2381 time Add a time stamp to the task
2382 note Prompt for a note and add it with template `org-log-note-headings'
2384 This option can also be set with on a per-file-basis with
2386 #+STARTUP: nologrefile
2387 #+STARTUP: logrefile
2388 #+STARTUP: lognoterefile
2390 You can have local logging settings for a subtree by setting the LOGGING
2391 property to one or more of these keywords.
2393 When bulk-refiling from the agenda, the value `note' is forbidden and
2394 will temporarily be changed to `time'."
2395 :group 'org-refile
2396 :group 'org-progress
2397 :version "24.1"
2398 :type '(choice
2399 (const :tag "No logging" nil)
2400 (const :tag "Record timestamp" time)
2401 (const :tag "Record timestamp with note." note)))
2403 (defcustom org-refile-targets nil
2404 "Targets for refiling entries with `\\[org-refile]'.
2405 This is a list of cons cells. Each cell contains:
2406 - a specification of the files to be considered, either a list of files,
2407 or a symbol whose function or variable value will be used to retrieve
2408 a file name or a list of file names. If you use `org-agenda-files' for
2409 that, all agenda files will be scanned for targets. Nil means consider
2410 headings in the current buffer.
2411 - A specification of how to find candidate refile targets. This may be
2412 any of:
2413 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2414 This tag has to be present in all target headlines, inheritance will
2415 not be considered.
2416 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2417 todo keyword.
2418 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2419 headlines that are refiling targets.
2420 - a cons cell (:level . N). Any headline of level N is considered 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.
2423 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2424 Note that, when `org-odd-levels-only' is set, level corresponds to
2425 order in hierarchy, not to the number of stars.
2427 Each element of this list generates a set of possible targets.
2428 The union of these sets is presented (with completion) to
2429 the user by `org-refile'.
2431 You can set the variable `org-refile-target-verify-function' to a function
2432 to verify each headline found by the simple criteria above.
2434 When this variable is nil, all top-level headlines in the current buffer
2435 are used, equivalent to the value `((nil . (:level . 1))'."
2436 :group 'org-refile
2437 :type '(repeat
2438 (cons
2439 (choice :value org-agenda-files
2440 (const :tag "All agenda files" org-agenda-files)
2441 (const :tag "Current buffer" nil)
2442 (function) (variable) (file))
2443 (choice :tag "Identify target headline by"
2444 (cons :tag "Specific tag" (const :value :tag) (string))
2445 (cons :tag "TODO keyword" (const :value :todo) (string))
2446 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2447 (cons :tag "Level number" (const :value :level) (integer))
2448 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2450 (defcustom org-refile-target-verify-function nil
2451 "Function to verify if the headline at point should be a refile target.
2452 The function will be called without arguments, with point at the
2453 beginning of the headline. It should return t and leave point
2454 where it is if the headline is a valid target for refiling.
2456 If the target should not be selected, the function must return nil.
2457 In addition to this, it may move point to a place from where the search
2458 should be continued. For example, the function may decide that the entire
2459 subtree of the current entry should be excluded and move point to the end
2460 of the subtree."
2461 :group 'org-refile
2462 :type '(choice
2463 (const nil)
2464 (function)))
2466 (defcustom org-refile-use-cache nil
2467 "Non-nil means cache refile targets to speed up the process.
2468 \\<org-mode-map>\
2469 The cache for a particular file will be updated automatically when
2470 the buffer has been killed, or when any of the marker used for flagging
2471 refile targets no longer points at a live buffer.
2472 If you have added new entries to a buffer that might themselves be targets,
2473 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2474 if you find that easier, \
2475 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2476 \\[org-refile]'."
2477 :group 'org-refile
2478 :version "24.1"
2479 :type 'boolean)
2481 (defcustom org-refile-use-outline-path nil
2482 "Non-nil means provide refile targets as paths.
2483 So a level 3 headline will be available as level1/level2/level3.
2485 When the value is `file', also include the file name (without directory)
2486 into the path. In this case, you can also stop the completion after
2487 the file name, to get entries inserted as top level in the file.
2489 When `full-file-path', include the full file path.
2491 When `buffer-name', use the buffer name."
2492 :group 'org-refile
2493 :type '(choice
2494 (const :tag "Not" nil)
2495 (const :tag "Yes" t)
2496 (const :tag "Start with file name" file)
2497 (const :tag "Start with full file path" full-file-path)
2498 (const :tag "Start with buffer name" buffer-name)))
2500 (defcustom org-outline-path-complete-in-steps t
2501 "Non-nil means complete the outline path in hierarchical steps.
2502 When Org uses the refile interface to select an outline path (see
2503 `org-refile-use-outline-path'), the completion of the path can be
2504 done in a single go, or it can be done in steps down the headline
2505 hierarchy. Going in steps is probably the best if you do not use
2506 a special completion package like `ido' or `icicles'. However,
2507 when using these packages, going in one step can be very fast,
2508 while still showing the whole path to the entry."
2509 :group 'org-refile
2510 :type 'boolean)
2512 (defcustom org-refile-allow-creating-parent-nodes nil
2513 "Non-nil means allow the creation of new nodes as refile targets.
2514 New nodes are then created by adding \"/new node name\" to the completion
2515 of an existing node. When the value of this variable is `confirm',
2516 new node creation must be confirmed by the user (recommended).
2517 When nil, the completion must match an existing entry.
2519 Note that, if the new heading is not seen by the criteria
2520 listed in `org-refile-targets', multiple instances of the same
2521 heading would be created by trying again to file under the new
2522 heading."
2523 :group 'org-refile
2524 :type '(choice
2525 (const :tag "Never" nil)
2526 (const :tag "Always" t)
2527 (const :tag "Prompt for confirmation" confirm)))
2529 (defcustom org-refile-active-region-within-subtree nil
2530 "Non-nil means also refile active region within a subtree.
2532 By default `org-refile' doesn't allow refiling regions if they
2533 don't contain a set of subtrees, but it might be convenient to
2534 do so sometimes: in that case, the first line of the region is
2535 converted to a headline before refiling."
2536 :group 'org-refile
2537 :version "24.1"
2538 :type 'boolean)
2540 (defgroup org-todo nil
2541 "Options concerning TODO items in Org mode."
2542 :tag "Org TODO"
2543 :group 'org)
2545 (defgroup org-progress nil
2546 "Options concerning Progress logging in Org mode."
2547 :tag "Org Progress"
2548 :group 'org-time)
2550 (defvar org-todo-interpretation-widgets
2551 '((:tag "Sequence (cycling hits every state)" sequence)
2552 (:tag "Type (cycling directly to DONE)" type))
2553 "The available interpretation symbols for customizing `org-todo-keywords'.
2554 Interested libraries should add to this list.")
2556 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2557 "List of TODO entry keyword sequences and their interpretation.
2558 \\<org-mode-map>This is a list of sequences.
2560 Each sequence starts with a symbol, either `sequence' or `type',
2561 indicating if the keywords should be interpreted as a sequence of
2562 action steps, or as different types of TODO items. The first
2563 keywords are states requiring action - these states will select a headline
2564 for inclusion into the global TODO list Org produces. If one of the
2565 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2566 signify that no further action is necessary. If \"|\" is not found,
2567 the last keyword is treated as the only DONE state of the sequence.
2569 The command `\\[org-todo]' cycles an entry through these states, and one
2570 additional state where no keyword is present. For details about this
2571 cycling, see the manual.
2573 TODO keywords and interpretation can also be set on a per-file basis with
2574 the special #+SEQ_TODO and #+TYP_TODO lines.
2576 Each keyword can optionally specify a character for fast state selection
2577 \(in combination with the variable `org-use-fast-todo-selection')
2578 and specifiers for state change logging, using the same syntax that
2579 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2580 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2581 indicates to record a time stamp each time this state is selected.
2583 Each keyword may also specify if a timestamp or a note should be
2584 recorded when entering or leaving the state, by adding additional
2585 characters in the parenthesis after the keyword. This looks like this:
2586 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2587 record only the time of the state change. With X and Y being either
2588 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2589 Y when leaving the state if and only if the *target* state does not
2590 define X. You may omit any of the fast-selection key or X or /Y,
2591 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2593 For backward compatibility, this variable may also be just a list
2594 of keywords. In this case the interpretation (sequence or type) will be
2595 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2596 :group 'org-todo
2597 :group 'org-keywords
2598 :type '(choice
2599 (repeat :tag "Old syntax, just keywords"
2600 (string :tag "Keyword"))
2601 (repeat :tag "New syntax"
2602 (cons
2603 (choice
2604 :tag "Interpretation"
2605 ;;Quick and dirty way to see
2606 ;;`org-todo-interpretations'. This takes the
2607 ;;place of item arguments
2608 :convert-widget
2609 (lambda (widget)
2610 (widget-put widget
2611 :args (mapcar
2612 (lambda (x)
2613 (widget-convert
2614 (cons 'const x)))
2615 org-todo-interpretation-widgets))
2616 widget))
2617 (repeat
2618 (string :tag "Keyword"))))))
2620 (defvar-local org-todo-keywords-1 nil
2621 "All TODO and DONE keywords active in a buffer.")
2622 (defvar org-todo-keywords-for-agenda nil)
2623 (defvar org-done-keywords-for-agenda nil)
2624 (defvar org-todo-keyword-alist-for-agenda nil)
2625 (defvar org-tag-alist-for-agenda nil
2626 "Alist of all tags from all agenda files.")
2627 (defvar org-tag-groups-alist-for-agenda nil
2628 "Alist of all groups tags from all current agenda files.")
2629 (defvar-local org-tag-groups-alist nil)
2630 (defvar org-agenda-contributing-files nil)
2631 (defvar-local org-current-tag-alist nil
2632 "Alist of all tag groups in current buffer.
2633 This variable takes into consideration `org-tag-alist',
2634 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2635 (defvar-local org-not-done-keywords nil)
2636 (defvar-local org-done-keywords nil)
2637 (defvar-local org-todo-heads nil)
2638 (defvar-local org-todo-sets nil)
2639 (defvar-local org-todo-log-states nil)
2640 (defvar-local org-todo-kwd-alist nil)
2641 (defvar-local org-todo-key-alist nil)
2642 (defvar-local org-todo-key-trigger nil)
2644 (defcustom org-todo-interpretation 'sequence
2645 "Controls how TODO keywords are interpreted.
2646 This variable is in principle obsolete and is only used for
2647 backward compatibility, if the interpretation of todo keywords is
2648 not given already in `org-todo-keywords'. See that variable for
2649 more information."
2650 :group 'org-todo
2651 :group 'org-keywords
2652 :type '(choice (const sequence)
2653 (const type)))
2655 (defcustom org-use-fast-todo-selection t
2656 "\\<org-mode-map>\
2657 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2658 This variable describes if and under what circumstances the cycling
2659 mechanism for TODO keywords will be replaced by a single-key, direct
2660 selection scheme.
2662 When nil, fast selection is never used.
2664 When the symbol `prefix', it will be used when `org-todo' is called
2665 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2666 in an Org buffer, and
2667 `\\[universal-argument] t' in an agenda buffer.
2669 When t, fast selection is used by default. In this case, the prefix
2670 argument forces cycling instead.
2672 In all cases, the special interface is only used if access keys have
2673 actually been assigned by the user, i.e. if keywords in the configuration
2674 are followed by a letter in parenthesis, like TODO(t)."
2675 :group 'org-todo
2676 :type '(choice
2677 (const :tag "Never" nil)
2678 (const :tag "By default" t)
2679 (const :tag "Only with C-u C-c C-t" prefix)))
2681 (defcustom org-provide-todo-statistics t
2682 "Non-nil means update todo statistics after insert and toggle.
2683 ALL-HEADLINES means update todo statistics by including headlines
2684 with no TODO keyword as well, counting them as not done.
2685 A list of TODO keywords means the same, but skip keywords that are
2686 not in this list.
2687 When set to a list of two lists, the first list contains keywords
2688 to consider as TODO keywords, the second list contains keywords
2689 to consider as DONE keywords.
2691 When this is set, todo statistics is updated in the parent of the
2692 current entry each time a todo state is changed."
2693 :group 'org-todo
2694 :type '(choice
2695 (const :tag "Yes, only for TODO entries" t)
2696 (const :tag "Yes, including all entries" all-headlines)
2697 (repeat :tag "Yes, for TODOs in this list"
2698 (string :tag "TODO keyword"))
2699 (list :tag "Yes, for TODOs and DONEs in these lists"
2700 (repeat (string :tag "TODO keyword"))
2701 (repeat (string :tag "DONE keyword")))
2702 (other :tag "No TODO statistics" nil)))
2704 (defcustom org-hierarchical-todo-statistics t
2705 "Non-nil means TODO statistics covers just direct children.
2706 When nil, all entries in the subtree are considered.
2707 This has only an effect if `org-provide-todo-statistics' is set.
2708 To set this to nil for only a single subtree, use a COOKIE_DATA
2709 property and include the word \"recursive\" into the value."
2710 :group 'org-todo
2711 :type 'boolean)
2713 (defcustom org-after-todo-state-change-hook nil
2714 "Hook which is run after the state of a TODO item was changed.
2715 The new state (a string with a TODO keyword, or nil) is available in the
2716 Lisp variable `org-state'."
2717 :group 'org-todo
2718 :type 'hook)
2720 (defvar org-blocker-hook nil
2721 "Hook for functions that are allowed to block a state change.
2723 Functions in this hook should not modify the buffer.
2724 Each function gets as its single argument a property list,
2725 see `org-trigger-hook' for more information about this list.
2727 If any of the functions in this hook returns nil, the state change
2728 is blocked.")
2730 (defvar org-trigger-hook nil
2731 "Hook for functions that are triggered by a state change.
2733 Each function gets as its single argument a property list with at
2734 least the following elements:
2736 (:type type-of-change :position pos-at-entry-start
2737 :from old-state :to new-state)
2739 Depending on the type, more properties may be present.
2741 This mechanism is currently implemented for:
2743 TODO state changes
2744 ------------------
2745 :type todo-state-change
2746 :from previous state (keyword as a string), or nil, or a symbol
2747 `todo' or `done', to indicate the general type of state.
2748 :to new state, like in :from")
2750 (defcustom org-enforce-todo-dependencies nil
2751 "Non-nil means undone TODO entries will block switching the parent to DONE.
2752 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2753 be blocked if any prior sibling is not yet done.
2754 Finally, if the parent is blocked because of ordered siblings of its own,
2755 the child will also be blocked."
2756 :set (lambda (var val)
2757 (set var val)
2758 (if val
2759 (add-hook 'org-blocker-hook
2760 'org-block-todo-from-children-or-siblings-or-parent)
2761 (remove-hook 'org-blocker-hook
2762 'org-block-todo-from-children-or-siblings-or-parent)))
2763 :group 'org-todo
2764 :type 'boolean)
2766 (defcustom org-enforce-todo-checkbox-dependencies nil
2767 "Non-nil means unchecked boxes will block switching the parent to DONE.
2768 When this is nil, checkboxes have no influence on switching TODO states.
2769 When non-nil, you first need to check off all check boxes before the TODO
2770 entry can be switched to DONE.
2771 This variable needs to be set before org.el is loaded, and you need to
2772 restart Emacs after a change to make the change effective. The only way
2773 to change is while Emacs is running is through the customize interface."
2774 :set (lambda (var val)
2775 (set var val)
2776 (if val
2777 (add-hook 'org-blocker-hook
2778 'org-block-todo-from-checkboxes)
2779 (remove-hook 'org-blocker-hook
2780 'org-block-todo-from-checkboxes)))
2781 :group 'org-todo
2782 :type 'boolean)
2784 (defcustom org-treat-insert-todo-heading-as-state-change nil
2785 "Non-nil means inserting a TODO heading is treated as state change.
2786 So when the command `\\[org-insert-todo-heading]' is used, state change
2787 logging will apply if appropriate. When nil, the new TODO item will
2788 be inserted directly, and no logging will take place."
2789 :group 'org-todo
2790 :type 'boolean)
2792 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2793 "Non-nil means switching TODO states with S-cursor counts as state change.
2794 This is the default behavior. However, setting this to nil allows a
2795 convenient way to select a TODO state and bypass any logging associated
2796 with that."
2797 :group 'org-todo
2798 :type 'boolean)
2800 (defcustom org-todo-state-tags-triggers nil
2801 "Tag changes that should be triggered by TODO state changes.
2802 This is a list. Each entry is
2804 (state-change (tag . flag) .......)
2806 State-change can be a string with a state, and empty string to indicate the
2807 state that has no TODO keyword, or it can be one of the symbols `todo'
2808 or `done', meaning any not-done or done state, respectively."
2809 :group 'org-todo
2810 :group 'org-tags
2811 :type '(repeat
2812 (cons (choice :tag "When changing to"
2813 (const :tag "Not-done state" todo)
2814 (const :tag "Done state" done)
2815 (string :tag "State"))
2816 (repeat
2817 (cons :tag "Tag action"
2818 (string :tag "Tag")
2819 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2821 (defcustom org-log-done nil
2822 "Information to record when a task moves to the DONE state.
2824 Possible values are:
2826 nil Don't add anything, just change the keyword
2827 time Add a time stamp to the task
2828 note Prompt for a note and add it with template `org-log-note-headings'
2830 This option can also be set with on a per-file-basis with
2832 #+STARTUP: nologdone
2833 #+STARTUP: logdone
2834 #+STARTUP: lognotedone
2836 You can have local logging settings for a subtree by setting the LOGGING
2837 property to one or more of these keywords."
2838 :group 'org-todo
2839 :group 'org-progress
2840 :type '(choice
2841 (const :tag "No logging" nil)
2842 (const :tag "Record CLOSED timestamp" time)
2843 (const :tag "Record CLOSED timestamp with note." note)))
2845 ;; Normalize old uses of org-log-done.
2846 (cond
2847 ((eq org-log-done t) (setq org-log-done 'time))
2848 ((and (listp org-log-done) (memq 'done org-log-done))
2849 (setq org-log-done 'note)))
2851 (defcustom org-log-reschedule nil
2852 "Information to record when the scheduling date of a tasks is modified.
2854 Possible values are:
2856 nil Don't add anything, just change the date
2857 time Add a time stamp to the task
2858 note Prompt for a note and add it with template `org-log-note-headings'
2860 This option can also be set with on a per-file-basis with
2862 #+STARTUP: nologreschedule
2863 #+STARTUP: logreschedule
2864 #+STARTUP: lognotereschedule"
2865 :group 'org-todo
2866 :group 'org-progress
2867 :type '(choice
2868 (const :tag "No logging" nil)
2869 (const :tag "Record timestamp" time)
2870 (const :tag "Record timestamp with note." note)))
2872 (defcustom org-log-redeadline nil
2873 "Information to record when the deadline date of a tasks is modified.
2875 Possible values are:
2877 nil Don't add anything, just change the date
2878 time Add a time stamp to the task
2879 note Prompt for a note and add it with template `org-log-note-headings'
2881 This option can also be set with on a per-file-basis with
2883 #+STARTUP: nologredeadline
2884 #+STARTUP: logredeadline
2885 #+STARTUP: lognoteredeadline
2887 You can have local logging settings for a subtree by setting the LOGGING
2888 property to one or more of these keywords."
2889 :group 'org-todo
2890 :group 'org-progress
2891 :type '(choice
2892 (const :tag "No logging" nil)
2893 (const :tag "Record timestamp" time)
2894 (const :tag "Record timestamp with note." note)))
2896 (defcustom org-log-note-clock-out nil
2897 "Non-nil means record a note when clocking out of an item.
2898 This can also be configured on a per-file basis by adding one of
2899 the following lines anywhere in the buffer:
2901 #+STARTUP: lognoteclock-out
2902 #+STARTUP: nolognoteclock-out"
2903 :group 'org-todo
2904 :group 'org-progress
2905 :type 'boolean)
2907 (defcustom org-log-done-with-time t
2908 "Non-nil means the CLOSED time stamp will contain date and time.
2909 When nil, only the date will be recorded."
2910 :group 'org-progress
2911 :type 'boolean)
2913 (defcustom org-log-note-headings
2914 '((done . "CLOSING NOTE %t")
2915 (state . "State %-12s from %-12S %t")
2916 (note . "Note taken on %t")
2917 (reschedule . "Rescheduled from %S on %t")
2918 (delschedule . "Not scheduled, was %S on %t")
2919 (redeadline . "New deadline from %S on %t")
2920 (deldeadline . "Removed deadline, was %S on %t")
2921 (refile . "Refiled on %t")
2922 (clock-out . ""))
2923 "Headings for notes added to entries.
2925 The value is an alist, with the car being a symbol indicating the
2926 note context, and the cdr is the heading to be used. The heading
2927 may also be the empty string. The following placeholders can be
2928 used:
2930 %t a time stamp.
2931 %T an active time stamp instead the default inactive one
2932 %d a short-format time stamp.
2933 %D an active short-format time stamp.
2934 %s the new TODO state or time stamp (inactive), in double quotes.
2935 %S the old TODO state or time stamp (inactive), in double quotes.
2936 %u the user name.
2937 %U full user name.
2939 In fact, it is not a good idea to change the `state' entry,
2940 because Agenda Log mode depends on the format of these entries."
2941 :group 'org-todo
2942 :group 'org-progress
2943 :type '(list :greedy t
2944 (cons (const :tag "Heading when closing an item" done) string)
2945 (cons (const :tag
2946 "Heading when changing todo state (todo sequence only)"
2947 state) string)
2948 (cons (const :tag "Heading when just taking a note" note) string)
2949 (cons (const :tag "Heading when rescheduling" reschedule) string)
2950 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2951 (cons (const :tag "Heading when changing deadline" redeadline) string)
2952 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2953 (cons (const :tag "Heading when refiling" refile) string)
2954 (cons (const :tag "Heading when clocking out" clock-out) string)))
2956 (unless (assq 'note org-log-note-headings)
2957 (push '(note . "%t") org-log-note-headings))
2959 (defcustom org-log-into-drawer nil
2960 "Non-nil means insert state change notes and time stamps into a drawer.
2961 When nil, state changes notes will be inserted after the headline and
2962 any scheduling and clock lines, but not inside a drawer.
2964 The value of this variable should be the name of the drawer to use.
2965 LOGBOOK is proposed as the default drawer for this purpose, you can
2966 also set this to a string to define the drawer of your choice.
2968 A value of t is also allowed, representing \"LOGBOOK\".
2970 A value of t or nil can also be set with on a per-file-basis with
2972 #+STARTUP: logdrawer
2973 #+STARTUP: nologdrawer
2975 If this variable is set, `org-log-state-notes-insert-after-drawers'
2976 will be ignored.
2978 You can set the property LOG_INTO_DRAWER to overrule this setting for
2979 a subtree.
2981 Do not check directly this variable in a Lisp program. Call
2982 function `org-log-into-drawer' instead."
2983 :group 'org-todo
2984 :group 'org-progress
2985 :type '(choice
2986 (const :tag "Not into a drawer" nil)
2987 (const :tag "LOGBOOK" t)
2988 (string :tag "Other")))
2990 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2992 (defun org-log-into-drawer ()
2993 "Name of the log drawer, as a string, or nil.
2994 This is the value of `org-log-into-drawer'. However, if the
2995 current entry has or inherits a LOG_INTO_DRAWER property, it will
2996 be used instead of the default value."
2997 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2998 (cond ((equal p "nil") nil)
2999 ((equal p "t") "LOGBOOK")
3000 ((stringp p) p)
3001 (p "LOGBOOK")
3002 ((stringp org-log-into-drawer) org-log-into-drawer)
3003 (org-log-into-drawer "LOGBOOK"))))
3005 (defcustom org-log-state-notes-insert-after-drawers nil
3006 "Non-nil means insert state change notes after any drawers in entry.
3007 Only the drawers that *immediately* follow the headline and the
3008 deadline/scheduled line are skipped.
3009 When nil, insert notes right after the heading and perhaps the line
3010 with deadline/scheduling if present.
3012 This variable will have no effect if `org-log-into-drawer' is
3013 set."
3014 :group 'org-todo
3015 :group 'org-progress
3016 :type 'boolean)
3018 (defcustom org-log-states-order-reversed t
3019 "Non-nil means the latest state note will be directly after heading.
3020 When nil, the state change notes will be ordered according to time.
3022 This option can also be set with on a per-file-basis with
3024 #+STARTUP: logstatesreversed
3025 #+STARTUP: nologstatesreversed"
3026 :group 'org-todo
3027 :group 'org-progress
3028 :type 'boolean)
3030 (defcustom org-todo-repeat-to-state nil
3031 "The TODO state to which a repeater should return the repeating task.
3032 By default this is the first task of a TODO sequence or the
3033 previous state of a TYPE_TODO set. But you can specify to use
3034 the previous state in a TODO sequence or a string.
3036 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3037 entry, which has precedence over this option."
3038 :group 'org-todo
3039 :version "24.1"
3040 :type '(choice (const :tag "Use the previous TODO state" t)
3041 (const :tag "Use the head of the TODO sequence" nil)
3042 (string :tag "Use a specific TODO state")))
3044 (defcustom org-log-repeat 'time
3045 "Non-nil means record moving through the DONE state when triggering repeat.
3046 An auto-repeating task is immediately switched back to TODO when
3047 marked DONE. If you are not logging state changes (by adding \"@\"
3048 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3049 record a closing note, there will be no record of the task moving
3050 through DONE. This variable forces taking a note anyway.
3052 nil Don't force a record
3053 time Record a time stamp
3054 note Prompt for a note and add it with template `org-log-note-headings'
3056 This option can also be set with on a per-file-basis with
3058 #+STARTUP: nologrepeat
3059 #+STARTUP: logrepeat
3060 #+STARTUP: lognoterepeat
3062 You can have local logging settings for a subtree by setting the LOGGING
3063 property to one or more of these keywords."
3064 :group 'org-todo
3065 :group 'org-progress
3066 :type '(choice
3067 (const :tag "Don't force a record" nil)
3068 (const :tag "Force recording the DONE state" time)
3069 (const :tag "Force recording a note with the DONE state" note)))
3072 (defgroup org-priorities nil
3073 "Priorities in Org mode."
3074 :tag "Org Priorities"
3075 :group 'org-todo)
3077 (defcustom org-enable-priority-commands t
3078 "Non-nil means priority commands are active.
3079 When nil, these commands will be disabled, so that you never accidentally
3080 set a priority."
3081 :group 'org-priorities
3082 :type 'boolean)
3084 (defcustom org-highest-priority ?A
3085 "The highest priority of TODO items. A character like ?A, ?B etc.
3086 Must have a smaller ASCII number than `org-lowest-priority'."
3087 :group 'org-priorities
3088 :type 'character)
3090 (defcustom org-lowest-priority ?C
3091 "The lowest priority of TODO items. A character like ?A, ?B etc.
3092 Must have a larger ASCII number than `org-highest-priority'."
3093 :group 'org-priorities
3094 :type 'character)
3096 (defcustom org-default-priority ?B
3097 "The default priority of TODO items.
3098 This is the priority an item gets if no explicit priority is given.
3099 When starting to cycle on an empty priority the first step in the cycle
3100 depends on `org-priority-start-cycle-with-default'. The resulting first
3101 step priority must not exceed the range from `org-highest-priority' to
3102 `org-lowest-priority' which means that `org-default-priority' has to be
3103 in this range exclusive or inclusive the range boundaries. Else the
3104 first step refuses to set the default and the second will fall back
3105 to (depending on the command used) the highest or lowest priority."
3106 :group 'org-priorities
3107 :type 'character)
3109 (defcustom org-priority-start-cycle-with-default t
3110 "Non-nil means start with default priority when starting to cycle.
3111 When this is nil, the first step in the cycle will be (depending on the
3112 command used) one higher or lower than the default priority.
3113 See also `org-default-priority'."
3114 :group 'org-priorities
3115 :type 'boolean)
3117 (defcustom org-get-priority-function nil
3118 "Function to extract the priority from a string.
3119 The string is normally the headline. If this is nil Org computes the
3120 priority from the priority cookie like [#A] in the headline. It returns
3121 an integer, increasing by 1000 for each priority level.
3122 The user can set a different function here, which should take a string
3123 as an argument and return the numeric priority."
3124 :group 'org-priorities
3125 :version "24.1"
3126 :type '(choice
3127 (const nil)
3128 (function)))
3130 (defgroup org-time nil
3131 "Options concerning time stamps and deadlines in Org mode."
3132 :tag "Org Time"
3133 :group 'org)
3135 (defcustom org-time-stamp-rounding-minutes '(0 5)
3136 "Number of minutes to round time stamps to.
3137 \\<org-mode-map>\
3138 These are two values, the first applies when first creating a time stamp.
3139 The second applies when changing it with the commands `S-up' and `S-down'.
3140 When changing the time stamp, this means that it will change in steps
3141 of N minutes, as given by the second value.
3143 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3144 numbers should be factors of 60, so for example 5, 10, 15.
3146 When this is larger than 1, you can still force an exact time stamp by using
3147 a double prefix argument to a time stamp command like \
3148 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3149 and by using a prefix arg to `S-up/down' to specify the exact number
3150 of minutes to shift."
3151 :group 'org-time
3152 :get (lambda (var) ; Make sure both elements are there
3153 (if (integerp (default-value var))
3154 (list (default-value var) 5)
3155 (default-value var)))
3156 :type '(list
3157 (integer :tag "when inserting times")
3158 (integer :tag "when modifying times")))
3160 ;; Normalize old customizations of this variable.
3161 (when (integerp org-time-stamp-rounding-minutes)
3162 (setq org-time-stamp-rounding-minutes
3163 (list org-time-stamp-rounding-minutes
3164 org-time-stamp-rounding-minutes)))
3166 (defcustom org-display-custom-times nil
3167 "Non-nil means overlay custom formats over all time stamps.
3168 The formats are defined through the variable `org-time-stamp-custom-formats'.
3169 To turn this on on a per-file basis, insert anywhere in the file:
3170 #+STARTUP: customtime"
3171 :group 'org-time
3172 :set 'set-default
3173 :type 'sexp)
3174 (make-variable-buffer-local 'org-display-custom-times)
3176 (defcustom org-time-stamp-custom-formats
3177 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3178 "Custom formats for time stamps. See `format-time-string' for the syntax.
3179 These are overlaid over the default ISO format if the variable
3180 `org-display-custom-times' is set. Time like %H:%M should be at the
3181 end of the second format. The custom formats are also honored by export
3182 commands, if custom time display is turned on at the time of export."
3183 :group 'org-time
3184 :type 'sexp)
3186 (defun org-time-stamp-format (&optional long inactive)
3187 "Get the right format for a time string."
3188 (let ((f (if long (cdr org-time-stamp-formats)
3189 (car org-time-stamp-formats))))
3190 (if inactive
3191 (concat "[" (substring f 1 -1) "]")
3192 f)))
3194 (defcustom org-deadline-warning-days 14
3195 "Number of days before expiration during which a deadline becomes active.
3196 This variable governs the display in sparse trees and in the agenda.
3197 When 0 or negative, it means use this number (the absolute value of it)
3198 even if a deadline has a different individual lead time specified.
3200 Custom commands can set this variable in the options section."
3201 :group 'org-time
3202 :group 'org-agenda-daily/weekly
3203 :type 'integer)
3205 (defcustom org-scheduled-delay-days 0
3206 "Number of days before a scheduled item becomes active.
3207 This variable governs the display in sparse trees and in the agenda.
3208 The default value (i.e. 0) means: don't delay scheduled item.
3209 When negative, it means use this number (the absolute value of it)
3210 even if a scheduled item has a different individual delay time
3211 specified.
3213 Custom commands can set this variable in the options section."
3214 :group 'org-time
3215 :group 'org-agenda-daily/weekly
3216 :version "24.4"
3217 :package-version '(Org . "8.0")
3218 :type 'integer)
3220 (defcustom org-read-date-prefer-future t
3221 "Non-nil means assume future for incomplete date input from user.
3222 This affects the following situations:
3223 1. The user gives a month but not a year.
3224 For example, if it is April and you enter \"feb 2\", this will be read
3225 as Feb 2, *next* year. \"May 5\", however, will be this year.
3226 2. The user gives a day, but no month.
3227 For example, if today is the 15th, and you enter \"3\", Org will read
3228 this as the third of *next* month. However, if you enter \"17\",
3229 it will be considered as *this* month.
3231 If you set this variable to the symbol `time', then also the following
3232 will work:
3234 3. If the user gives a time.
3235 If the time is before now, it will be interpreted as tomorrow.
3237 Currently none of this works for ISO week specifications.
3239 When this option is nil, the current day, month and year will always be
3240 used as defaults.
3242 See also `org-agenda-jump-prefer-future'."
3243 :group 'org-time
3244 :type '(choice
3245 (const :tag "Never" nil)
3246 (const :tag "Check month and day" t)
3247 (const :tag "Check month, day, and time" time)))
3249 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3250 "Should the agenda jump command prefer the future for incomplete dates?
3251 The default is to do the same as configured in `org-read-date-prefer-future'.
3252 But you can also set a deviating value here.
3253 This may t or nil, or the symbol `org-read-date-prefer-future'."
3254 :group 'org-agenda
3255 :group 'org-time
3256 :version "24.1"
3257 :type '(choice
3258 (const :tag "Use org-read-date-prefer-future"
3259 org-read-date-prefer-future)
3260 (const :tag "Never" nil)
3261 (const :tag "Always" t)))
3263 (defcustom org-read-date-force-compatible-dates t
3264 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3266 Depending on the system Emacs is running on, certain dates cannot
3267 be represented with the type used internally to represent time.
3268 Dates between 1970-1-1 and 2038-1-1 can always be represented
3269 correctly. Some systems allow for earlier dates, some for later,
3270 some for both. One way to find out it to insert any date into an
3271 Org buffer, putting the cursor on the year and hitting S-up and
3272 S-down to test the range.
3274 When this variable is set to t, the date/time prompt will not let
3275 you specify dates outside the 1970-2037 range, so it is certain that
3276 these dates will work in whatever version of Emacs you are
3277 running, and also that you can move a file from one Emacs implementation
3278 to another. WHenever Org is forcing the year for you, it will display
3279 a message and beep.
3281 When this variable is nil, Org will check if the date is
3282 representable in the specific Emacs implementation you are using.
3283 If not, it will force a year, usually the current year, and beep
3284 to remind you. Currently this setting is not recommended because
3285 the likelihood that you will open your Org files in an Emacs that
3286 has limited date range is not negligible.
3288 A workaround for this problem is to use diary sexp dates for time
3289 stamps outside of this range."
3290 :group 'org-time
3291 :version "24.1"
3292 :type 'boolean)
3294 (defcustom org-read-date-display-live t
3295 "Non-nil means display current interpretation of date prompt live.
3296 This display will be in an overlay, in the minibuffer."
3297 :group 'org-time
3298 :type 'boolean)
3300 (defcustom org-read-date-popup-calendar t
3301 "Non-nil means pop up a calendar when prompting for a date.
3302 In the calendar, the date can be selected with mouse-1. However, the
3303 minibuffer will also be active, and you can simply enter the date as well.
3304 When nil, only the minibuffer will be available."
3305 :group 'org-time
3306 :type 'boolean)
3307 (defvaralias 'org-popup-calendar-for-date-prompt
3308 'org-read-date-popup-calendar)
3310 (defcustom org-extend-today-until 0
3311 "The hour when your day really ends. Must be an integer.
3312 This has influence for the following applications:
3313 - When switching the agenda to \"today\". It it is still earlier than
3314 the time given here, the day recognized as TODAY is actually yesterday.
3315 - When a date is read from the user and it is still before the time given
3316 here, the current date and time will be assumed to be yesterday, 23:59.
3317 Also, timestamps inserted in capture templates follow this rule.
3319 IMPORTANT: This is a feature whose implementation is and likely will
3320 remain incomplete. Really, it is only here because past midnight seems to
3321 be the favorite working time of John Wiegley :-)"
3322 :group 'org-time
3323 :type 'integer)
3325 (defcustom org-use-effective-time nil
3326 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3327 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3328 \"effective time\" of any timestamps between midnight and 8am will be
3329 23:59 of the previous day."
3330 :group 'org-time
3331 :version "24.1"
3332 :type 'boolean)
3334 (defcustom org-use-last-clock-out-time-as-effective-time nil
3335 "When non-nil, use the last clock out time for `org-todo'.
3336 Note that this option has precedence over the combined use of
3337 `org-use-effective-time' and `org-extend-today-until'."
3338 :group 'org-time
3339 :version "24.4"
3340 :package-version '(Org . "8.0")
3341 :type 'boolean)
3343 (defcustom org-edit-timestamp-down-means-later nil
3344 "Non-nil means S-down will increase the time in a time stamp.
3345 When nil, S-up will increase."
3346 :group 'org-time
3347 :type 'boolean)
3349 (defcustom org-calendar-follow-timestamp-change t
3350 "Non-nil means make the calendar window follow timestamp changes.
3351 When a timestamp is modified and the calendar window is visible, it will be
3352 moved to the new date."
3353 :group 'org-time
3354 :type 'boolean)
3356 (defgroup org-tags nil
3357 "Options concerning tags in Org mode."
3358 :tag "Org Tags"
3359 :group 'org)
3361 (defcustom org-tag-alist nil
3362 "Default tags available in Org files.
3364 The value of this variable is an alist. Associations either:
3366 (TAG)
3367 (TAG . SELECT)
3368 (SPECIAL)
3370 where TAG is a tag as a string, SELECT is character, used to
3371 select that tag through the fast tag selection interface, and
3372 SPECIAL is one of the following keywords: `:startgroup',
3373 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3374 `:newline'. These keywords are used to define a hierarchy of
3375 tags. See manual for details.
3377 When this variable is nil, Org mode bases tag input on what is
3378 already in the buffer. The value can be overridden locally by
3379 using a TAGS keyword, e.g.,
3381 #+TAGS: tag1 tag2
3383 See also `org-tag-persistent-alist' to sidestep this behavior."
3384 :group 'org-tags
3385 :type '(repeat
3386 (choice
3387 (cons :tag "Tag with key"
3388 (string :tag "Tag name")
3389 (character :tag "Access char"))
3390 (list :tag "Tag" (string :tag "Tag name"))
3391 (const :tag "Start radio group" (:startgroup))
3392 (const :tag "Start tag group, non distinct" (:startgrouptag))
3393 (const :tag "Group tags delimiter" (:grouptags))
3394 (const :tag "End radio group" (:endgroup))
3395 (const :tag "End tag group, non distinct" (:endgrouptag))
3396 (const :tag "New line" (:newline)))))
3398 (defcustom org-tag-persistent-alist nil
3399 "Tags always available in Org files.
3401 The value of this variable is an alist. Associations either:
3403 (TAG)
3404 (TAG . SELECT)
3405 (SPECIAL)
3407 where TAG is a tag as a string, SELECT is a character, used to
3408 select that tag through the fast tag selection interface, and
3409 SPECIAL is one of the following keywords: `:startgroup',
3410 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3411 `:newline'. These keywords are used to define a hierarchy of
3412 tags. See manual for details.
3414 Unlike to `org-tag-alist', tags defined in this variable do not
3415 depend on a local TAGS keyword. Instead, to disable these tags
3416 on a per-file basis, insert anywhere in the file:
3418 #+STARTUP: noptag"
3419 :group 'org-tags
3420 :type '(repeat
3421 (choice
3422 (cons :tag "Tag with key"
3423 (string :tag "Tag name")
3424 (character :tag "Access char"))
3425 (list :tag "Tag" (string :tag "Tag name"))
3426 (const :tag "Start radio group" (:startgroup))
3427 (const :tag "Start tag group, non distinct" (:startgrouptag))
3428 (const :tag "Group tags delimiter" (:grouptags))
3429 (const :tag "End radio group" (:endgroup))
3430 (const :tag "End tag group, non distinct" (:endgrouptag))
3431 (const :tag "New line" (:newline)))))
3433 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3434 "If non-nil, always offer completion for all tags of all agenda files.
3435 Instead of customizing this variable directly, you might want to
3436 set it locally for capture buffers, because there no list of
3437 tags in that file can be created dynamically (there are none).
3439 (add-hook \\='org-capture-mode-hook
3440 (lambda ()
3441 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3442 :group 'org-tags
3443 :version "24.1"
3444 :type 'boolean)
3446 (defvar org-file-tags nil
3447 "List of tags that can be inherited by all entries in the file.
3448 The tags will be inherited if the variable `org-use-tag-inheritance'
3449 says they should be.
3450 This variable is populated from #+FILETAGS lines.")
3452 (defcustom org-use-fast-tag-selection 'auto
3453 "Non-nil means use fast tag selection scheme.
3454 This is a special interface to select and deselect tags with single keys.
3455 When nil, fast selection is never used.
3456 When the symbol `auto', fast selection is used if and only if selection
3457 characters for tags have been configured, either through the variable
3458 `org-tag-alist' or through a #+TAGS line in the buffer.
3459 When t, fast selection is always used and selection keys are assigned
3460 automatically if necessary."
3461 :group 'org-tags
3462 :type '(choice
3463 (const :tag "Always" t)
3464 (const :tag "Never" nil)
3465 (const :tag "When selection characters are configured" auto)))
3467 (defcustom org-fast-tag-selection-single-key nil
3468 "Non-nil means fast tag selection exits after first change.
3469 When nil, you have to press RET to exit it.
3470 During fast tag selection, you can toggle this flag with `C-c'.
3471 This variable can also have the value `expert'. In this case, the window
3472 displaying the tags menu is not even shown, until you press C-c again."
3473 :group 'org-tags
3474 :type '(choice
3475 (const :tag "No" nil)
3476 (const :tag "Yes" t)
3477 (const :tag "Expert" expert)))
3479 (defvar org-fast-tag-selection-include-todo nil
3480 "Non-nil means fast tags selection interface will also offer TODO states.
3481 This is an undocumented feature, you should not rely on it.")
3483 (defcustom org-tags-column -77
3484 "The column to which tags should be indented in a headline.
3485 If this number is positive, it specifies the column. If it is negative,
3486 it means that the tags should be flushright to that column. For example,
3487 -80 works well for a normal 80 character screen.
3488 When 0, place tags directly after headline text, with only one space in
3489 between."
3490 :group 'org-tags
3491 :type 'integer)
3493 (defcustom org-auto-align-tags t
3494 "Non-nil keeps tags aligned when modifying headlines.
3495 Some operations (i.e. demoting) change the length of a headline and
3496 therefore shift the tags around. With this option turned on, after
3497 each such operation the tags are again aligned to `org-tags-column'."
3498 :group 'org-tags
3499 :type 'boolean)
3501 (defcustom org-use-tag-inheritance t
3502 "Non-nil means tags in levels apply also for sublevels.
3503 When nil, only the tags directly given in a specific line apply there.
3504 This may also be a list of tags that should be inherited, or a regexp that
3505 matches tags that should be inherited. Additional control is possible
3506 with the variable `org-tags-exclude-from-inheritance' which gives an
3507 explicit list of tags to be excluded from inheritance, even if the value of
3508 `org-use-tag-inheritance' would select it for inheritance.
3510 If this option is t, a match early-on in a tree can lead to a large
3511 number of matches in the subtree when constructing the agenda or creating
3512 a sparse tree. If you only want to see the first match in a tree during
3513 a search, check out the variable `org-tags-match-list-sublevels'."
3514 :group 'org-tags
3515 :type '(choice
3516 (const :tag "Not" nil)
3517 (const :tag "Always" t)
3518 (repeat :tag "Specific tags" (string :tag "Tag"))
3519 (regexp :tag "Tags matched by regexp")))
3521 (defcustom org-tags-exclude-from-inheritance nil
3522 "List of tags that should never be inherited.
3523 This is a way to exclude a few tags from inheritance. For way to do
3524 the opposite, to actively allow inheritance for selected tags,
3525 see the variable `org-use-tag-inheritance'."
3526 :group 'org-tags
3527 :type '(repeat (string :tag "Tag")))
3529 (defun org-tag-inherit-p (tag)
3530 "Check if TAG is one that should be inherited."
3531 (cond
3532 ((member tag org-tags-exclude-from-inheritance) nil)
3533 ((eq org-use-tag-inheritance t) t)
3534 ((not org-use-tag-inheritance) nil)
3535 ((stringp org-use-tag-inheritance)
3536 (string-match org-use-tag-inheritance tag))
3537 ((listp org-use-tag-inheritance)
3538 (member tag org-use-tag-inheritance))
3539 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3541 (defcustom org-tags-match-list-sublevels t
3542 "Non-nil means list also sublevels of headlines matching a search.
3543 This variable applies to tags/property searches, and also to stuck
3544 projects because this search is based on a tags match as well.
3546 When set to the symbol `indented', sublevels are indented with
3547 leading dots.
3549 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3550 the sublevels of a headline matching a tag search often also match
3551 the same search. Listing all of them can create very long lists.
3552 Setting this variable to nil causes subtrees of a match to be skipped.
3554 This variable is semi-obsolete and probably should always be true. It
3555 is better to limit inheritance to certain tags using the variables
3556 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "No, don't list them" nil)
3560 (const :tag "Yes, do list them" t)
3561 (const :tag "List them, indented with leading dots" indented)))
3563 (defcustom org-tags-sort-function nil
3564 "When set, tags are sorted using this function as a comparator."
3565 :group 'org-tags
3566 :type '(choice
3567 (const :tag "No sorting" nil)
3568 (const :tag "Alphabetical" org-string-collate-lessp)
3569 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3570 (function :tag "Custom function" nil)))
3572 (defvar org-tags-history nil
3573 "History of minibuffer reads for tags.")
3574 (defvar org-last-tags-completion-table nil
3575 "The last used completion table for tags.")
3576 (defvar org-after-tags-change-hook nil
3577 "Hook that is run after the tags in a line have changed.")
3579 (defgroup org-properties nil
3580 "Options concerning properties in Org mode."
3581 :tag "Org Properties"
3582 :group 'org)
3584 (defcustom org-property-format "%-10s %s"
3585 "How property key/value pairs should be formatted by `indent-line'.
3586 When `indent-line' hits a property definition, it will format the line
3587 according to this format, mainly to make sure that the values are
3588 lined-up with respect to each other."
3589 :group 'org-properties
3590 :type 'string)
3592 (defcustom org-properties-postprocess-alist nil
3593 "Alist of properties and functions to adjust inserted values.
3594 Elements of this alist must be of the form
3596 ([string] [function])
3598 where [string] must be a property name and [function] must be a
3599 lambda expression: this lambda expression must take one argument,
3600 the value to adjust, and return the new value as a string.
3602 For example, this element will allow the property \"Remaining\"
3603 to be updated wrt the relation between the \"Effort\" property
3604 and the clock summary:
3606 ((\"Remaining\" (lambda(value)
3607 (let ((clocksum (org-clock-sum-current-item))
3608 (effort (org-duration-to-minutes
3609 (org-entry-get (point) \"Effort\"))))
3610 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3611 :group 'org-properties
3612 :version "24.1"
3613 :type '(alist :key-type (string :tag "Property")
3614 :value-type (function :tag "Function")))
3616 (defcustom org-use-property-inheritance nil
3617 "Non-nil means properties apply also for sublevels.
3619 This setting is chiefly used during property searches. Turning it on can
3620 cause significant overhead when doing a search, which is why it is not
3621 on by default.
3623 When nil, only the properties directly given in the current entry count.
3624 When t, every property is inherited. The value may also be a list of
3625 properties that should have inheritance, or a regular expression matching
3626 properties that should be inherited.
3628 However, note that some special properties use inheritance under special
3629 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3630 and the properties ending in \"_ALL\" when they are used as descriptor
3631 for valid values of a property.
3633 Note for programmers:
3634 When querying an entry with `org-entry-get', you can control if inheritance
3635 should be used. By default, `org-entry-get' looks only at the local
3636 properties. You can request inheritance by setting the inherit argument
3637 to t (to force inheritance) or to `selective' (to respect the setting
3638 in this variable)."
3639 :group 'org-properties
3640 :type '(choice
3641 (const :tag "Not" nil)
3642 (const :tag "Always" t)
3643 (repeat :tag "Specific properties" (string :tag "Property"))
3644 (regexp :tag "Properties matched by regexp")))
3646 (defun org-property-inherit-p (property)
3647 "Return a non-nil value if PROPERTY should be inherited."
3648 (cond
3649 ((eq org-use-property-inheritance t) t)
3650 ((not org-use-property-inheritance) nil)
3651 ((stringp org-use-property-inheritance)
3652 (string-match org-use-property-inheritance property))
3653 ((listp org-use-property-inheritance)
3654 (member-ignore-case property org-use-property-inheritance))
3655 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3657 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3658 "The default column format, if no other format has been defined.
3659 This variable can be set on the per-file basis by inserting a line
3661 #+COLUMNS: %25ITEM ....."
3662 :group 'org-properties
3663 :type 'string)
3665 (defcustom org-columns-ellipses ".."
3666 "The ellipses to be used when a field in column view is truncated.
3667 When this is the empty string, as many characters as possible are shown,
3668 but then there will be no visual indication that the field has been truncated.
3669 When this is a string of length N, the last N characters of a truncated
3670 field are replaced by this string. If the column is narrower than the
3671 ellipses string, only part of the ellipses string will be shown."
3672 :group 'org-properties
3673 :type 'string)
3675 (defconst org-global-properties-fixed
3676 '(("VISIBILITY_ALL" . "folded children content all")
3677 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3678 "List of property/value pairs that can be inherited by any entry.
3680 These are fixed values, for the preset properties. The user variable
3681 that can be used to add to this list is `org-global-properties'.
3683 The entries in this list are cons cells where the car is a property
3684 name and cdr is a string with the value. If the value represents
3685 multiple items like an \"_ALL\" property, separate the items by
3686 spaces.")
3688 (defcustom org-global-properties nil
3689 "List of property/value pairs that can be inherited by any entry.
3691 This list will be combined with the constant `org-global-properties-fixed'.
3693 The entries in this list are cons cells where the car is a property
3694 name and cdr is a string with the value.
3696 You can set buffer-local values for the same purpose in the variable
3697 `org-file-properties' this by adding lines like
3699 #+PROPERTY: NAME VALUE"
3700 :group 'org-properties
3701 :type '(repeat
3702 (cons (string :tag "Property")
3703 (string :tag "Value"))))
3705 (defvar-local org-file-properties nil
3706 "List of property/value pairs that can be inherited by any entry.
3707 Valid for the current buffer.
3708 This variable is populated from #+PROPERTY lines.")
3710 (defgroup org-agenda nil
3711 "Options concerning agenda views in Org mode."
3712 :tag "Org Agenda"
3713 :group 'org)
3715 (defvar-local org-category nil
3716 "Variable used by Org files to set a category for agenda display.
3717 Such files should use a file variable to set it, for example
3719 # -*- mode: org; org-category: \"ELisp\"
3721 or contain a special line
3723 #+CATEGORY: ELisp
3725 If the file does not specify a category, then file's base name
3726 is used instead.")
3727 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3729 (defcustom org-agenda-files nil
3730 "The files to be used for agenda display.
3732 If an entry is a directory, all files in that directory that are matched
3733 by `org-agenda-file-regexp' will be part of the file list.
3735 If the value of the variable is not a list but a single file name, then
3736 the list of agenda files is actually stored and maintained in that file,
3737 one agenda file per line. In this file paths can be given relative to
3738 `org-directory'. Tilde expansion and environment variable substitution
3739 are also made.
3741 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3742 and removed with `\\[org-remove-file]'."
3743 :group 'org-agenda
3744 :type '(choice
3745 (repeat :tag "List of files and directories" file)
3746 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3748 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3749 "Regular expression to match files for `org-agenda-files'.
3750 If any element in the list in that variable contains a directory instead
3751 of a normal file, all files in that directory that are matched by this
3752 regular expression will be included."
3753 :group 'org-agenda
3754 :type 'regexp)
3756 (defcustom org-agenda-text-search-extra-files nil
3757 "List of extra files to be searched by text search commands.
3758 These files will be searched in addition to the agenda files by the
3759 commands `org-search-view' (`\\[org-agenda] s') \
3760 and `org-occur-in-agenda-files'.
3761 Note that these files will only be searched for text search commands,
3762 not for the other agenda views like todo lists, tag searches or the weekly
3763 agenda. This variable is intended to list notes and possibly archive files
3764 that should also be searched by these two commands.
3765 In fact, if the first element in the list is the symbol `agenda-archives',
3766 then all archive files of all agenda files will be added to the search
3767 scope."
3768 :group 'org-agenda
3769 :type '(set :greedy t
3770 (const :tag "Agenda Archives" agenda-archives)
3771 (repeat :inline t (file))))
3773 (defvaralias 'org-agenda-multi-occur-extra-files
3774 'org-agenda-text-search-extra-files)
3776 (defcustom org-agenda-skip-unavailable-files nil
3777 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3778 A nil value means to remove them, after a query, from the list."
3779 :group 'org-agenda
3780 :type 'boolean)
3782 (defcustom org-agenda-diary-file 'diary-file
3783 "File to which to add new entries with the `i' key in agenda and calendar.
3784 When this is the symbol `diary-file', the functionality in the Emacs
3785 calendar will be used to add entries to the `diary-file'. But when this
3786 points to a file, `org-agenda-diary-entry' will be used instead."
3787 :group 'org-agenda
3788 :type '(choice
3789 (const :tag "The standard Emacs diary file" diary-file)
3790 (file :tag "Special Org file diary entries")))
3792 (defgroup org-latex nil
3793 "Options for embedding LaTeX code into Org mode."
3794 :tag "Org LaTeX"
3795 :group 'org)
3797 (defcustom org-format-latex-options
3798 '(:foreground default :background default :scale 1.0
3799 :html-foreground "Black" :html-background "Transparent"
3800 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3801 "Options for creating images from LaTeX fragments.
3802 This is a property list with the following properties:
3803 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3804 `default' means use the foreground of the default face.
3805 `auto' means use the foreground from the text face.
3806 :background the background color, or \"Transparent\".
3807 `default' means use the background of the default face.
3808 `auto' means use the background from the text face.
3809 :scale a scaling factor for the size of the images, to get more pixels
3810 :html-foreground, :html-background, :html-scale
3811 the same numbers for HTML export.
3812 :matchers a list indicating which matchers should be used to
3813 find LaTeX fragments. Valid members of this list are:
3814 \"begin\" find environments
3815 \"$1\" find single characters surrounded by $.$
3816 \"$\" find math expressions surrounded by $...$
3817 \"$$\" find math expressions surrounded by $$....$$
3818 \"\\(\" find math expressions surrounded by \\(...\\)
3819 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3820 :group 'org-latex
3821 :type 'plist)
3823 (defcustom org-format-latex-signal-error t
3824 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3825 When nil, just push out a message."
3826 :group 'org-latex
3827 :version "24.1"
3828 :type 'boolean)
3830 (defcustom org-latex-to-mathml-jar-file nil
3831 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3832 Use this to specify additional executable file say a jar file.
3834 When using MathToWeb as the converter, specify the full-path to
3835 your mathtoweb.jar file."
3836 :group 'org-latex
3837 :version "24.1"
3838 :type '(choice
3839 (const :tag "None" nil)
3840 (file :tag "JAR file" :must-match t)))
3842 (defcustom org-latex-to-mathml-convert-command nil
3843 "Command to convert LaTeX fragments to MathML.
3844 Replace format-specifiers in the command as noted below and use
3845 `shell-command' to convert LaTeX to MathML.
3846 %j: Executable file in fully expanded form as specified by
3847 `org-latex-to-mathml-jar-file'.
3848 %I: Input LaTeX file in fully expanded form.
3849 %i: The latex fragment to be converted.
3850 %o: Output MathML file.
3852 This command is used by `org-create-math-formula'.
3854 When using MathToWeb as the converter, set this option to
3855 \"java -jar %j -unicode -force -df %o %I\".
3857 When using LaTeXML set this option to
3858 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3859 :group 'org-latex
3860 :version "24.1"
3861 :type '(choice
3862 (const :tag "None" nil)
3863 (string :tag "\nShell command")))
3865 (defcustom org-preview-latex-default-process 'dvipng
3866 "The default process to convert LaTeX fragments to image files.
3867 All available processes and theirs documents can be found in
3868 `org-preview-latex-process-alist', which see."
3869 :group 'org-latex
3870 :version "26.1"
3871 :package-version '(Org . "9.0")
3872 :type 'symbol)
3874 (defcustom org-preview-latex-process-alist
3875 '((dvipng
3876 :programs ("latex" "dvipng")
3877 :description "dvi > png"
3878 :message "you need to install the programs: latex and dvipng."
3879 :image-input-type "dvi"
3880 :image-output-type "png"
3881 :image-size-adjust (1.0 . 1.0)
3882 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3883 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3884 (dvisvgm
3885 :programs ("latex" "dvisvgm")
3886 :description "dvi > svg"
3887 :message "you need to install the programs: latex and dvisvgm."
3888 :use-xcolor t
3889 :image-input-type "dvi"
3890 :image-output-type "svg"
3891 :image-size-adjust (1.7 . 1.5)
3892 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3893 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3894 (imagemagick
3895 :programs ("latex" "convert")
3896 :description "pdf > png"
3897 :message "you need to install the programs: latex and imagemagick."
3898 :use-xcolor t
3899 :image-input-type "pdf"
3900 :image-output-type "png"
3901 :image-size-adjust (1.0 . 1.0)
3902 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3903 :image-converter
3904 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3905 "Definitions of external processes for LaTeX previewing.
3906 Org mode can use some external commands to generate TeX snippet's images for
3907 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3908 `org-create-formula-image' how to call them.
3910 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3911 PROPERTIES accepts the following attributes:
3913 :programs list of strings, required programs.
3914 :description string, describe the process.
3915 :message string, message it when required programs cannot be found.
3916 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3917 :image-output-type string, output file type of image converter (e.g., \"png\").
3918 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3919 deal with background and foreground color of image.
3920 Otherwise, dvipng style background and foreground color
3921 format are generated. You may then refer to them in
3922 command options with \"%F\" and \"%B\".
3923 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3924 image size showed in buffer and the cdr element is for
3925 HTML file. This option is only useful for process
3926 developers, users should use variable
3927 `org-format-latex-options' instead.
3928 :post-clean list of strings, files matched are to be cleaned up once
3929 the image is generated. When nil, the files with \".dvi\",
3930 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3931 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3932 be cleaned up.
3933 :latex-header list of strings, the LaTeX header of the snippet file.
3934 When nil, the fallback value is used instead, which is
3935 controlled by `org-format-latex-header',
3936 `org-latex-default-packages-alist' and
3937 `org-latex-packages-alist', which see.
3938 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3939 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3940 replaced with values defined below.
3941 :image-converter list of image converter commands strings. Each of them is
3942 given to the shell and supports any of the following
3943 place-holders defined below.
3945 Place-holders used by `:image-converter' and `:latex-compiler':
3947 %f input file name
3948 %b base name of input file
3949 %o base directory of input file
3950 %O absolute output file name
3952 Place-holders only used by `:image-converter':
3954 %F foreground of image
3955 %B background of image
3956 %D dpi, which is used to adjust image size by some processing commands.
3957 %S the image size scale ratio, which is used to adjust image size by some
3958 processing commands."
3959 :group 'org-latex
3960 :version "26.1"
3961 :package-version '(Org . "9.0")
3962 :type '(alist :tag "LaTeX to image backends"
3963 :value-type (plist)))
3965 (defcustom org-preview-latex-image-directory "ltximg/"
3966 "Path to store latex preview images.
3967 A relative path here creates many directories relative to the
3968 processed Org files paths. An absolute path puts all preview
3969 images at the same place."
3970 :group 'org-latex
3971 :version "26.1"
3972 :package-version '(Org . "9.0")
3973 :type 'string)
3975 (defun org-format-latex-mathml-available-p ()
3976 "Return t if `org-latex-to-mathml-convert-command' is usable."
3977 (save-match-data
3978 (when (and (boundp 'org-latex-to-mathml-convert-command)
3979 org-latex-to-mathml-convert-command)
3980 (let ((executable (car (split-string
3981 org-latex-to-mathml-convert-command))))
3982 (when (executable-find executable)
3983 (if (string-match
3984 "%j" org-latex-to-mathml-convert-command)
3985 (file-readable-p org-latex-to-mathml-jar-file)
3986 t))))))
3988 (defcustom org-format-latex-header "\\documentclass{article}
3989 \\usepackage[usenames]{color}
3990 \[PACKAGES]
3991 \[DEFAULT-PACKAGES]
3992 \\pagestyle{empty} % do not remove
3993 % The settings below are copied from fullpage.sty
3994 \\setlength{\\textwidth}{\\paperwidth}
3995 \\addtolength{\\textwidth}{-3cm}
3996 \\setlength{\\oddsidemargin}{1.5cm}
3997 \\addtolength{\\oddsidemargin}{-2.54cm}
3998 \\setlength{\\evensidemargin}{\\oddsidemargin}
3999 \\setlength{\\textheight}{\\paperheight}
4000 \\addtolength{\\textheight}{-\\headheight}
4001 \\addtolength{\\textheight}{-\\headsep}
4002 \\addtolength{\\textheight}{-\\footskip}
4003 \\addtolength{\\textheight}{-3cm}
4004 \\setlength{\\topmargin}{1.5cm}
4005 \\addtolength{\\topmargin}{-2.54cm}"
4006 "The document header used for processing LaTeX fragments.
4007 It is imperative that this header make sure that no page number
4008 appears on the page. The package defined in the variables
4009 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4010 will either replace the placeholder \"[PACKAGES]\" in this
4011 header, or they will be appended."
4012 :group 'org-latex
4013 :type 'string)
4015 (defun org-set-packages-alist (var val)
4016 "Set the packages alist and make sure it has 3 elements per entry."
4017 (set var (mapcar (lambda (x)
4018 (if (and (consp x) (= (length x) 2))
4019 (list (car x) (nth 1 x) t)
4021 val)))
4023 (defun org-get-packages-alist (var)
4024 "Get the packages alist and make sure it has 3 elements per entry."
4025 (mapcar (lambda (x)
4026 (if (and (consp x) (= (length x) 2))
4027 (list (car x) (nth 1 x) t)
4029 (default-value var)))
4031 (defcustom org-latex-default-packages-alist
4032 '(("AUTO" "inputenc" t ("pdflatex"))
4033 ("T1" "fontenc" t ("pdflatex"))
4034 ("" "graphicx" t)
4035 ("" "grffile" t)
4036 ("" "longtable" nil)
4037 ("" "wrapfig" nil)
4038 ("" "rotating" nil)
4039 ("normalem" "ulem" t)
4040 ("" "amsmath" t)
4041 ("" "textcomp" t)
4042 ("" "amssymb" t)
4043 ("" "capt-of" nil)
4044 ("" "hyperref" nil))
4045 "Alist of default packages to be inserted in the header.
4047 Change this only if one of the packages here causes an
4048 incompatibility with another package you are using.
4050 The packages in this list are needed by one part or another of
4051 Org mode to function properly:
4053 - inputenc, fontenc: for basic font and character selection
4054 - graphicx: for including images
4055 - grffile: allow periods and spaces in graphics file names
4056 - longtable: For multipage tables
4057 - wrapfig: for figure placement
4058 - rotating: for sideways figures and tables
4059 - ulem: for underline and strike-through
4060 - amsmath: for subscript and superscript and math environments
4061 - textcomp, amssymb: for various symbols used
4062 for interpreting the entities in `org-entities'. You can skip
4063 some of these packages if you don't use any of their symbols.
4064 - capt-of: for captions outside of floats
4065 - hyperref: for cross references
4067 Therefore you should not modify this variable unless you know
4068 what you are doing. The one reason to change it anyway is that
4069 you might be loading some other package that conflicts with one
4070 of the default packages. Each element is either a cell or
4071 a string.
4073 A cell is of the format
4075 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4077 If SNIPPET-FLAG is non-nil, the package also needs to be included
4078 when compiling LaTeX snippets into images for inclusion into
4079 non-LaTeX output. COMPILERS is a list of compilers that should
4080 include the package, see `org-latex-compiler'. If the document
4081 compiler is not in the list, and the list is non-nil, the package
4082 will not be inserted in the final document.
4084 A string will be inserted as-is in the header of the document."
4085 :group 'org-latex
4086 :group 'org-export-latex
4087 :set 'org-set-packages-alist
4088 :get 'org-get-packages-alist
4089 :version "26.1"
4090 :package-version '(Org . "8.3")
4091 :type '(repeat
4092 (choice
4093 (list :tag "options/package pair"
4094 (string :tag "options")
4095 (string :tag "package")
4096 (boolean :tag "Snippet")
4097 (choice
4098 (const :tag "For all compilers" nil)
4099 (repeat :tag "Allowed compiler" string)))
4100 (string :tag "A line of LaTeX"))))
4102 (defcustom org-latex-packages-alist nil
4103 "Alist of packages to be inserted in every LaTeX header.
4105 These will be inserted after `org-latex-default-packages-alist'.
4106 Each element is either a cell or a string.
4108 A cell is of the format:
4110 (\"options\" \"package\" SNIPPET-FLAG)
4112 SNIPPET-FLAG, when non-nil, indicates that this package is also
4113 needed when turning LaTeX snippets into images for inclusion into
4114 non-LaTeX output.
4116 A string will be inserted as-is in the header of the document.
4118 Make sure that you only list packages here which:
4120 - you want in every file;
4121 - do not conflict with the setup in `org-format-latex-header';
4122 - do not conflict with the default packages in
4123 `org-latex-default-packages-alist'."
4124 :group 'org-latex
4125 :group 'org-export-latex
4126 :set 'org-set-packages-alist
4127 :get 'org-get-packages-alist
4128 :type '(repeat
4129 (choice
4130 (list :tag "options/package pair"
4131 (string :tag "options")
4132 (string :tag "package")
4133 (boolean :tag "Snippet"))
4134 (string :tag "A line of LaTeX"))))
4136 (defgroup org-appearance nil
4137 "Settings for Org mode appearance."
4138 :tag "Org Appearance"
4139 :group 'org)
4141 (defcustom org-level-color-stars-only nil
4142 "Non-nil means fontify only the stars in each headline.
4143 When nil, the entire headline is fontified.
4144 Changing it requires restart of `font-lock-mode' to become effective
4145 also in regions already fontified."
4146 :group 'org-appearance
4147 :type 'boolean)
4149 (defcustom org-hide-leading-stars nil
4150 "Non-nil means hide the first N-1 stars in a headline.
4151 This works by using the face `org-hide' for these stars. This
4152 face is white for a light background, and black for a dark
4153 background. You may have to customize the face `org-hide' to
4154 make this work.
4155 Changing it requires restart of `font-lock-mode' to become effective
4156 also in regions already fontified.
4157 You may also set this on a per-file basis by adding one of the following
4158 lines to the buffer:
4160 #+STARTUP: hidestars
4161 #+STARTUP: showstars"
4162 :group 'org-appearance
4163 :type 'boolean)
4165 (defcustom org-hidden-keywords nil
4166 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4167 For example, a value \\='(title) for this list makes the document's title
4168 appear in the buffer without the initial \"#+TITLE:\" part."
4169 :group 'org-appearance
4170 :version "24.1"
4171 :type '(set (const :tag "#+AUTHOR" author)
4172 (const :tag "#+DATE" date)
4173 (const :tag "#+EMAIL" email)
4174 (const :tag "#+TITLE" title)))
4176 (defcustom org-custom-properties nil
4177 "List of properties (as strings) with a special meaning.
4178 The default use of these custom properties is to let the user
4179 hide them with `org-toggle-custom-properties-visibility'."
4180 :group 'org-properties
4181 :group 'org-appearance
4182 :version "24.3"
4183 :type '(repeat (string :tag "Property Name")))
4185 (defcustom org-fontify-done-headline nil
4186 "Non-nil means change the face of a headline if it is marked DONE.
4187 Normally, only the TODO/DONE keyword indicates the state of a headline.
4188 When this is non-nil, the headline after the keyword is set to the
4189 `org-headline-done' as an additional indication."
4190 :group 'org-appearance
4191 :type 'boolean)
4193 (defcustom org-fontify-emphasized-text t
4194 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4195 Changing this variable requires a restart of Emacs to take effect."
4196 :group 'org-appearance
4197 :type 'boolean)
4199 (defcustom org-fontify-whole-heading-line nil
4200 "Non-nil means fontify the whole line for headings.
4201 This is useful when setting a background color for the
4202 org-level-* faces."
4203 :group 'org-appearance
4204 :type 'boolean)
4206 (defcustom org-highlight-latex-and-related nil
4207 "Non-nil means highlight LaTeX related syntax in the buffer.
4208 When non nil, the value should be a list containing any of the
4209 following symbols:
4210 `latex' Highlight LaTeX snippets and environments.
4211 `script' Highlight subscript and superscript.
4212 `entities' Highlight entities."
4213 :group 'org-appearance
4214 :version "24.4"
4215 :package-version '(Org . "8.0")
4216 :type '(choice
4217 (const :tag "No highlighting" nil)
4218 (set :greedy t :tag "Highlight"
4219 (const :tag "LaTeX snippets and environments" latex)
4220 (const :tag "Subscript and superscript" script)
4221 (const :tag "Entities" entities))))
4223 (defcustom org-hide-emphasis-markers nil
4224 "Non-nil mean font-lock should hide the emphasis marker characters."
4225 :group 'org-appearance
4226 :type 'boolean)
4228 (defcustom org-hide-macro-markers nil
4229 "Non-nil mean font-lock should hide the brackets marking macro calls."
4230 :group 'org-appearance
4231 :type 'boolean)
4233 (defcustom org-pretty-entities nil
4234 "Non-nil means show entities as UTF8 characters.
4235 When nil, the \\name form remains in the buffer."
4236 :group 'org-appearance
4237 :version "24.1"
4238 :type 'boolean)
4240 (defcustom org-pretty-entities-include-sub-superscripts t
4241 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4242 :group 'org-appearance
4243 :version "24.1"
4244 :type 'boolean)
4246 (defvar org-emph-re nil
4247 "Regular expression for matching emphasis.
4248 After a match, the match groups contain these elements:
4249 0 The match of the full regular expression, including the characters
4250 before and after the proper match
4251 1 The character before the proper match, or empty at beginning of line
4252 2 The proper match, including the leading and trailing markers
4253 3 The leading marker like * or /, indicating the type of highlighting
4254 4 The text between the emphasis markers, not including the markers
4255 5 The character after the match, empty at the end of a line")
4257 (defvar org-verbatim-re nil
4258 "Regular expression for matching verbatim text.")
4260 (defvar org-emphasis-regexp-components) ; defined just below
4261 (defvar org-emphasis-alist) ; defined just below
4262 (defun org-set-emph-re (var val)
4263 "Set variable and compute the emphasis regular expression."
4264 (set var val)
4265 (when (and (boundp 'org-emphasis-alist)
4266 (boundp 'org-emphasis-regexp-components)
4267 org-emphasis-alist org-emphasis-regexp-components)
4268 (pcase-let*
4269 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4270 (body (if (<= nl 0) body
4271 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4272 (template
4273 (format (concat "\\([%s]\\|^\\)" ;before markers
4274 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4275 "\\([%s]\\|$\\)") ;after markers
4276 pre border border body border post)))
4277 (setq org-emph-re (format template "*/_+"))
4278 (setq org-verbatim-re (format template "=~")))))
4280 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4281 ;; set this option proved cumbersome. See this message/thread:
4282 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4283 (defvar org-emphasis-regexp-components
4284 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4285 "Components used to build the regular expression for emphasis.
4286 This is a list with five entries. Terminology: In an emphasis string
4287 like \" *strong word* \", we call the initial space PREMATCH, the final
4288 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4289 and \"trong wor\" is the body. The different components in this variable
4290 specify what is allowed/forbidden in each part:
4292 pre Chars allowed as prematch. Beginning of line will be allowed too.
4293 post Chars allowed as postmatch. End of line will be allowed too.
4294 border The chars *forbidden* as border characters.
4295 body-regexp A regexp like \".\" to match a body character. Don't use
4296 non-shy groups here, and don't allow newline here.
4297 newline The maximum number of newlines allowed in an emphasis exp.
4299 You need to reload Org or to restart Emacs after setting this.")
4301 (defcustom org-emphasis-alist
4302 '(("*" bold)
4303 ("/" italic)
4304 ("_" underline)
4305 ("=" org-verbatim verbatim)
4306 ("~" org-code verbatim)
4307 ("+" (:strike-through t)))
4308 "Alist of characters and faces to emphasize text.
4309 Text starting and ending with a special character will be emphasized,
4310 for example *bold*, _underlined_ and /italic/. This variable sets the
4311 marker characters and the face to be used by font-lock for highlighting
4312 in Org buffers.
4314 You need to reload Org or to restart Emacs after customizing this."
4315 :group 'org-appearance
4316 :set 'org-set-emph-re
4317 :version "24.4"
4318 :package-version '(Org . "8.0")
4319 :type '(repeat
4320 (list
4321 (string :tag "Marker character")
4322 (choice
4323 (face :tag "Font-lock-face")
4324 (plist :tag "Face property list"))
4325 (option (const verbatim)))))
4327 (defvar org-protecting-blocks '("src" "example" "export")
4328 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4329 This is needed for font-lock setup.")
4331 ;;; Functions and variables from their packages
4332 ;; Declared here to avoid compiler warnings
4333 (defvar mark-active)
4335 ;; Various packages
4336 (declare-function calc-eval "calc" (str &optional separator &rest args))
4337 (declare-function calendar-forward-day "cal-move" (arg))
4338 (declare-function calendar-goto-date "cal-move" (date))
4339 (declare-function calendar-goto-today "cal-move" ())
4340 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4341 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4342 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4343 (declare-function cdlatex-tab "ext:cdlatex" ())
4344 (declare-function dired-get-filename
4345 "dired"
4346 (&optional localp no-error-if-not-filep))
4347 (declare-function iswitchb-read-buffer
4348 "iswitchb"
4349 (prompt &optional
4350 default require-match _predicate start matches-set))
4351 (declare-function org-agenda-change-all-lines
4352 "org-agenda"
4353 (newhead hdmarker &optional fixface just-this))
4354 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4355 "org-agenda"
4356 (&optional end))
4357 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4358 (declare-function org-agenda-format-item
4359 "org-agenda"
4360 (extra txt &optional level category tags dotime
4361 remove-re habitp))
4362 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4363 (declare-function org-agenda-save-markers-for-cut-and-paste
4364 "org-agenda"
4365 (beg end))
4366 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4367 (declare-function org-agenda-skip "org-agenda" ())
4368 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4369 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4370 (declare-function org-indent-mode "org-indent" (&optional arg))
4371 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4372 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4373 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4374 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4375 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4376 (declare-function parse-time-string "parse-time" (string))
4378 (defvar align-mode-rules-list)
4379 (defvar calc-embedded-close-formula)
4380 (defvar calc-embedded-open-formula)
4381 (defvar calc-embedded-open-mode)
4382 (defvar font-lock-unfontify-region-function)
4383 (defvar iswitchb-temp-buflist)
4384 (defvar org-agenda-tags-todo-honor-ignore-options)
4385 (defvar remember-data-file)
4386 (defvar texmathp-why)
4388 ;;;###autoload
4389 (defun turn-on-orgtbl ()
4390 "Unconditionally turn on `orgtbl-mode'."
4391 (require 'org-table)
4392 (orgtbl-mode 1))
4394 (defun org-at-table-p (&optional table-type)
4395 "Non-nil if the cursor is inside an Org table.
4396 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4397 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4398 (or (not (derived-mode-p 'org-mode))
4399 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4400 (and e (or table-type
4401 (eq 'org (org-element-property :type e))))))))
4403 (defun org-at-table.el-p ()
4404 "Non-nil when point is at a table.el table."
4405 (and (org-match-line "[ \t]*[|+]")
4406 (let ((element (org-element-at-point)))
4407 (and (eq (org-element-type element) 'table)
4408 (eq (org-element-property :type element) 'table.el)))))
4410 (defun org-at-table-hline-p ()
4411 "Non-nil when point is inside a hline in a table.
4412 Assume point is already in a table."
4413 (org-match-line org-table-hline-regexp))
4415 (defun org-table-map-tables (function &optional quietly)
4416 "Apply FUNCTION to the start of all tables in the buffer."
4417 (org-with-wide-buffer
4418 (goto-char (point-min))
4419 (while (re-search-forward org-table-any-line-regexp nil t)
4420 (unless quietly
4421 (message "Mapping tables: %d%%"
4422 (floor (* 100.0 (point)) (buffer-size))))
4423 (beginning-of-line 1)
4424 (when (and (looking-at org-table-line-regexp)
4425 ;; Exclude tables in src/example/verbatim/clocktable blocks
4426 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4427 (save-excursion (funcall function))
4428 (or (looking-at org-table-line-regexp)
4429 (forward-char 1)))
4430 (re-search-forward org-table-any-border-regexp nil 1)))
4431 (unless quietly (message "Mapping tables: done")))
4433 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4434 (declare-function org-clock-update-mode-line "org-clock" ())
4435 (declare-function org-resolve-clocks "org-clock"
4436 (&optional also-non-dangling-p prompt last-valid))
4438 (defun org-at-TBLFM-p (&optional pos)
4439 "Non-nil when point (or POS) is in #+TBLFM line."
4440 (save-excursion
4441 (goto-char (or pos (point)))
4442 (beginning-of-line)
4443 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4444 (eq (org-element-type (org-element-at-point)) 'table))))
4446 (defvar org-clock-start-time)
4447 (defvar org-clock-marker (make-marker)
4448 "Marker recording the last clock-in.")
4449 (defvar org-clock-hd-marker (make-marker)
4450 "Marker recording the last clock-in, but the headline position.")
4451 (defvar org-clock-heading ""
4452 "The heading of the current clock entry.")
4453 (defun org-clock-is-active ()
4454 "Return the buffer where the clock is currently running.
4455 Return nil if no clock is running."
4456 (marker-buffer org-clock-marker))
4458 (defun org-check-running-clock ()
4459 "Check if the current buffer contains the running clock.
4460 If yes, offer to stop it and to save the buffer with the changes."
4461 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4462 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4463 (buffer-name))))
4464 (org-clock-out)
4465 (when (y-or-n-p "Save changed buffer?")
4466 (save-buffer))))
4468 (defun org-clocktable-try-shift (dir n)
4469 "Check if this line starts a clock table, if yes, shift the time block."
4470 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4471 (org-clocktable-shift dir n)))
4473 ;;;###autoload
4474 (defun org-clock-persistence-insinuate ()
4475 "Set up hooks for clock persistence."
4476 (require 'org-clock)
4477 (add-hook 'org-mode-hook 'org-clock-load)
4478 (add-hook 'kill-emacs-hook 'org-clock-save))
4480 (defgroup org-archive nil
4481 "Options concerning archiving in Org mode."
4482 :tag "Org Archive"
4483 :group 'org-structure)
4485 (defcustom org-archive-location "%s_archive::"
4486 "The location where subtrees should be archived.
4488 The value of this variable is a string, consisting of two parts,
4489 separated by a double-colon. The first part is a filename and
4490 the second part is a headline.
4492 When the filename is omitted, archiving happens in the same file.
4493 %s in the filename will be replaced by the current file
4494 name (without the directory part). Archiving to a different file
4495 is useful to keep archived entries from contributing to the
4496 Org Agenda.
4498 The archived entries will be filed as subtrees of the specified
4499 headline. When the headline is omitted, the subtrees are simply
4500 filed away at the end of the file, as top-level entries. Also in
4501 the heading you can use %s to represent the file name, this can be
4502 useful when using the same archive for a number of different files.
4504 Here are a few examples:
4505 \"%s_archive::\"
4506 If the current file is Projects.org, archive in file
4507 Projects.org_archive, as top-level trees. This is the default.
4509 \"::* Archived Tasks\"
4510 Archive in the current file, under the top-level headline
4511 \"* Archived Tasks\".
4513 \"~/org/archive.org::\"
4514 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4516 \"~/org/archive.org::* From %s\"
4517 Archive in file ~/org/archive.org (absolute path), under headlines
4518 \"From FILENAME\" where file name is the current file name.
4520 \"~/org/datetree.org::datetree/* Finished Tasks\"
4521 The \"datetree/\" string is special, signifying to archive
4522 items to the datetree. Items are placed in either the CLOSED
4523 date of the item, or the current date if there is no CLOSED date.
4524 The heading will be a subentry to the current date. There doesn't
4525 need to be a heading, but there always needs to be a slash after
4526 datetree. For example, to store archived items directly in the
4527 datetree, use \"~/org/datetree.org::datetree/\".
4529 \"basement::** Finished Tasks\"
4530 Archive in file ./basement (relative path), as level 3 trees
4531 below the level 2 heading \"** Finished Tasks\".
4533 You may set this option on a per-file basis by adding to the buffer a
4534 line like
4536 #+ARCHIVE: basement::** Finished Tasks
4538 You may also define it locally for a subtree by setting an ARCHIVE property
4539 in the entry. If such a property is found in an entry, or anywhere up
4540 the hierarchy, it will be used."
4541 :group 'org-archive
4542 :type 'string)
4544 (defcustom org-agenda-skip-archived-trees t
4545 "Non-nil means the agenda will skip any items located in archived trees.
4546 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4547 variable is no longer recommended, you should leave it at the value t.
4548 Instead, use the key `v' to cycle the archives-mode in the agenda."
4549 :group 'org-archive
4550 :group 'org-agenda-skip
4551 :type 'boolean)
4553 (defcustom org-columns-skip-archived-trees t
4554 "Non-nil means ignore archived trees when creating column view."
4555 :group 'org-archive
4556 :group 'org-properties
4557 :type 'boolean)
4559 (defcustom org-cycle-open-archived-trees nil
4560 "Non-nil means `org-cycle' will open archived trees.
4561 An archived tree is a tree marked with the tag ARCHIVE.
4562 When nil, archived trees will stay folded. You can still open them with
4563 normal outline commands like `show-all', but not with the cycling commands."
4564 :group 'org-archive
4565 :group 'org-cycle
4566 :type 'boolean)
4568 (defcustom org-sparse-tree-open-archived-trees nil
4569 "Non-nil means sparse tree construction shows matches in archived trees.
4570 When nil, matches in these trees are highlighted, but the trees are kept in
4571 collapsed state."
4572 :group 'org-archive
4573 :group 'org-sparse-trees
4574 :type 'boolean)
4576 (defcustom org-sparse-tree-default-date-type nil
4577 "The default date type when building a sparse tree.
4578 When this is nil, a date is a scheduled or a deadline timestamp.
4579 Otherwise, these types are allowed:
4581 all: all timestamps
4582 active: only active timestamps (<...>)
4583 inactive: only inactive timestamps ([...])
4584 scheduled: only scheduled timestamps
4585 deadline: only deadline timestamps"
4586 :type '(choice (const :tag "Scheduled or deadline" nil)
4587 (const :tag "All timestamps" all)
4588 (const :tag "Only active timestamps" active)
4589 (const :tag "Only inactive timestamps" inactive)
4590 (const :tag "Only scheduled timestamps" scheduled)
4591 (const :tag "Only deadline timestamps" deadline)
4592 (const :tag "Only closed timestamps" closed))
4593 :version "26.1"
4594 :package-version '(Org . "8.3")
4595 :group 'org-sparse-trees)
4597 (defun org-cycle-hide-archived-subtrees (state)
4598 "Re-hide all archived subtrees after a visibility state change.
4599 STATE should be one of the symbols listed in the docstring of
4600 `org-cycle-hook'."
4601 (when (and (not org-cycle-open-archived-trees)
4602 (not (memq state '(overview folded))))
4603 (save-excursion
4604 (let* ((globalp (memq state '(contents all)))
4605 (beg (if globalp (point-min) (point)))
4606 (end (if globalp (point-max) (org-end-of-subtree t))))
4607 (org-hide-archived-subtrees beg end)
4608 (goto-char beg)
4609 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4610 (message "%s" (substitute-command-keys
4611 "Subtree is archived and stays closed. Use \
4612 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4614 (defun org-force-cycle-archived ()
4615 "Cycle subtree even if it is archived."
4616 (interactive)
4617 (setq this-command 'org-cycle)
4618 (let ((org-cycle-open-archived-trees t))
4619 (call-interactively 'org-cycle)))
4621 (defun org-hide-archived-subtrees (beg end)
4622 "Re-hide all archived subtrees after a visibility state change."
4623 (org-with-wide-buffer
4624 (let ((case-fold-search nil)
4625 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4626 (goto-char beg)
4627 ;; Include headline point is currently on.
4628 (beginning-of-line)
4629 (while (and (< (point) end) (re-search-forward re end t))
4630 (when (member org-archive-tag (org-get-tags nil t))
4631 (org-flag-subtree t)
4632 (org-end-of-subtree t))))))
4634 (defun org-flag-subtree (flag)
4635 (save-excursion
4636 (org-back-to-heading t)
4637 (org-flag-region (line-end-position)
4638 (progn (org-end-of-subtree t) (point))
4639 flag
4640 'outline)))
4642 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4644 ;; Declare Column View Code
4646 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4647 (declare-function org-columns-compute "org-colview" (property))
4649 ;; Declare ID code
4651 (declare-function org-id-store-link "org-id")
4652 (declare-function org-id-locations-load "org-id")
4653 (declare-function org-id-locations-save "org-id")
4654 (defvar org-id-track-globally)
4656 ;;; Variables for pre-computed regular expressions, all buffer local
4658 (defvar-local org-todo-regexp nil
4659 "Matches any of the TODO state keywords.
4660 Since TODO keywords are case-sensitive, `case-fold-search' is
4661 expected to be bound to nil when matching against this regexp.")
4663 (defvar-local org-not-done-regexp nil
4664 "Matches any of the TODO state keywords except the last one.
4665 Since TODO keywords are case-sensitive, `case-fold-search' is
4666 expected to be bound to nil when matching against this regexp.")
4668 (defvar-local org-not-done-heading-regexp nil
4669 "Matches a TODO headline that is not done.
4670 Since TODO keywords are case-sensitive, `case-fold-search' is
4671 expected to be bound to nil when matching against this regexp.")
4673 (defvar-local org-todo-line-regexp nil
4674 "Matches a headline and puts TODO state into group 2 if present.
4675 Since TODO keywords are case-sensitive, `case-fold-search' is
4676 expected to be bound to nil when matching against this regexp.")
4678 (defvar-local org-complex-heading-regexp nil
4679 "Matches a headline and puts everything into groups:
4681 group 1: Stars
4682 group 2: The TODO keyword, maybe
4683 group 3: Priority cookie
4684 group 4: True headline
4685 group 5: Tags
4687 Since TODO keywords are case-sensitive, `case-fold-search' is
4688 expected to be bound to nil when matching against this regexp.")
4690 (defvar-local org-complex-heading-regexp-format nil
4691 "Printf format to make regexp to match an exact headline.
4692 This regexp will match the headline of any node which has the
4693 exact headline text that is put into the format, but may have any
4694 TODO state, priority and tags.")
4696 (defvar-local org-todo-line-tags-regexp nil
4697 "Matches a headline and puts TODO state into group 2 if present.
4698 Also put tags into group 4 if tags are present.")
4700 (defconst org-plain-time-of-day-regexp
4701 (concat
4702 "\\(\\<[012]?[0-9]"
4703 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4704 "\\(--?"
4705 "\\(\\<[012]?[0-9]"
4706 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4707 "\\)?")
4708 "Regular expression to match a plain time or time range.
4709 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4710 groups carry important information:
4711 0 the full match
4712 1 the first time, range or not
4713 8 the second time, if it is a range.")
4715 (defconst org-plain-time-extension-regexp
4716 (concat
4717 "\\(\\<[012]?[0-9]"
4718 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4719 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4720 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4721 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4722 groups carry important information:
4723 0 the full match
4724 7 hours of duration
4725 9 minutes of duration")
4727 (defconst org-stamp-time-of-day-regexp
4728 (concat
4729 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4730 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4731 "\\(--?"
4732 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4733 "Regular expression to match a timestamp time or time range.
4734 After a match, the following groups carry important information:
4735 0 the full match
4736 1 date plus weekday, for back referencing to make sure both times are on the same day
4737 2 the first time, range or not
4738 4 the second time, if it is a range.")
4740 (defconst org-startup-options
4741 '(("fold" org-startup-folded t)
4742 ("overview" org-startup-folded t)
4743 ("nofold" org-startup-folded nil)
4744 ("showall" org-startup-folded nil)
4745 ("showeverything" org-startup-folded showeverything)
4746 ("content" org-startup-folded content)
4747 ("indent" org-startup-indented t)
4748 ("noindent" org-startup-indented nil)
4749 ("hidestars" org-hide-leading-stars t)
4750 ("showstars" org-hide-leading-stars nil)
4751 ("odd" org-odd-levels-only t)
4752 ("oddeven" org-odd-levels-only nil)
4753 ("align" org-startup-align-all-tables t)
4754 ("noalign" org-startup-align-all-tables nil)
4755 ("shrink" org-startup-shrink-all-tables t)
4756 ("inlineimages" org-startup-with-inline-images t)
4757 ("noinlineimages" org-startup-with-inline-images nil)
4758 ("latexpreview" org-startup-with-latex-preview t)
4759 ("nolatexpreview" org-startup-with-latex-preview nil)
4760 ("customtime" org-display-custom-times t)
4761 ("logdone" org-log-done time)
4762 ("lognotedone" org-log-done note)
4763 ("nologdone" org-log-done nil)
4764 ("lognoteclock-out" org-log-note-clock-out t)
4765 ("nolognoteclock-out" org-log-note-clock-out nil)
4766 ("logrepeat" org-log-repeat state)
4767 ("lognoterepeat" org-log-repeat note)
4768 ("logdrawer" org-log-into-drawer t)
4769 ("nologdrawer" org-log-into-drawer nil)
4770 ("logstatesreversed" org-log-states-order-reversed t)
4771 ("nologstatesreversed" org-log-states-order-reversed nil)
4772 ("nologrepeat" org-log-repeat nil)
4773 ("logreschedule" org-log-reschedule time)
4774 ("lognotereschedule" org-log-reschedule note)
4775 ("nologreschedule" org-log-reschedule nil)
4776 ("logredeadline" org-log-redeadline time)
4777 ("lognoteredeadline" org-log-redeadline note)
4778 ("nologredeadline" org-log-redeadline nil)
4779 ("logrefile" org-log-refile time)
4780 ("lognoterefile" org-log-refile note)
4781 ("nologrefile" org-log-refile nil)
4782 ("fninline" org-footnote-define-inline t)
4783 ("nofninline" org-footnote-define-inline nil)
4784 ("fnlocal" org-footnote-section nil)
4785 ("fnauto" org-footnote-auto-label t)
4786 ("fnprompt" org-footnote-auto-label nil)
4787 ("fnconfirm" org-footnote-auto-label confirm)
4788 ("fnplain" org-footnote-auto-label plain)
4789 ("fnadjust" org-footnote-auto-adjust t)
4790 ("nofnadjust" org-footnote-auto-adjust nil)
4791 ("constcgs" constants-unit-system cgs)
4792 ("constSI" constants-unit-system SI)
4793 ("noptag" org-tag-persistent-alist nil)
4794 ("hideblocks" org-hide-block-startup t)
4795 ("nohideblocks" org-hide-block-startup nil)
4796 ("beamer" org-startup-with-beamer-mode t)
4797 ("entitiespretty" org-pretty-entities t)
4798 ("entitiesplain" org-pretty-entities nil))
4799 "Variable associated with STARTUP options for Org.
4800 Each element is a list of three items: the startup options (as written
4801 in the #+STARTUP line), the corresponding variable, and the value to set
4802 this variable to if the option is found. An optional forth element PUSH
4803 means to push this value onto the list in the variable.")
4805 (defcustom org-group-tags t
4806 "When non-nil (the default), use group tags.
4807 This can be turned on/off through `org-toggle-tags-groups'."
4808 :group 'org-tags
4809 :group 'org-startup
4810 :type 'boolean)
4812 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4814 (defun org-toggle-tags-groups ()
4815 "Toggle support for group tags.
4816 Support for group tags is controlled by the option
4817 `org-group-tags', which is non-nil by default."
4818 (interactive)
4819 (setq org-group-tags (not org-group-tags))
4820 (cond ((and (derived-mode-p 'org-agenda-mode)
4821 org-group-tags)
4822 (org-agenda-redo))
4823 ((derived-mode-p 'org-mode)
4824 (let ((org-inhibit-startup t)) (org-mode))))
4825 (message "Groups tags support has been turned %s"
4826 (if org-group-tags "on" "off")))
4828 (defun org-tag-add-to-alist (alist1 alist2)
4829 "Append ALIST1 elements to ALIST2 if they are not there yet."
4830 (cond
4831 ((null alist2) alist1)
4832 ((null alist1) alist2)
4833 (t (let ((alist2-cars (mapcar (lambda (x) (car-safe x)) alist2))
4834 to-add)
4835 (dolist (i alist1)
4836 (unless (member (car-safe i) alist2-cars)
4837 (push i to-add)))
4838 (append to-add alist2)))))
4840 (defun org-set-regexps-and-options (&optional tags-only)
4841 "Precompute regular expressions used in the current buffer.
4842 When optional argument TAGS-ONLY is non-nil, only compute tags
4843 related expressions."
4844 (when (derived-mode-p 'org-mode)
4845 (let ((alist (org--setup-collect-keywords
4846 (org-make-options-regexp
4847 (append '("FILETAGS" "TAGS" "SETUPFILE")
4848 (and (not tags-only)
4849 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4850 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4851 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4852 ;; Startup options. Get this early since it does change
4853 ;; behavior for other options (e.g., tags).
4854 (let ((startup (cdr (assq 'startup alist))))
4855 (dolist (option startup)
4856 (let ((entry (assoc-string option org-startup-options t)))
4857 (when entry
4858 (let ((var (nth 1 entry))
4859 (val (nth 2 entry)))
4860 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4861 (unless (listp (symbol-value var))
4862 (set (make-local-variable var) nil))
4863 (add-to-list var val)))))))
4864 (setq-local org-file-tags
4865 (mapcar #'org-add-prop-inherited
4866 (cdr (assq 'filetags alist))))
4867 (setq org-current-tag-alist
4868 (org-tag-add-to-alist
4869 org-tag-persistent-alist
4870 (let ((tags (cdr (assq 'tags alist))))
4871 (if tags (org-tag-string-to-alist tags)
4872 org-tag-alist))))
4873 (setq org-tag-groups-alist
4874 (org-tag-alist-to-groups org-current-tag-alist))
4875 (unless tags-only
4876 ;; File properties.
4877 (setq-local org-file-properties (cdr (assq 'property alist)))
4878 ;; Archive location.
4879 (let ((archive (cdr (assq 'archive alist))))
4880 (when archive (setq-local org-archive-location archive)))
4881 ;; Category.
4882 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4883 (when cat
4884 (setq-local org-category (intern cat))
4885 (setq-local org-file-properties
4886 (org--update-property-plist
4887 "CATEGORY" cat org-file-properties))))
4888 ;; Columns.
4889 (let ((column (cdr (assq 'columns alist))))
4890 (when column (setq-local org-columns-default-format column)))
4891 ;; Constants.
4892 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4893 ;; Link abbreviations.
4894 (let ((links (cdr (assq 'link alist))))
4895 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4896 ;; Priorities.
4897 (let ((priorities (cdr (assq 'priorities alist))))
4898 (when priorities
4899 (setq-local org-highest-priority (nth 0 priorities))
4900 (setq-local org-lowest-priority (nth 1 priorities))
4901 (setq-local org-default-priority (nth 2 priorities))))
4902 ;; Scripts.
4903 (let ((scripts (assq 'scripts alist)))
4904 (when scripts
4905 (setq-local org-use-sub-superscripts (cdr scripts))))
4906 ;; TODO keywords.
4907 (setq-local org-todo-kwd-alist nil)
4908 (setq-local org-todo-key-alist nil)
4909 (setq-local org-todo-key-trigger nil)
4910 (setq-local org-todo-keywords-1 nil)
4911 (setq-local org-done-keywords nil)
4912 (setq-local org-todo-heads nil)
4913 (setq-local org-todo-sets nil)
4914 (setq-local org-todo-log-states nil)
4915 (let ((todo-sequences
4916 (or (nreverse (cdr (assq 'todo alist)))
4917 (let ((d (default-value 'org-todo-keywords)))
4918 (if (not (stringp (car d))) d
4919 ;; XXX: Backward compatibility code.
4920 (list (cons org-todo-interpretation d)))))))
4921 (dolist (sequence todo-sequences)
4922 (let* ((sequence (or (run-hook-with-args-until-success
4923 'org-todo-setup-filter-hook sequence)
4924 sequence))
4925 (sequence-type (car sequence))
4926 (keywords (cdr sequence))
4927 (sep (member "|" keywords))
4928 names alist)
4929 (dolist (k (remove "|" keywords))
4930 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4932 (error "Invalid TODO keyword %s" k))
4933 (let ((name (match-string 1 k))
4934 (key (match-string 2 k))
4935 (log (org-extract-log-state-settings k)))
4936 (push name names)
4937 (push (cons name (and key (string-to-char key))) alist)
4938 (when log (push log org-todo-log-states))))
4939 (let* ((names (nreverse names))
4940 (done (if sep (org-remove-keyword-keys (cdr sep))
4941 (last names)))
4942 (head (car names))
4943 (tail (list sequence-type head (car done) (org-last done))))
4944 (add-to-list 'org-todo-heads head 'append)
4945 (push names org-todo-sets)
4946 (setq org-done-keywords (append org-done-keywords done nil))
4947 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4948 (setq org-todo-key-alist
4949 (append org-todo-key-alist
4950 (and alist
4951 (append '((:startgroup))
4952 (nreverse alist)
4953 '((:endgroup))))))
4954 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4955 (setq org-todo-sets (nreverse org-todo-sets)
4956 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4957 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4958 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4959 ;; Compute the regular expressions and other local variables.
4960 ;; Using `org-outline-regexp-bol' would complicate them much,
4961 ;; because of the fixed white space at the end of that string.
4962 (unless org-done-keywords
4963 (setq org-done-keywords
4964 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4965 (setq org-not-done-keywords
4966 (org-delete-all org-done-keywords
4967 (copy-sequence org-todo-keywords-1))
4968 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4969 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4970 org-not-done-heading-regexp
4971 (format org-heading-keyword-regexp-format org-not-done-regexp)
4972 org-todo-line-regexp
4973 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4974 org-complex-heading-regexp
4975 (concat "^\\(\\*+\\)"
4976 "\\(?: +" org-todo-regexp "\\)?"
4977 "\\(?: +\\(\\[#.\\]\\)\\)?"
4978 "\\(?: +\\(.*?\\)\\)??"
4979 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4980 "[ \t]*$")
4981 org-complex-heading-regexp-format
4982 (concat "^\\(\\*+\\)"
4983 "\\(?: +" org-todo-regexp "\\)?"
4984 "\\(?: +\\(\\[#.\\]\\)\\)?"
4985 "\\(?: +"
4986 ;; Stats cookies can be stuck to body.
4987 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4988 "\\(%s\\)"
4989 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4990 "\\)"
4991 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4992 "[ \t]*$")
4993 org-todo-line-tags-regexp
4994 (concat "^\\(\\*+\\)"
4995 "\\(?: +" org-todo-regexp "\\)?"
4996 "\\(?: +\\(.*?\\)\\)??"
4997 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
4998 "[ \t]*$"))
4999 (org-compute-latex-and-related-regexp)))))
5001 (defun org--setup-collect-keywords (regexp &optional files alist)
5002 "Return setup keywords values as an alist.
5004 REGEXP matches a subset of setup keywords. FILES is a list of
5005 file names already visited. It is used to avoid circular setup
5006 files. ALIST, when non-nil, is the alist computed so far.
5008 Return value contains the following keys: `archive', `category',
5009 `columns', `constants', `filetags', `link', `priorities',
5010 `property', `scripts', `startup', `tags' and `todo'."
5011 (org-with-wide-buffer
5012 (goto-char (point-min))
5013 (let ((case-fold-search t))
5014 (while (re-search-forward regexp nil t)
5015 (let ((element (org-element-at-point)))
5016 (when (eq (org-element-type element) 'keyword)
5017 (let ((key (org-element-property :key element))
5018 (value (org-element-property :value element)))
5019 (cond
5020 ((equal key "ARCHIVE")
5021 (when (org-string-nw-p value)
5022 (push (cons 'archive value) alist)))
5023 ((equal key "CATEGORY") (push (cons 'category value) alist))
5024 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5025 ((equal key "CONSTANTS")
5026 (let* ((constants (assq 'constants alist))
5027 (store (cdr constants)))
5028 (dolist (pair (split-string value))
5029 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5030 pair)
5031 (let* ((name (match-string 1 pair))
5032 (value (match-string 2 pair))
5033 (old (assoc name store)))
5034 (if old (setcdr old value)
5035 (push (cons name value) store)))))
5036 (if constants (setcdr constants store)
5037 (push (cons 'constants store) alist))))
5038 ((equal key "FILETAGS")
5039 (when (org-string-nw-p value)
5040 (let ((old (assq 'filetags alist))
5041 (new (apply #'nconc
5042 (mapcar (lambda (x) (org-split-string x ":"))
5043 (split-string value)))))
5044 (if old (setcdr old (append new (cdr old)))
5045 (push (cons 'filetags new) alist)))))
5046 ((equal key "LINK")
5047 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5048 (let ((links (assq 'link alist))
5049 (pair (cons (match-string-no-properties 1 value)
5050 (match-string-no-properties 2 value))))
5051 (if links (push pair (cdr links))
5052 (push (list 'link pair) alist)))))
5053 ((equal key "OPTIONS")
5054 (when (and (org-string-nw-p value)
5055 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5056 (push (cons 'scripts (read (match-string 1 value))) alist)))
5057 ((equal key "PRIORITIES")
5058 (push (cons 'priorities
5059 (let ((prio (split-string value)))
5060 (if (< (length prio) 3) '(?A ?C ?B)
5061 (mapcar #'string-to-char prio))))
5062 alist))
5063 ((equal key "PROPERTY")
5064 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5065 (let* ((property (assq 'property alist))
5066 (value (org--update-property-plist
5067 (match-string-no-properties 1 value)
5068 (match-string-no-properties 2 value)
5069 (cdr property))))
5070 (if property (setcdr property value)
5071 (push (cons 'property value) alist)))))
5072 ((equal key "STARTUP")
5073 (let ((startup (assq 'startup alist)))
5074 (if startup
5075 (setcdr startup
5076 (append (cdr startup) (split-string value)))
5077 (push (cons 'startup (split-string value)) alist))))
5078 ((equal key "TAGS")
5079 (let ((tag-cell (assq 'tags alist)))
5080 (if tag-cell
5081 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5082 (push (cons 'tags value) alist))))
5083 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5084 (let ((todo (assq 'todo alist))
5085 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5086 (split-string value))))
5087 (if todo (push value (cdr todo))
5088 (push (list 'todo value) alist))))
5089 ((equal key "SETUPFILE")
5090 (unless buffer-read-only ; Do not check in Gnus messages.
5091 (let ((f (and (org-string-nw-p value)
5092 (expand-file-name
5093 (org-unbracket-string "\"" "\"" value)))))
5094 (when (and f (file-readable-p f) (not (member f files)))
5095 (with-temp-buffer
5096 (setq default-directory (file-name-directory f))
5097 (insert-file-contents f)
5098 (setq alist
5099 ;; Fake Org mode to benefit from cache
5100 ;; without recurring needlessly.
5101 (let ((major-mode 'org-mode))
5102 (org--setup-collect-keywords
5103 regexp (cons f files) alist)))))))))))))))
5104 alist)
5106 (defun org-tag-string-to-alist (s)
5107 "Return tag alist associated to string S.
5108 S is a value for TAGS keyword or produced with
5109 `org-tag-alist-to-string'. Return value is an alist suitable for
5110 `org-tag-alist' or `org-tag-persistent-alist'."
5111 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5112 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5113 "\\|{.+?}\\)" ; regular expression
5114 "\\(?:(\\(.\\))\\)?\\'"))
5115 alist group-flag)
5116 (dolist (tokens lines (cdr (nreverse alist)))
5117 (push '(:newline) alist)
5118 (while tokens
5119 (let ((token (pop tokens)))
5120 (pcase token
5121 ("{"
5122 (push '(:startgroup) alist)
5123 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5124 ("}"
5125 (push '(:endgroup) alist)
5126 (setq group-flag nil))
5127 ("["
5128 (push '(:startgrouptag) alist)
5129 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5130 ("]"
5131 (push '(:endgrouptag) alist)
5132 (setq group-flag nil))
5133 (":"
5134 (push '(:grouptags) alist))
5135 ((guard (string-match tag-re token))
5136 (let ((tag (match-string 1 token))
5137 (key (and (match-beginning 2)
5138 (string-to-char (match-string 2 token)))))
5139 ;; Push all tags in groups, no matter if they already
5140 ;; appear somewhere else in the list.
5141 (when (or group-flag (not (assoc tag alist)))
5142 (push (cons tag key) alist))))))))))
5144 (defun org-tag-alist-to-string (alist &optional skip-key)
5145 "Return tag string associated to ALIST.
5147 ALIST is an alist, as defined in `org-tag-alist' or
5148 `org-tag-persistent-alist', or produced with
5149 `org-tag-string-to-alist'.
5151 Return value is a string suitable as a value for \"TAGS\"
5152 keyword.
5154 When optional argument SKIP-KEY is non-nil, skip selection keys
5155 next to tags."
5156 (mapconcat (lambda (token)
5157 (pcase token
5158 (`(:startgroup) "{")
5159 (`(:endgroup) "}")
5160 (`(:startgrouptag) "[")
5161 (`(:endgrouptag) "]")
5162 (`(:grouptags) ":")
5163 (`(:newline) "\\n")
5164 ((and
5165 (guard (not skip-key))
5166 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5167 (format "%s(%c)" tag key))
5168 (`(,(and tag (pred stringp)) . ,_) tag)
5169 (_ (user-error "Invalid tag token: %S" token))))
5170 alist
5171 " "))
5173 (defun org-tag-alist-to-groups (alist)
5174 "Return group alist from tag ALIST.
5175 ALIST is an alist, as defined in `org-tag-alist' or
5176 `org-tag-persistent-alist', or produced with
5177 `org-tag-string-to-alist'. Return value is an alist following
5178 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5179 a string, summarizing TAGS, as a list of strings."
5180 (let (groups group-status current-group)
5181 (dolist (token alist (nreverse groups))
5182 (pcase token
5183 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5184 (`(,(or :endgroup :endgrouptag))
5185 (when (eq group-status 'append)
5186 (push (nreverse current-group) groups))
5187 (setq group-status nil current-group nil))
5188 (`(:grouptags) (setq group-status 'append))
5189 ((and `(,tag . ,_) (guard group-status))
5190 (if (eq group-status 'append) (push tag current-group)
5191 (setq current-group (list tag))))
5192 (_ nil)))))
5194 (defvar org--file-cache (make-hash-table :test #'equal)
5195 "Hash table to store contents of files referenced via a URL.
5196 This is the cache of file URLs read using `org-file-contents'.")
5198 (defun org-reset-file-cache ()
5199 "Reset the cache of files downloaded by `org-file-contents'."
5200 (clrhash org--file-cache))
5202 (defun org-file-url-p (file)
5203 "Non-nil if FILE is a URL."
5204 (require 'ffap)
5205 (string-match-p ffap-url-regexp file))
5207 (defun org-file-contents (file &optional noerror nocache)
5208 "Return the contents of FILE, as a string.
5210 FILE can be a file name or URL.
5212 If FILE is a URL, download the contents. If the URL contents are
5213 already cached in the `org--file-cache' hash table, the download step
5214 is skipped.
5216 If NOERROR is non-nil, ignore the error when unable to read the FILE
5217 from file or URL.
5219 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5220 is available. This option applies only if FILE is a URL."
5221 (let* ((is-url (org-file-url-p file))
5222 (cache (and is-url
5223 (not nocache)
5224 (gethash file org--file-cache))))
5225 (cond
5226 (cache)
5227 (is-url
5228 (with-current-buffer (url-retrieve-synchronously file)
5229 (goto-char (point-min))
5230 ;; Move point to after the url-retrieve header.
5231 (search-forward "\n\n" nil :move)
5232 ;; Search for the success code only in the url-retrieve header.
5233 (if (save-excursion
5234 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5235 ;; Update the cache `org--file-cache' and return contents.
5236 (puthash file
5237 (buffer-substring-no-properties (point) (point-max))
5238 org--file-cache)
5239 (funcall (if noerror #'message #'user-error)
5240 "Unable to fetch file from %S"
5241 file))))
5243 (with-temp-buffer
5244 (condition-case nil
5245 (progn
5246 (insert-file-contents file)
5247 (buffer-string))
5248 (file-error
5249 (funcall (if noerror #'message #'user-error)
5250 "Unable to read file %S"
5251 file))))))))
5253 (defun org-extract-log-state-settings (x)
5254 "Extract the log state setting from a TODO keyword string.
5255 This will extract info from a string like \"WAIT(w@/!)\"."
5256 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5257 (let ((kw (match-string 1 x))
5258 (log1 (and (match-end 3) (match-string 3 x)))
5259 (log2 (and (match-end 4) (match-string 4 x))))
5260 (and (or log1 log2)
5261 (list kw
5262 (and log1 (if (equal log1 "!") 'time 'note))
5263 (and log2 (if (equal log2 "!") 'time 'note)))))))
5265 (defun org-remove-keyword-keys (list)
5266 "Remove a pair of parenthesis at the end of each string in LIST."
5267 (mapcar (lambda (x)
5268 (if (string-match "(.*)$" x)
5269 (substring x 0 (match-beginning 0))
5271 list))
5273 (defun org-assign-fast-keys (alist)
5274 "Assign fast keys to a keyword-key alist.
5275 Respect keys that are already there."
5276 (let (new e (alt ?0))
5277 (while (setq e (pop alist))
5278 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5279 (cdr e)) ;; Key already assigned.
5280 (push e new)
5281 (let ((clist (string-to-list (downcase (car e))))
5282 (used (append new alist)))
5283 (when (= (car clist) ?@)
5284 (pop clist))
5285 (while (and clist (rassoc (car clist) used))
5286 (pop clist))
5287 (unless clist
5288 (while (rassoc alt used)
5289 (cl-incf alt)))
5290 (push (cons (car e) (or (car clist) alt)) new))))
5291 (nreverse new)))
5293 ;;; Some variables used in various places
5295 (defvar org-window-configuration nil
5296 "Used in various places to store a window configuration.")
5297 (defvar org-selected-window nil
5298 "Used in various places to store a window configuration.")
5299 (defvar org-finish-function nil
5300 "Function to be called when `C-c C-c' is used.
5301 This is for getting out of special buffers like capture.")
5302 (defvar org-last-state)
5304 ;; Defined somewhere in this file, but used before definition.
5305 (defvar org-entities) ;; defined in org-entities.el
5306 (defvar org-struct-menu)
5307 (defvar org-org-menu)
5308 (defvar org-tbl-menu)
5310 ;;;; Define the Org mode
5312 ;; We use a before-change function to check if a table might need
5313 ;; an update.
5314 (defvar org-table-may-need-update t
5315 "Indicates that a table might need an update.
5316 This variable is set by `org-before-change-function'.
5317 `org-table-align' sets it back to nil.")
5318 (defun org-before-change-function (_beg _end)
5319 "Every change indicates that a table might need an update."
5320 (setq org-table-may-need-update t))
5321 (defvar org-mode-map)
5322 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5323 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5324 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5325 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5326 (defvar org-table-buffer-is-an nil)
5328 (defvar bidi-paragraph-direction)
5329 (defvar buffer-face-mode-face)
5331 (require 'outline)
5333 ;; Other stuff we need.
5334 (require 'time-date)
5335 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5336 (require 'easymenu)
5337 (autoload 'easy-menu-add "easymenu")
5338 (require 'overlay)
5340 ;; (require 'org-macs) moved higher up in the file before it is first used
5341 (require 'org-entities)
5342 ;; (require 'org-compat) moved higher up in the file before it is first used
5343 (require 'org-faces)
5344 (require 'org-list)
5345 (require 'org-pcomplete)
5346 (require 'org-src)
5347 (require 'org-footnote)
5348 (require 'org-macro)
5350 ;; babel
5351 (require 'ob)
5353 ;;;###autoload
5354 (define-derived-mode org-mode outline-mode "Org"
5355 "Outline-based notes management and organizer, alias
5356 \"Carsten's outline-mode for keeping track of everything.\"
5358 Org mode develops organizational tasks around a NOTES file which
5359 contains information about projects as plain text. Org mode is
5360 implemented on top of Outline mode, which is ideal to keep the content
5361 of large files well structured. It supports ToDo items, deadlines and
5362 time stamps, which magically appear in the diary listing of the Emacs
5363 calendar. Tables are easily created with a built-in table editor.
5364 Plain text URL-like links connect to websites, emails (VM), Usenet
5365 messages (Gnus), BBDB entries, and any files related to the project.
5366 For printing and sharing of notes, an Org file (or a part of it)
5367 can be exported as a structured ASCII or HTML file.
5369 The following commands are available:
5371 \\{org-mode-map}"
5373 ;; Get rid of Outline menus, they are not needed
5374 ;; Need to do this here because define-derived-mode sets up
5375 ;; the keymap so late. Still, it is a waste to call this each time
5376 ;; we switch another buffer into Org mode.
5377 (define-key org-mode-map [menu-bar headings] 'undefined)
5378 (define-key org-mode-map [menu-bar hide] 'undefined)
5379 (define-key org-mode-map [menu-bar show] 'undefined)
5381 (org-load-modules-maybe)
5382 (org-install-agenda-files-menu)
5383 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5384 (add-to-invisibility-spec '(org-hide-block . t))
5385 (add-to-invisibility-spec '(org-hide-drawer . t))
5386 (setq-local outline-regexp org-outline-regexp)
5387 (setq-local outline-level 'org-outline-level)
5388 (setq bidi-paragraph-direction 'left-to-right)
5389 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5390 (unless org-display-table
5391 (setq org-display-table (make-display-table)))
5392 (set-display-table-slot
5393 org-display-table 4
5394 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5395 org-ellipsis)))
5396 (setq buffer-display-table org-display-table))
5397 (org-set-regexps-and-options)
5398 (org-set-font-lock-defaults)
5399 (when (and org-tag-faces (not org-tags-special-faces-re))
5400 ;; tag faces set outside customize.... force initialization.
5401 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5402 ;; Calc embedded
5403 (setq-local calc-embedded-open-mode "# ")
5404 ;; Modify a few syntax entries
5405 (modify-syntax-entry ?@ "w")
5406 (modify-syntax-entry ?\" "\"")
5407 (modify-syntax-entry ?\\ "_")
5408 (modify-syntax-entry ?~ "_")
5409 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5410 ;; Activate before-change-function
5411 (setq-local org-table-may-need-update t)
5412 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5413 ;; Check for running clock before killing a buffer
5414 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5415 ;; Initialize macros templates.
5416 (org-macro-initialize-templates)
5417 ;; Initialize radio targets.
5418 (org-update-radio-target-regexp)
5419 ;; Indentation.
5420 (setq-local indent-line-function 'org-indent-line)
5421 (setq-local indent-region-function 'org-indent-region)
5422 ;; Filling and auto-filling.
5423 (org-setup-filling)
5424 ;; Comments.
5425 (org-setup-comments-handling)
5426 ;; Initialize cache.
5427 (org-element-cache-reset)
5428 ;; Beginning/end of defun
5429 (setq-local beginning-of-defun-function 'org-backward-element)
5430 (setq-local end-of-defun-function
5431 (lambda ()
5432 (if (not (org-at-heading-p))
5433 (org-forward-element)
5434 (org-forward-element)
5435 (forward-char -1))))
5436 ;; Next error for sparse trees
5437 (setq-local next-error-function 'org-occur-next-match)
5438 ;; Make sure dependence stuff works reliably, even for users who set it
5439 ;; too late :-(
5440 (if org-enforce-todo-dependencies
5441 (add-hook 'org-blocker-hook
5442 'org-block-todo-from-children-or-siblings-or-parent)
5443 (remove-hook 'org-blocker-hook
5444 'org-block-todo-from-children-or-siblings-or-parent))
5445 (if org-enforce-todo-checkbox-dependencies
5446 (add-hook 'org-blocker-hook
5447 'org-block-todo-from-checkboxes)
5448 (remove-hook 'org-blocker-hook
5449 'org-block-todo-from-checkboxes))
5451 ;; Align options lines
5452 (setq-local
5453 align-mode-rules-list
5454 '((org-in-buffer-settings
5455 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5456 (modes . '(org-mode)))))
5458 ;; Imenu
5459 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5461 ;; Make isearch reveal context
5462 (setq-local outline-isearch-open-invisible-function
5463 (lambda (&rest _) (org-show-context 'isearch)))
5465 ;; Setup the pcomplete hooks
5466 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5467 (setq-local pcomplete-command-name-function 'org-command-at-point)
5468 (setq-local pcomplete-default-completion-function 'ignore)
5469 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5470 (setq-local pcomplete-termination-string "")
5471 (setq-local buffer-face-mode-face 'org-default)
5473 ;; If empty file that did not turn on Org mode automatically, make
5474 ;; it to.
5475 (when (and org-insert-mode-line-in-empty-file
5476 (called-interactively-p 'any)
5477 (= (point-min) (point-max)))
5478 (insert "# -*- mode: org -*-\n\n"))
5479 (unless org-inhibit-startup
5480 (org-unmodified
5481 (when org-startup-with-beamer-mode (org-beamer-mode))
5482 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5483 (org-table-map-tables
5484 (cond ((and org-startup-align-all-tables
5485 org-startup-shrink-all-tables)
5486 (lambda () (org-table-align) (org-table-shrink)))
5487 (org-startup-align-all-tables #'org-table-align)
5488 (t #'org-table-shrink))
5490 (when org-startup-with-inline-images (org-display-inline-images))
5491 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5492 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5493 (when org-startup-truncated (setq truncate-lines t))
5494 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5495 (org-refresh-effort-properties)))
5496 ;; Try to set `org-hide' face correctly.
5497 (let ((foreground (org-find-invisible-foreground)))
5498 (when foreground
5499 (set-face-foreground 'org-hide foreground))))
5501 ;; Update `customize-package-emacs-version-alist'
5502 (add-to-list 'customize-package-emacs-version-alist
5503 '(Org ("8.0" . "24.4")
5504 ("8.1" . "24.4")
5505 ("8.2" . "24.4")
5506 ("8.2.7" . "24.4")
5507 ("8.3" . "26.1")
5508 ("9.0" . "26.1")
5509 ("9.1" . "26.1")
5510 ("9.2" . "27.1")))
5512 (defvar org-mode-transpose-word-syntax-table
5513 (let ((st (make-syntax-table text-mode-syntax-table)))
5514 (dolist (c org-emphasis-alist st)
5515 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5517 (when (fboundp 'abbrev-table-put)
5518 (abbrev-table-put org-mode-abbrev-table
5519 :parents (list text-mode-abbrev-table)))
5521 (defun org-find-invisible-foreground ()
5522 (let ((candidates (remove
5523 "unspecified-bg"
5524 (nconc
5525 (list (face-background 'default)
5526 (face-background 'org-default))
5527 (mapcar
5528 (lambda (alist)
5529 (when (boundp alist)
5530 (cdr (assq 'background-color (symbol-value alist)))))
5531 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5532 (list (face-foreground 'org-hide))))))
5533 (car (remove nil candidates))))
5535 (defun org-current-time (&optional rounding-minutes past)
5536 "Current time, possibly rounded to ROUNDING-MINUTES.
5537 When ROUNDING-MINUTES is not an integer, fall back on the car of
5538 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5539 the rounding returns a past time."
5540 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5541 (car org-time-stamp-rounding-minutes)))
5542 (time (decode-time)) res)
5543 (if (< r 1)
5544 (current-time)
5545 (setq res
5546 (apply 'encode-time
5547 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5548 (nthcdr 2 time))))
5549 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5550 (seconds-to-time (- (float-time res) (* r 60)))
5551 res))))
5553 (defun org-today ()
5554 "Return today date, considering `org-extend-today-until'."
5555 (time-to-days
5556 (time-subtract (current-time)
5557 (list 0 (* 3600 org-extend-today-until) 0))))
5559 ;;;; Font-Lock stuff, including the activators
5561 (defvar org-mouse-map (make-sparse-keymap))
5562 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5563 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5564 (when org-mouse-1-follows-link
5565 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5566 (when org-tab-follows-link
5567 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5568 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5570 (require 'font-lock)
5572 (defconst org-non-link-chars "]\t\n\r<>")
5573 (defvar org-link-types-re nil
5574 "Matches a link that has a url-like prefix like \"http:\"")
5575 (defvar org-link-re-with-space nil
5576 "Matches a link with spaces, optional angular brackets around it.")
5577 (defvar org-link-re-with-space2 nil
5578 "Matches a link with spaces, optional angular brackets around it.")
5579 (defvar org-link-re-with-space3 nil
5580 "Matches a link with spaces, only for internal part in bracket links.")
5581 (defvar org-angle-link-re nil
5582 "Matches link with angular brackets, spaces are allowed.")
5583 (defvar org-plain-link-re nil
5584 "Matches plain link, without spaces.")
5585 (defvar org-bracket-link-regexp nil
5586 "Matches a link in double brackets.")
5587 (defvar org-bracket-link-analytic-regexp nil
5588 "Regular expression used to analyze links.
5589 Here is what the match groups contain after a match:
5590 1: http:
5591 2: http
5592 3: path
5593 4: [desc]
5594 5: desc")
5595 (defvar org-bracket-link-analytic-regexp++ nil
5596 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5597 (defvar org-any-link-re nil
5598 "Regular expression matching any link.")
5600 (defconst org-match-sexp-depth 3
5601 "Number of stacked braces for sub/superscript matching.")
5603 (defun org-create-multibrace-regexp (left right n)
5604 "Create a regular expression which will match a balanced sexp.
5605 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5606 as single character strings.
5607 The regexp returned will match the entire expression including the
5608 delimiters. It will also define a single group which contains the
5609 match except for the outermost delimiters. The maximum depth of
5610 stacked delimiters is N. Escaping delimiters is not possible."
5611 (let* ((nothing (concat "[^" left right "]*?"))
5612 (or "\\|")
5613 (re nothing)
5614 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5615 (while (> n 1)
5616 (setq n (1- n)
5617 re (concat re or next)
5618 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5619 (concat left "\\(" re "\\)" right)))
5621 (defconst org-match-substring-regexp
5622 (concat
5623 "\\(\\S-\\)\\([_^]\\)\\("
5624 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5625 "\\|"
5626 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5627 "\\|"
5628 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5629 "The regular expression matching a sub- or superscript.")
5631 (defconst org-match-substring-with-braces-regexp
5632 (concat
5633 "\\(\\S-\\)\\([_^]\\)"
5634 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5635 "The regular expression matching a sub- or superscript, forcing braces.")
5637 (defun org-make-link-regexps ()
5638 "Update the link regular expressions.
5639 This should be called after the variable `org-link-parameters' has changed."
5640 (let ((types-re (regexp-opt (org-link-types) t)))
5641 (setq org-link-types-re
5642 (concat "\\`" types-re ":")
5643 org-link-re-with-space
5644 (concat "<?" types-re ":"
5645 "\\([^" org-non-link-chars " ]"
5646 "[^" org-non-link-chars "]*"
5647 "[^" org-non-link-chars " ]\\)>?")
5648 org-link-re-with-space2
5649 (concat "<?" types-re ":"
5650 "\\([^" org-non-link-chars " ]"
5651 "[^\t\n\r]*"
5652 "[^" org-non-link-chars " ]\\)>?")
5653 org-link-re-with-space3
5654 (concat "<?" types-re ":"
5655 "\\([^" org-non-link-chars " ]"
5656 "[^\t\n\r]*\\)")
5657 org-angle-link-re
5658 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5659 types-re)
5660 org-plain-link-re
5661 (concat
5662 "\\<" types-re ":"
5663 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5664 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5665 org-bracket-link-regexp
5666 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5667 org-bracket-link-analytic-regexp
5668 (concat
5669 "\\[\\["
5670 "\\(" types-re ":\\)?"
5671 "\\([^]]+\\)"
5672 "\\]"
5673 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5674 "\\]")
5675 org-bracket-link-analytic-regexp++
5676 (concat
5677 "\\[\\["
5678 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5679 "\\([^]]+\\)"
5680 "\\]"
5681 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5682 "\\]")
5683 org-any-link-re
5684 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5685 org-angle-link-re "\\)\\|\\("
5686 org-plain-link-re "\\)"))))
5688 (org-make-link-regexps)
5690 (defvar org-emph-face nil)
5692 (defun org-do-emphasis-faces (limit)
5693 "Run through the buffer and emphasize strings."
5694 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5695 (car org-emphasis-regexp-components))))
5696 (catch :exit
5697 (while (re-search-forward quick-re limit t)
5698 (let* ((marker (match-string 2))
5699 (verbatim? (member marker '("~" "="))))
5700 (when (save-excursion
5701 (goto-char (match-beginning 0))
5702 (and
5703 ;; Do not match table hlines.
5704 (not (and (equal marker "+")
5705 (org-match-line
5706 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5707 ;; Do not match headline stars. Do not consider
5708 ;; stars of a headline as closing marker for bold
5709 ;; markup either.
5710 (not (and (equal marker "*")
5711 (save-excursion
5712 (forward-char)
5713 (skip-chars-backward "*")
5714 (looking-at-p org-outline-regexp-bol))))
5715 ;; Match full emphasis markup regexp.
5716 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5717 ;; Do not span over paragraph boundaries.
5718 (not (string-match-p org-element-paragraph-separate
5719 (match-string 2)))
5720 ;; Do not span over cells in table rows.
5721 (not (and (save-match-data (org-match-line "[ \t]*|"))
5722 (string-match-p "|" (match-string 4))))))
5723 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5724 (font-lock-prepend-text-property
5725 (match-beginning 2) (match-end 2) 'face face)
5726 (when verbatim?
5727 (org-remove-flyspell-overlays-in
5728 (match-beginning 0) (match-end 0)))
5729 (add-text-properties (match-beginning 2) (match-end 2)
5730 '(font-lock-multiline t org-emphasis t))
5731 (when org-hide-emphasis-markers
5732 (add-text-properties (match-end 4) (match-beginning 5)
5733 '(invisible org-link))
5734 (add-text-properties (match-beginning 3) (match-end 3)
5735 '(invisible org-link)))
5736 (throw :exit t))))))))
5738 (defun org-emphasize (&optional char)
5739 "Insert or change an emphasis, i.e. a font like bold or italic.
5740 If there is an active region, change that region to a new emphasis.
5741 If there is no region, just insert the marker characters and position
5742 the cursor between them.
5743 CHAR should be the marker character. If it is a space, it means to
5744 remove the emphasis of the selected region.
5745 If CHAR is not given (for example in an interactive call) it will be
5746 prompted for."
5747 (interactive)
5748 (let ((erc org-emphasis-regexp-components)
5749 (string "") beg end move s)
5750 (if (org-region-active-p)
5751 (setq beg (region-beginning)
5752 end (region-end)
5753 string (buffer-substring beg end))
5754 (setq move t))
5756 (unless char
5757 (message "Emphasis marker or tag: [%s]"
5758 (mapconcat #'car org-emphasis-alist ""))
5759 (setq char (read-char-exclusive)))
5760 (if (equal char ?\s)
5761 (setq s ""
5762 move nil)
5763 (unless (assoc (char-to-string char) org-emphasis-alist)
5764 (user-error "No such emphasis marker: \"%c\"" char))
5765 (setq s (char-to-string char)))
5766 (while (and (> (length string) 1)
5767 (equal (substring string 0 1) (substring string -1))
5768 (assoc (substring string 0 1) org-emphasis-alist))
5769 (setq string (substring string 1 -1)))
5770 (setq string (concat s string s))
5771 (when beg (delete-region beg end))
5772 (unless (or (bolp)
5773 (string-match (concat "[" (nth 0 erc) "\n]")
5774 (char-to-string (char-before (point)))))
5775 (insert " "))
5776 (unless (or (eobp)
5777 (string-match (concat "[" (nth 1 erc) "\n]")
5778 (char-to-string (char-after (point)))))
5779 (insert " ") (backward-char 1))
5780 (insert string)
5781 (and move (backward-char 1))))
5783 (defconst org-nonsticky-props
5784 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5786 (defsubst org-rear-nonsticky-at (pos)
5787 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5789 (defun org-activate-links (limit)
5790 "Add link properties to links.
5791 This includes angle, plain, and bracket links."
5792 (catch :exit
5793 (while (re-search-forward org-any-link-re limit t)
5794 (let* ((start (match-beginning 0))
5795 (end (match-end 0))
5796 (style (cond ((eq ?< (char-after start)) 'angle)
5797 ((eq ?\[ (char-after (1+ start))) 'bracket)
5798 (t 'plain))))
5799 (when (and (memq style org-highlight-links)
5800 ;; Do not confuse plain links with tags.
5801 (not (and (eq style 'plain)
5802 (let ((face (get-text-property
5803 (max (1- start) (point-min)) 'face)))
5804 (if (consp face) (memq 'org-tag face)
5805 (eq 'org-tag face))))))
5806 (let* ((link-object (save-excursion
5807 (goto-char start)
5808 (save-match-data (org-element-link-parser))))
5809 (link (org-element-property :raw-link link-object))
5810 (type (org-element-property :type link-object))
5811 (path (org-element-property :path link-object))
5812 (properties ;for link's visible part
5813 (list
5814 'face (pcase (org-link-get-parameter type :face)
5815 ((and (pred functionp) face) (funcall face path))
5816 ((and (pred facep) face) face)
5817 ((and (pred consp) face) face) ;anonymous
5818 (_ 'org-link))
5819 'mouse-face (or (org-link-get-parameter type :mouse-face)
5820 'highlight)
5821 'keymap (or (org-link-get-parameter type :keymap)
5822 org-mouse-map)
5823 'help-echo (pcase (org-link-get-parameter type :help-echo)
5824 ((and (pred stringp) echo) echo)
5825 ((and (pred functionp) echo) echo)
5826 (_ (concat "LINK: " link)))
5827 'htmlize-link (pcase (org-link-get-parameter type
5828 :htmlize-link)
5829 ((and (pred functionp) f) (funcall f))
5830 (_ `(:uri ,link)))
5831 'font-lock-multiline t)))
5832 (org-remove-flyspell-overlays-in start end)
5833 (org-rear-nonsticky-at end)
5834 (if (not (eq 'bracket style))
5835 (add-text-properties start end properties)
5836 ;; Handle invisible parts in bracket links.
5837 (remove-text-properties start end '(invisible nil))
5838 (let ((hidden
5839 (append `(invisible
5840 ,(or (org-link-get-parameter type :display)
5841 'org-link))
5842 properties))
5843 (visible-start (or (match-beginning 4) (match-beginning 2)))
5844 (visible-end (or (match-end 4) (match-end 2))))
5845 (add-text-properties start visible-start hidden)
5846 (add-text-properties visible-start visible-end properties)
5847 (add-text-properties visible-end end hidden)
5848 (org-rear-nonsticky-at visible-start)
5849 (org-rear-nonsticky-at visible-end)))
5850 (let ((f (org-link-get-parameter type :activate-func)))
5851 (when (functionp f)
5852 (funcall f start end path (eq style 'bracket))))
5853 (throw :exit t))))) ;signal success
5854 nil))
5856 (defun org-activate-code (limit)
5857 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5858 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5859 (remove-text-properties (match-beginning 0) (match-end 0)
5860 '(display t invisible t intangible t))
5863 (defcustom org-src-fontify-natively t
5864 "When non-nil, fontify code in code blocks.
5865 See also the `org-block' face."
5866 :type 'boolean
5867 :version "26.1"
5868 :package-version '(Org . "8.3")
5869 :group 'org-appearance
5870 :group 'org-babel)
5872 (defcustom org-allow-promoting-top-level-subtree nil
5873 "When non-nil, allow promoting a top level subtree.
5874 The leading star of the top level headline will be replaced
5875 by a #."
5876 :type 'boolean
5877 :version "24.1"
5878 :group 'org-appearance)
5880 (defun org-fontify-meta-lines-and-blocks (limit)
5881 (condition-case nil
5882 (org-fontify-meta-lines-and-blocks-1 limit)
5883 (error (message "Org mode fontification error in %S at %d"
5884 (current-buffer)
5885 (line-number-at-pos)))))
5887 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5888 "Fontify #+ lines and blocks."
5889 (let ((case-fold-search t))
5890 (when (re-search-forward
5891 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5892 limit t)
5893 (let ((beg (match-beginning 0))
5894 (block-start (match-end 0))
5895 (block-end nil)
5896 (lang (match-string 7))
5897 (beg1 (line-beginning-position 2))
5898 (dc1 (downcase (match-string 2)))
5899 (dc3 (downcase (match-string 3)))
5900 end end1 quoting block-type)
5901 (cond
5902 ((and (match-end 4) (equal dc3 "+begin"))
5903 ;; Truly a block
5904 (setq block-type (downcase (match-string 5))
5905 quoting (member block-type org-protecting-blocks))
5906 (when (re-search-forward
5907 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5908 nil t) ;; on purpose, we look further than LIMIT
5909 (setq end (min (point-max) (match-end 0))
5910 end1 (min (point-max) (1- (match-beginning 0))))
5911 (setq block-end (match-beginning 0))
5912 (when quoting
5913 (org-remove-flyspell-overlays-in beg1 end1)
5914 (remove-text-properties beg end
5915 '(display t invisible t intangible t)))
5916 (add-text-properties
5917 beg end '(font-lock-fontified t font-lock-multiline t))
5918 (add-text-properties beg beg1 '(face org-meta-line))
5919 (org-remove-flyspell-overlays-in beg beg1)
5920 (add-text-properties ; For end_src
5921 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5922 (org-remove-flyspell-overlays-in end1 end)
5923 (cond
5924 ((and lang (not (string= lang "")) org-src-fontify-natively)
5925 (org-src-font-lock-fontify-block lang block-start block-end)
5926 (add-text-properties beg1 block-end '(src-block t)))
5927 (quoting
5928 (add-text-properties beg1 (min (point-max) (1+ end1))
5929 (list 'face
5930 (list :inherit
5931 (let ((face-name
5932 (intern (format "org-block-%s" lang))))
5933 (append (and (facep face-name) (list face-name))
5934 '(org-block))))))) ; end of source block
5935 ((not org-fontify-quote-and-verse-blocks))
5936 ((string= block-type "quote")
5937 (add-face-text-property
5938 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5939 ((string= block-type "verse")
5940 (add-face-text-property
5941 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5942 (add-text-properties beg beg1 '(face org-block-begin-line))
5943 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5944 '(face org-block-end-line))
5946 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5947 (org-remove-flyspell-overlays-in
5948 (match-beginning 0)
5949 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5950 (add-text-properties
5951 beg (match-end 3)
5952 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5953 '(font-lock-fontified t invisible t)
5954 '(font-lock-fontified t face org-document-info-keyword)))
5955 (add-text-properties
5956 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5957 (if (string-equal dc1 "+title:")
5958 '(font-lock-fontified t face org-document-title)
5959 '(font-lock-fontified t face org-document-info))))
5960 ((string-prefix-p "+caption" dc1)
5961 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5962 (remove-text-properties (match-beginning 0) (match-end 0)
5963 '(display t invisible t intangible t))
5964 ;; Handle short captions.
5965 (save-excursion
5966 (beginning-of-line)
5967 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5968 (add-text-properties (line-beginning-position) (match-end 1)
5969 '(font-lock-fontified t face org-meta-line))
5970 (add-text-properties (match-end 0) (line-end-position)
5971 '(font-lock-fontified t face org-block))
5973 ((member dc3 '(" " ""))
5974 (org-remove-flyspell-overlays-in beg (match-end 0))
5975 (add-text-properties
5976 beg (match-end 0)
5977 '(font-lock-fontified t face font-lock-comment-face)))
5978 (t ;; just any other in-buffer setting, but not indented
5979 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5980 (remove-text-properties (match-beginning 0) (match-end 0)
5981 '(display t invisible t intangible t))
5982 (add-text-properties beg (match-end 0)
5983 '(font-lock-fontified t face org-meta-line))
5984 t))))))
5986 (defun org-fontify-drawers (limit)
5987 "Fontify drawers."
5988 (when (re-search-forward org-drawer-regexp limit t)
5989 (add-text-properties
5990 (match-beginning 0) (match-end 0)
5991 '(font-lock-fontified t face org-special-keyword))
5992 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (defun org-fontify-macros (limit)
5996 "Fontify macros."
5997 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
5998 (let ((begin (match-beginning 0))
5999 (opening-end (match-beginning 1)))
6000 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6001 (match-string 1))
6002 (let ((end (match-end 1))
6003 (closing-start (match-beginning 1)))
6004 (add-text-properties
6005 begin end
6006 '(font-lock-multiline t font-lock-fontified t face org-macro))
6007 (org-remove-flyspell-overlays-in begin end)
6008 (when org-hide-macro-markers
6009 (add-text-properties begin opening-end '(invisible t))
6010 (add-text-properties closing-start end '(invisible t)))
6011 t)))))
6013 (defun org-activate-footnote-links (limit)
6014 "Add text properties for footnotes."
6015 (let ((fn (org-footnote-next-reference-or-definition limit)))
6016 (when fn
6017 (let* ((beg (nth 1 fn))
6018 (end (nth 2 fn))
6019 (label (car fn))
6020 (referencep (/= (line-beginning-position) beg)))
6021 (when (and referencep (nth 3 fn))
6022 (save-excursion
6023 (goto-char beg)
6024 (search-forward (or label "fn:"))
6025 (org-remove-flyspell-overlays-in beg (match-end 0))))
6026 (add-text-properties beg end
6027 (list 'mouse-face 'highlight
6028 'keymap org-mouse-map
6029 'help-echo
6030 (if referencep "Footnote reference"
6031 "Footnote definition")
6032 'font-lock-fontified t
6033 'font-lock-multiline t
6034 'face 'org-footnote))))))
6036 (defun org-activate-dates (limit)
6037 "Add text properties for dates."
6038 (when (and (re-search-forward org-tsr-regexp-both limit t)
6039 (not (equal (char-before (match-beginning 0)) 91)))
6040 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6041 (add-text-properties (match-beginning 0) (match-end 0)
6042 (list 'mouse-face 'highlight
6043 'keymap org-mouse-map))
6044 (org-rear-nonsticky-at (match-end 0))
6045 (when org-display-custom-times
6046 ;; If it's a date range, activate custom time for second date.
6047 (when (match-end 3)
6048 (org-display-custom-time (match-beginning 3) (match-end 3)))
6049 (org-display-custom-time (match-beginning 1) (match-end 1)))
6052 (defvar-local org-target-link-regexp nil
6053 "Regular expression matching radio targets in plain text.")
6055 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6056 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6057 border border border))
6058 "Regular expression matching a link target.")
6060 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6061 "Regular expression matching a radio target.")
6063 (defconst org-any-target-regexp
6064 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6065 "Regular expression matching any target.")
6067 (defun org-activate-target-links (limit)
6068 "Add text properties for target matches."
6069 (when org-target-link-regexp
6070 (let ((case-fold-search t))
6071 (when (re-search-forward org-target-link-regexp limit t)
6072 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6073 (add-text-properties (match-beginning 1) (match-end 1)
6074 (list 'mouse-face 'highlight
6075 'keymap org-mouse-map
6076 'help-echo "Radio target link"
6077 'org-linked-text t))
6078 (org-rear-nonsticky-at (match-end 1))
6079 t))))
6081 (defun org-update-radio-target-regexp ()
6082 "Find all radio targets in this file and update the regular expression.
6083 Also refresh fontification if needed."
6084 (interactive)
6085 (let ((old-regexp org-target-link-regexp)
6086 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6087 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6088 (targets
6089 (org-with-wide-buffer
6090 (goto-char (point-min))
6091 (let (rtn)
6092 (while (re-search-forward org-radio-target-regexp nil t)
6093 ;; Make sure point is really within the object.
6094 (backward-char)
6095 (let ((obj (org-element-context)))
6096 (when (eq (org-element-type obj) 'radio-target)
6097 (cl-pushnew (org-element-property :value obj) rtn
6098 :test #'equal))))
6099 rtn))))
6100 (setq org-target-link-regexp
6101 (and targets
6102 (concat before-re
6103 (mapconcat
6104 (lambda (x)
6105 (replace-regexp-in-string
6106 " +" "\\s-+" (regexp-quote x) t t))
6107 targets
6108 "\\|")
6109 after-re)))
6110 (unless (equal old-regexp org-target-link-regexp)
6111 ;; Clean-up cache.
6112 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6113 ((not org-target-link-regexp) old-regexp)
6115 (concat before-re
6116 (mapconcat
6117 (lambda (re)
6118 (substring re (length before-re)
6119 (- (length after-re))))
6120 (list old-regexp org-target-link-regexp)
6121 "\\|")
6122 after-re)))))
6123 (org-with-wide-buffer
6124 (goto-char (point-min))
6125 (while (re-search-forward regexp nil t)
6126 (org-element-cache-refresh (match-beginning 1)))))
6127 ;; Re fontify buffer.
6128 (when (memq 'radio org-highlight-links)
6129 (org-restart-font-lock)))))
6131 (defvar org-latex-and-related-regexp nil
6132 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6134 (defun org-compute-latex-and-related-regexp ()
6135 "Compute regular expression for LaTeX, entities and sub/superscript.
6136 Result depends on variable `org-highlight-latex-and-related'."
6137 (setq-local
6138 org-latex-and-related-regexp
6139 (let* ((re-sub
6140 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6141 ((eq org-use-sub-superscripts '{})
6142 (list org-match-substring-with-braces-regexp))
6143 (org-use-sub-superscripts (list org-match-substring-regexp))))
6144 (re-latex
6145 (when (memq 'latex org-highlight-latex-and-related)
6146 (let ((matchers (plist-get org-format-latex-options :matchers)))
6147 (delq nil
6148 (mapcar (lambda (x)
6149 (and (member (car x) matchers) (nth 1 x)))
6150 org-latex-regexps)))))
6151 (re-entities
6152 (when (memq 'entities org-highlight-latex-and-related)
6153 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6154 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6156 (defun org-do-latex-and-related (limit)
6157 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6158 LIMIT bounds the search for syntax to highlight. Stop at first
6159 highlighted object, if any. Return t if some highlighting was
6160 done, nil otherwise."
6161 (when (org-string-nw-p org-latex-and-related-regexp)
6162 (catch 'found
6163 (while (re-search-forward org-latex-and-related-regexp limit t)
6164 (unless
6165 (cl-some
6166 (lambda (f)
6167 (memq f '(org-code org-verbatim underline org-special-keyword)))
6168 (save-excursion
6169 (goto-char (1+ (match-beginning 0)))
6170 (face-at-point nil t)))
6171 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6172 '(?_ ?^))
6174 0)))
6175 (font-lock-prepend-text-property
6176 (+ offset (match-beginning 0)) (match-end 0)
6177 'face 'org-latex-and-related)
6178 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6179 '(font-lock-multiline t)))
6180 (throw 'found t)))
6181 nil)))
6183 (defun org-restart-font-lock ()
6184 "Restart `font-lock-mode', to force refontification."
6185 (when (and (boundp 'font-lock-mode) font-lock-mode)
6186 (font-lock-mode -1)
6187 (font-lock-mode 1)))
6189 (defun org-activate-tags (limit)
6190 (when (re-search-forward
6191 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6192 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6193 (add-text-properties (match-beginning 1) (match-end 1)
6194 (list 'mouse-face 'highlight
6195 'keymap org-mouse-map))
6196 (org-rear-nonsticky-at (match-end 1))
6199 (defun org-outline-level ()
6200 "Compute the outline level of the heading at point.
6202 If this is called at a normal headline, the level is the number
6203 of stars. Use `org-reduced-level' to remove the effect of
6204 `org-odd-levels'. Unlike to `org-current-level', this function
6205 takes into consideration inlinetasks."
6206 (org-with-wide-buffer
6207 (end-of-line)
6208 (if (re-search-backward org-outline-regexp-bol nil t)
6209 (1- (- (match-end 0) (match-beginning 0)))
6210 0)))
6212 (defvar org-font-lock-keywords nil)
6214 (defsubst org-re-property (property &optional literal allow-null value)
6215 "Return a regexp matching a PROPERTY line.
6217 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6218 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6219 non-nil, match properties even without a value.
6221 Match group 3 is set to the value when it exists. If there is no
6222 value and ALLOW-NULL is non-nil, it is set to the empty string.
6224 With optional argument VALUE, match only property lines with
6225 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6226 unless LITERAL is non-nil."
6227 (concat
6228 "^\\(?4:[ \t]*\\)"
6229 (format "\\(?1::\\(?2:%s\\):\\)"
6230 (if literal property (regexp-quote property)))
6231 (cond (value
6232 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6233 (if literal value (regexp-quote value))))
6234 (allow-null
6235 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6237 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6239 (defconst org-property-re
6240 (org-re-property "\\S-+" 'literal t)
6241 "Regular expression matching a property line.
6242 There are four matching groups:
6243 1: :PROPKEY: including the leading and trailing colon,
6244 2: PROPKEY without the leading and trailing colon,
6245 3: PROPVAL without leading or trailing spaces,
6246 4: the indentation of the current line,
6247 5: trailing whitespace.")
6249 (defvar org-font-lock-hook nil
6250 "Functions to be called for special font lock stuff.")
6252 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6254 (defvar org-font-lock-set-keywords-hook nil
6255 "Functions that can manipulate `org-font-lock-extra-keywords'.
6256 This is called after `org-font-lock-extra-keywords' is defined, but before
6257 it is installed to be used by font lock. This can be useful if something
6258 needs to be inserted at a specific position in the font-lock sequence.")
6260 (defun org-font-lock-hook (limit)
6261 "Run `org-font-lock-hook' within LIMIT."
6262 (run-hook-with-args 'org-font-lock-hook limit))
6264 (defun org-set-font-lock-defaults ()
6265 "Set font lock defaults for the current buffer."
6266 (let* ((em org-fontify-emphasized-text)
6267 (lk org-highlight-links)
6268 (org-font-lock-extra-keywords
6269 (list
6270 ;; Call the hook
6271 '(org-font-lock-hook)
6272 ;; Headlines
6273 `(,(if org-fontify-whole-heading-line
6274 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6275 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6276 (1 (org-get-level-face 1))
6277 (2 (org-get-level-face 2))
6278 (3 (org-get-level-face 3)))
6279 ;; Table lines
6280 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6281 (1 'org-table t))
6282 ;; Table internals
6283 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6284 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6285 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6286 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6287 ;; Drawers
6288 '(org-fontify-drawers)
6289 ;; Properties
6290 (list org-property-re
6291 '(1 'org-special-keyword t)
6292 '(3 'org-property-value t))
6293 ;; Link related fontification.
6294 '(org-activate-links)
6295 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6296 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6297 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6298 (when (memq 'footnote lk) '(org-activate-footnote-links))
6299 ;; Targets.
6300 (list org-any-target-regexp '(0 'org-target t))
6301 ;; Diary sexps.
6302 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6303 ;; Macro
6304 '(org-fontify-macros)
6305 ;; TODO keyword
6306 (list (format org-heading-keyword-regexp-format
6307 org-todo-regexp)
6308 '(2 (org-get-todo-face 2) t))
6309 ;; DONE
6310 (if org-fontify-done-headline
6311 (list (format org-heading-keyword-regexp-format
6312 (concat
6313 "\\(?:"
6314 (mapconcat 'regexp-quote org-done-keywords "\\|")
6315 "\\)"))
6316 '(2 'org-headline-done t))
6317 nil)
6318 ;; Priorities
6319 '(org-font-lock-add-priority-faces)
6320 ;; Tags
6321 '(org-font-lock-add-tag-faces)
6322 ;; Tags groups
6323 (when (and org-group-tags org-tag-groups-alist)
6324 (list (concat org-outline-regexp-bol ".+\\(:"
6325 (regexp-opt (mapcar 'car org-tag-groups-alist))
6326 ":\\).*$")
6327 '(1 'org-tag-group prepend)))
6328 ;; Special keywords
6329 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6330 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6331 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6332 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6333 ;; Emphasis
6334 (when em '(org-do-emphasis-faces))
6335 ;; Checkboxes
6336 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6337 1 'org-checkbox prepend)
6338 (when (cdr (assq 'checkbox org-list-automatic-rules))
6339 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6340 (0 (org-get-checkbox-statistics-face) t)))
6341 ;; Description list items
6342 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6343 1 'org-list-dt prepend)
6344 ;; ARCHIVEd headings
6345 (list (concat
6346 org-outline-regexp-bol
6347 "\\(.*:" org-archive-tag ":.*\\)")
6348 '(1 'org-archived prepend))
6349 ;; Specials
6350 '(org-do-latex-and-related)
6351 '(org-fontify-entities)
6352 '(org-raise-scripts)
6353 ;; Code
6354 '(org-activate-code (1 'org-code t))
6355 ;; COMMENT
6356 (list (format
6357 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6358 org-todo-regexp
6359 org-comment-string)
6360 '(9 'org-special-keyword t))
6361 ;; Blocks and meta lines
6362 '(org-fontify-meta-lines-and-blocks))))
6363 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6364 (run-hooks 'org-font-lock-set-keywords-hook)
6365 ;; Now set the full font-lock-keywords
6366 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6367 (setq-local font-lock-defaults
6368 '(org-font-lock-keywords t nil nil backward-paragraph))
6369 (kill-local-variable 'font-lock-keywords)
6370 nil))
6372 (defun org-toggle-pretty-entities ()
6373 "Toggle the composition display of entities as UTF8 characters."
6374 (interactive)
6375 (setq-local org-pretty-entities (not org-pretty-entities))
6376 (org-restart-font-lock)
6377 (if org-pretty-entities
6378 (message "Entities are now displayed as UTF8 characters")
6379 (save-restriction
6380 (widen)
6381 (decompose-region (point-min) (point-max))
6382 (message "Entities are now displayed as plain text"))))
6384 (defvar-local org-custom-properties-overlays nil
6385 "List of overlays used for custom properties.")
6387 (defun org-toggle-custom-properties-visibility ()
6388 "Display or hide properties in `org-custom-properties'."
6389 (interactive)
6390 (if org-custom-properties-overlays
6391 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6392 (setq org-custom-properties-overlays nil))
6393 (when org-custom-properties
6394 (org-with-wide-buffer
6395 (goto-char (point-min))
6396 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6397 (while (re-search-forward regexp nil t)
6398 (let ((end (cdr (save-match-data (org-get-property-block)))))
6399 (when (and end (< (point) end))
6400 ;; Hide first custom property in current drawer.
6401 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6402 (overlay-put o 'invisible t)
6403 (overlay-put o 'org-custom-property t)
6404 (push o org-custom-properties-overlays))
6405 ;; Hide additional custom properties in the same drawer.
6406 (while (re-search-forward regexp end t)
6407 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6408 (overlay-put o 'invisible t)
6409 (overlay-put o 'org-custom-property t)
6410 (push o org-custom-properties-overlays)))))
6411 ;; Each entry is limited to a single property drawer.
6412 (outline-next-heading)))))))
6414 (defun org-fontify-entities (limit)
6415 "Find an entity to fontify."
6416 (let (ee)
6417 (when org-pretty-entities
6418 (catch 'match
6419 ;; "\_ "-family is left out on purpose. Only the first one,
6420 ;; i.e., "\_ ", could be fontified anyway, and it would be
6421 ;; confusing when adding a second white space character.
6422 (while (re-search-forward
6423 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6424 limit t)
6425 (when (and (not (org-at-comment-p))
6426 (setq ee (org-entity-get (match-string 1)))
6427 (= (length (nth 6 ee)) 1))
6428 (let* ((end (if (equal (match-string 2) "{}")
6429 (match-end 2)
6430 (match-end 1))))
6431 (add-text-properties
6432 (match-beginning 0) end
6433 (list 'font-lock-fontified t))
6434 (compose-region (match-beginning 0) end
6435 (nth 6 ee) nil)
6436 (backward-char 1)
6437 (throw 'match t))))
6438 nil))))
6440 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6441 "Fontify string S like in Org mode."
6442 (with-temp-buffer
6443 (insert s)
6444 (let ((org-odd-levels-only odd-levels))
6445 (org-mode)
6446 (org-font-lock-ensure)
6447 (buffer-string))))
6449 (defvar org-m nil)
6450 (defvar org-l nil)
6451 (defvar org-f nil)
6452 (defun org-get-level-face (n)
6453 "Get the right face for match N in font-lock matching of headlines."
6454 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6455 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6456 (if org-cycle-level-faces
6457 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6458 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6459 (cond
6460 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6461 ((eq n 2) org-f)
6462 (t (unless org-level-color-stars-only org-f))))
6464 (defun org-face-from-face-or-color (context inherit face-or-color)
6465 "Create a face list that inherits INHERIT, but sets the foreground color.
6466 When FACE-OR-COLOR is not a string, just return it."
6467 (if (stringp face-or-color)
6468 (list :inherit inherit
6469 (cdr (assoc context org-faces-easy-properties))
6470 face-or-color)
6471 face-or-color))
6473 (defun org-get-todo-face (kwd)
6474 "Get the right face for a TODO keyword KWD.
6475 If KWD is a number, get the corresponding match group."
6476 (when (numberp kwd) (setq kwd (match-string kwd)))
6477 (or (org-face-from-face-or-color
6478 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6479 (and (member kwd org-done-keywords) 'org-done)
6480 'org-todo))
6482 (defun org-get-priority-face (priority)
6483 "Get the right face for PRIORITY.
6484 PRIORITY is a character."
6485 (or (org-face-from-face-or-color
6486 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6487 'org-priority))
6489 (defun org-get-tag-face (tag)
6490 "Get the right face for TAG.
6491 If TAG is a number, get the corresponding match group."
6492 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6493 (or (org-face-from-face-or-color
6494 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6495 'org-tag)))
6497 (defun org-font-lock-add-priority-faces (limit)
6498 "Add the special priority faces."
6499 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6500 (add-text-properties
6501 (match-beginning 1) (match-end 1)
6502 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6503 'font-lock-fontified t))))
6505 (defun org-font-lock-add-tag-faces (limit)
6506 "Add the special tag faces."
6507 (when (and org-tag-faces org-tags-special-faces-re)
6508 (while (re-search-forward org-tags-special-faces-re limit t)
6509 (add-text-properties (match-beginning 1) (match-end 1)
6510 (list 'face (org-get-tag-face 1)
6511 'font-lock-fontified t))
6512 (backward-char 1))))
6514 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6515 "Remove fontification and activation overlays from links."
6516 (font-lock-default-unfontify-region beg end)
6517 (let* ((buffer-undo-list t)
6518 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6519 (inhibit-modification-hooks t)
6520 deactivate-mark buffer-file-name buffer-file-truename)
6521 (decompose-region beg end)
6522 (remove-text-properties beg end
6523 '(mouse-face t keymap t org-linked-text t
6524 invisible t intangible t
6525 org-emphasis t))
6526 (org-remove-font-lock-display-properties beg end)))
6528 (defconst org-script-display '(((raise -0.3) (height 0.7))
6529 ((raise 0.3) (height 0.7))
6530 ((raise -0.5))
6531 ((raise 0.5)))
6532 "Display properties for showing superscripts and subscripts.")
6534 (defun org-remove-font-lock-display-properties (beg end)
6535 "Remove specific display properties that have been added by font lock.
6536 The will remove the raise properties that are used to show superscripts
6537 and subscripts."
6538 (let (next prop)
6539 (while (< beg end)
6540 (setq next (next-single-property-change beg 'display nil end)
6541 prop (get-text-property beg 'display))
6542 (when (member prop org-script-display)
6543 (put-text-property beg next 'display nil))
6544 (setq beg next))))
6546 (defun org-raise-scripts (limit)
6547 "Add raise properties to sub/superscripts."
6548 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6549 (re-search-forward
6550 (if (eq org-use-sub-superscripts t)
6551 org-match-substring-regexp
6552 org-match-substring-with-braces-regexp)
6553 limit t))
6554 (let* ((pos (point)) table-p comment-p
6555 (mpos (match-beginning 3))
6556 (emph-p (get-text-property mpos 'org-emphasis))
6557 (link-p (get-text-property mpos 'mouse-face))
6558 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6559 (goto-char (point-at-bol))
6560 (setq table-p (looking-at-p org-table-dataline-regexp)
6561 comment-p (looking-at-p "^[ \t]*#[ +]"))
6562 (goto-char pos)
6563 ;; Handle a_b^c
6564 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6565 (unless (or comment-p emph-p link-p keyw-p)
6566 (put-text-property (match-beginning 3) (match-end 0)
6567 'display
6568 (if (equal (char-after (match-beginning 2)) ?^)
6569 (nth (if table-p 3 1) org-script-display)
6570 (nth (if table-p 2 0) org-script-display)))
6571 (add-text-properties (match-beginning 2) (match-end 2)
6572 (list 'invisible t))
6573 (when (and (eq (char-after (match-beginning 3)) ?{)
6574 (eq (char-before (match-end 3)) ?}))
6575 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6576 (list 'invisible t))
6577 (add-text-properties (1- (match-end 3)) (match-end 3)
6578 (list 'invisible t))))
6579 t)))
6581 (defun org-remove-empty-overlays-at (pos)
6582 "Remove outline overlays that do not contain non-white stuff."
6583 (dolist (o (overlays-at pos))
6584 (and (eq 'outline (overlay-get o 'invisible))
6585 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6586 (overlay-end o))))
6587 (delete-overlay o))))
6589 (defun org-show-empty-lines-in-parent ()
6590 "Move to the parent and re-show empty lines before visible headlines."
6591 (save-excursion
6592 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6593 (org-cycle-show-empty-lines context))))
6595 (defun org-files-list ()
6596 "Return `org-agenda-files' list, plus all open Org files.
6597 This is useful for operations that need to scan all of a user's
6598 open and agenda-wise Org files."
6599 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6600 (dolist (buf (buffer-list))
6601 (with-current-buffer buf
6602 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6603 (cl-pushnew (expand-file-name (buffer-file-name)) files
6604 :test #'equal))))
6605 files))
6607 (defsubst org-entry-beginning-position ()
6608 "Return the beginning position of the current entry."
6609 (save-excursion (org-back-to-heading t) (point)))
6611 (defsubst org-entry-end-position ()
6612 "Return the end position of the current entry."
6613 (save-excursion (outline-next-heading) (point)))
6615 (defun org-subtree-end-visible-p ()
6616 "Is the end of the current subtree visible?"
6617 (pos-visible-in-window-p
6618 (save-excursion (org-end-of-subtree t) (point))))
6620 (defun org-first-headline-recenter ()
6621 "Move cursor to the first headline and recenter the headline."
6622 (let ((window (get-buffer-window)))
6623 (when window
6624 (goto-char (point-min))
6625 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6626 (set-window-start window (line-beginning-position))))))
6629 ;;; Visibility (headlines, blocks, drawers)
6631 ;;;; Headlines visibility
6633 (defun org-show-entry ()
6634 "Show the body directly following this heading.
6635 Show the heading too, if it is currently invisible."
6636 (interactive)
6637 (save-excursion
6638 (ignore-errors
6639 (org-back-to-heading t)
6640 (org-flag-region
6641 (line-end-position 0)
6642 (save-excursion
6643 (if (re-search-forward
6644 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6645 (match-beginning 1)
6646 (point-max)))
6648 'outline))))
6650 (defun org-show-children (&optional level)
6651 "Show all direct subheadings of this heading.
6652 Prefix arg LEVEL is how many levels below the current level
6653 should be shown. Default is enough to cause the following
6654 heading to appear."
6655 (interactive "p")
6656 (save-excursion
6657 (org-back-to-heading t)
6658 (let* ((current-level (funcall outline-level))
6659 (max-level (org-get-valid-level
6660 current-level
6661 (if level (prefix-numeric-value level) 1)))
6662 (end (save-excursion (org-end-of-subtree t t)))
6663 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6664 (past-first-child nil)
6665 ;; Make sure to skip inlinetasks.
6666 (re (format regexp-fmt
6667 current-level
6668 (cond
6669 ((not (featurep 'org-inlinetask)) "")
6670 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6672 (t (1- org-inlinetask-min-level))))))
6673 ;; Display parent heading.
6674 (org-flag-heading nil)
6675 (forward-line)
6676 ;; Display children. First child may be deeper than expected
6677 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6678 ;; MAX-LEVEL accordingly.
6679 (while (re-search-forward re end t)
6680 (unless past-first-child
6681 (setq re (format regexp-fmt
6682 current-level
6683 (max (funcall outline-level) max-level)))
6684 (setq past-first-child t))
6685 (org-flag-heading nil)))))
6687 (defun org-show-subtree ()
6688 "Show everything after this heading at deeper levels."
6689 (interactive)
6690 (org-flag-region
6691 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6693 ;;;; Blocks visibility
6695 (defun org-hide-block-toggle-maybe ()
6696 "Toggle visibility of block at point.
6697 Unlike to `org-hide-block-toggle', this function does not throw
6698 an error. Return a non-nil value when toggling is successful."
6699 (interactive)
6700 (ignore-errors (org-hide-block-toggle)))
6702 (defun org-hide-block-toggle (&optional force)
6703 "Toggle the visibility of the current block.
6704 When optional argument FORCE is `off', make block visible. If it
6705 is non-nil, hide it unconditionally. Throw an error when not at
6706 a block. Return a non-nil value when toggling is successful."
6707 (interactive)
6708 (let ((element (org-element-at-point)))
6709 (unless (memq (org-element-type element)
6710 '(center-block comment-block dynamic-block example-block
6711 export-block quote-block special-block
6712 src-block verse-block))
6713 (user-error "Not at a block"))
6714 (let* ((post (org-element-property :post-affiliated element))
6715 (start (save-excursion
6716 (goto-char post)
6717 (line-end-position)))
6718 (end (save-excursion
6719 (goto-char (org-element-property :end element))
6720 (skip-chars-backward " \t\n")
6721 (line-end-position))))
6722 ;; Do nothing when not before or at the block opening line or at
6723 ;; the block closing line.
6724 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6725 (cond ((eq force 'off)
6726 (org-flag-region start end nil 'org-hide-block))
6727 (force
6728 (org-flag-region start end t 'org-hide-block))
6729 ((eq (get-char-property start 'invisible) 'org-hide-block)
6730 (org-flag-region start end nil 'org-hide-block))
6732 (org-flag-region start end t 'org-hide-block)))
6733 ;; When the block is hidden away, make sure point is left in
6734 ;; a visible part of the buffer.
6735 (when (invisible-p (max (1- (point)) (point-min)))
6736 (goto-char post))
6737 ;; Signal success.
6738 t))))
6740 (defun org-hide-block-toggle-all ()
6741 "Toggle the visibility of all blocks in the current buffer."
6742 (org-block-map 'org-hide-block-toggle))
6744 (defun org-hide-block-all ()
6745 "Fold all blocks in the current buffer."
6746 (interactive)
6747 (org-show-all '(blocks))
6748 (org-block-map 'org-hide-block-toggle-maybe))
6750 ;;;; Drawers visibility
6752 (defun org-cycle-hide-drawers (state &optional exceptions)
6753 "Re-hide all drawers after a visibility state change.
6754 STATE should be one of the symbols listed in the docstring of
6755 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6756 a list of strings specifying which drawers should not be hidden."
6757 (when (and (derived-mode-p 'org-mode)
6758 (not (memq state '(overview folded contents))))
6759 (save-excursion
6760 (let* ((globalp (eq state 'all))
6761 (beg (if globalp (point-min) (point)))
6762 (end (if globalp (point-max)
6763 (if (eq state 'children)
6764 (save-excursion (outline-next-heading) (point))
6765 (org-end-of-subtree t)))))
6766 (goto-char beg)
6767 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6768 (unless (member-ignore-case (match-string 1) exceptions)
6769 (let ((drawer (org-element-at-point)))
6770 (when (memq (org-element-type drawer) '(drawer property-drawer))
6771 (org-flag-drawer t drawer)
6772 ;; Make sure to skip drawer entirely or we might flag
6773 ;; it another time when matching its ending line with
6774 ;; `org-drawer-regexp'.
6775 (goto-char (org-element-property :end drawer))))))))))
6777 (defun org-flag-drawer (flag &optional element)
6778 "When FLAG is non-nil, hide the drawer we are at.
6779 Otherwise make it visible. When optional argument ELEMENT is
6780 a parsed drawer, as returned by `org-element-at-point', hide or
6781 show that drawer instead."
6782 (let ((drawer (or element
6783 (and (save-excursion
6784 (beginning-of-line)
6785 (looking-at-p org-drawer-regexp))
6786 (org-element-at-point)))))
6787 (when (memq (org-element-type drawer) '(drawer property-drawer))
6788 (let ((post (org-element-property :post-affiliated drawer)))
6789 (org-flag-region
6790 (save-excursion (goto-char post) (line-end-position))
6791 (save-excursion (goto-char (org-element-property :end drawer))
6792 (skip-chars-backward " \t\n")
6793 (line-end-position))
6794 flag 'org-hide-drawer)
6795 ;; When the drawer is hidden away, make sure point lies in
6796 ;; a visible part of the buffer.
6797 (when (invisible-p (max (1- (point)) (point-min)))
6798 (goto-char post))))))
6800 ;;;; Visibility cycling
6802 (defvar-local org-cycle-global-status nil)
6803 (put 'org-cycle-global-status 'org-state t)
6804 (defvar-local org-cycle-subtree-status nil)
6805 (put 'org-cycle-subtree-status 'org-state t)
6807 (defun org-show-all (&optional types)
6808 "Show all contents in the visible part of the buffer.
6809 By default, the function expands headings, blocks and drawers.
6810 When optional argument TYPE is a list of symbols among `blocks',
6811 `drawers' and `headings', to only expand one specific type."
6812 (dolist (type (or types '(blocks drawers headings)))
6813 (org-flag-region (point-min) (point-max) nil
6814 (pcase type
6815 (`blocks 'org-hide-block)
6816 (`drawers 'org-hide-drawer)
6817 (`headings 'outline)
6818 (_ (error "Invalid type: %S" type))))))
6820 ;;;###autoload
6821 (defun org-cycle (&optional arg)
6822 "TAB-action and visibility cycling for Org mode.
6824 This is the command invoked in Org mode by the `TAB' key. Its main
6825 purpose is outline visibility cycling, but it also invokes other actions
6826 in special contexts.
6828 When this function is called with a `\\[universal-argument]' prefix, rotate \
6829 the entire
6830 buffer through 3 states (global cycling)
6831 1. OVERVIEW: Show only top-level headlines.
6832 2. CONTENTS: Show all headlines of all levels, but no body text.
6833 3. SHOW ALL: Show everything.
6835 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6836 switch to the startup visibility,
6837 determined by the variable `org-startup-folded', and by any VISIBILITY
6838 properties in the buffer.
6840 With a `\\[universal-argument] \\[universal-argument] \
6841 \\[universal-argument]' prefix argument, show the entire buffer, including
6842 any drawers.
6844 When inside a table, re-align the table and move to the next field.
6846 When point is at the beginning of a headline, rotate the subtree started
6847 by this line through 3 different states (local cycling)
6848 1. FOLDED: Only the main headline is shown.
6849 2. CHILDREN: The main headline and the direct children are shown.
6850 From this state, you can move to one of the children
6851 and zoom in further.
6852 3. SUBTREE: Show the entire subtree, including body text.
6853 If there is no subtree, switch directly from CHILDREN to FOLDED.
6855 When point is at the beginning of an empty headline and the variable
6856 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6857 of the headline by demoting and promoting it to likely levels. This
6858 speeds up creation document structure by pressing `TAB' once or several
6859 times right after creating a new headline.
6861 When there is a numeric prefix, go up to a heading with level ARG, do
6862 a `show-subtree' and return to the previous cursor position. If ARG
6863 is negative, go up that many levels.
6865 When point is not at the beginning of a headline, execute the global
6866 binding for `TAB', which is re-indenting the line. See the option
6867 `org-cycle-emulate-tab' for details.
6869 As a special case, if point is at the beginning of the buffer and there is
6870 no headline in line 1, this function will act as if called with prefix arg
6871 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6872 prefix arg, but only
6873 if the variable `org-cycle-global-at-bob' is t."
6874 (interactive "P")
6875 (org-load-modules-maybe)
6876 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6877 (and org-cycle-level-after-item/entry-creation
6878 (or (org-cycle-level)
6879 (org-cycle-item-indentation))))
6880 (let* ((limit-level
6881 (or org-cycle-max-level
6882 (and (boundp 'org-inlinetask-min-level)
6883 org-inlinetask-min-level
6884 (1- org-inlinetask-min-level))))
6885 (nstars (and limit-level
6886 (if org-odd-levels-only
6887 (and limit-level (1- (* limit-level 2)))
6888 limit-level)))
6889 (org-outline-regexp
6890 (if (not (derived-mode-p 'org-mode))
6891 outline-regexp
6892 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6893 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6894 (not (looking-at org-outline-regexp))))
6895 (org-cycle-hook
6896 (if bob-special
6897 (delq 'org-optimize-window-after-visibility-change
6898 (copy-sequence org-cycle-hook))
6899 org-cycle-hook))
6900 (pos (point)))
6902 (cond
6904 ((equal arg '(16))
6905 (setq last-command 'dummy)
6906 (org-set-startup-visibility)
6907 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6909 ((equal arg '(64))
6910 (org-show-all)
6911 (org-unlogged-message "Entire buffer visible, including drawers"))
6913 ((equal arg '(4)) (org-cycle-internal-global))
6915 ;; Try hiding block at point.
6916 ((org-hide-block-toggle-maybe))
6918 ;; Try cdlatex TAB completion
6919 ((org-try-cdlatex-tab))
6921 ;; Table: enter it or move to the next field.
6922 ((org-at-table-p 'any)
6923 (if (org-at-table.el-p)
6924 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6925 Use `\\[org-edit-special]' to edit table.el tables"))
6926 (if arg (org-table-edit-field t)
6927 (org-table-justify-field-maybe)
6928 (call-interactively 'org-table-next-field))))
6930 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6932 ;; Global cycling: delegate to `org-cycle-internal-global'.
6933 (bob-special (org-cycle-internal-global))
6935 ;; Drawers: delegate to `org-flag-drawer'.
6936 ((save-excursion
6937 (beginning-of-line 1)
6938 (looking-at org-drawer-regexp))
6939 (org-flag-drawer ; toggle block visibility
6940 (not (get-char-property (match-end 0) 'invisible))))
6942 ;; Show-subtree, ARG levels up from here.
6943 ((integerp arg)
6944 (save-excursion
6945 (org-back-to-heading)
6946 (outline-up-heading (if (< arg 0) (- arg)
6947 (- (funcall outline-level) arg)))
6948 (org-show-subtree)))
6950 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6951 ((and (featurep 'org-inlinetask)
6952 (org-inlinetask-at-task-p)
6953 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6954 (org-inlinetask-toggle-visibility))
6956 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6957 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6958 (save-excursion (move-beginning-of-line 1)
6959 (looking-at org-outline-regexp)))
6960 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6961 (org-cycle-internal-local))
6963 ;; From there: TAB emulation and template completion.
6964 (buffer-read-only (org-back-to-heading))
6966 ((run-hook-with-args-until-success
6967 'org-tab-after-check-for-cycling-hook))
6969 ((run-hook-with-args-until-success
6970 'org-tab-before-tab-emulation-hook))
6972 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6973 (or (not (bolp))
6974 (not (looking-at org-outline-regexp))))
6975 (call-interactively (global-key-binding "\t")))
6977 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6978 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6979 (or (and (eq org-cycle-emulate-tab 'white)
6980 (= (match-end 0) (point-at-eol)))
6981 (and (eq org-cycle-emulate-tab 'whitestart)
6982 (>= (match-end 0) pos))))
6984 (eq org-cycle-emulate-tab t))
6985 (call-interactively (global-key-binding "\t")))
6987 (t (save-excursion
6988 (org-back-to-heading)
6989 (org-cycle)))))))
6991 (defun org-cycle-internal-global ()
6992 "Do the global cycling action."
6993 ;; Hack to avoid display of messages for .org attachments in Gnus
6994 (let ((ga (string-match "\\*fontification" (buffer-name))))
6995 (cond
6996 ((and (eq last-command this-command)
6997 (eq org-cycle-global-status 'overview))
6998 ;; We just created the overview - now do table of contents
6999 ;; This can be slow in very large buffers, so indicate action
7000 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7001 (unless ga (org-unlogged-message "CONTENTS..."))
7002 (org-content)
7003 (unless ga (org-unlogged-message "CONTENTS...done"))
7004 (setq org-cycle-global-status 'contents)
7005 (run-hook-with-args 'org-cycle-hook 'contents))
7007 ((and (eq last-command this-command)
7008 (eq org-cycle-global-status 'contents))
7009 ;; We just showed the table of contents - now show everything
7010 (run-hook-with-args 'org-pre-cycle-hook 'all)
7011 (org-show-all '(headings blocks))
7012 (unless ga (org-unlogged-message "SHOW ALL"))
7013 (setq org-cycle-global-status 'all)
7014 (run-hook-with-args 'org-cycle-hook 'all))
7017 ;; Default action: go to overview
7018 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7019 (org-overview)
7020 (unless ga (org-unlogged-message "OVERVIEW"))
7021 (setq org-cycle-global-status 'overview)
7022 (run-hook-with-args 'org-cycle-hook 'overview)))))
7024 (defvar org-called-with-limited-levels nil
7025 "Non-nil when `org-with-limited-levels' is currently active.")
7027 (defun org-cycle-internal-local ()
7028 "Do the local cycling action."
7029 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7030 ;; First, determine end of headline (EOH), end of subtree or item
7031 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7032 (save-excursion
7033 (if (org-at-item-p)
7034 (progn
7035 (beginning-of-line)
7036 (setq struct (org-list-struct))
7037 (setq eoh (point-at-eol))
7038 (setq eos (org-list-get-item-end-before-blank (point) struct))
7039 (setq has-children (org-list-has-child-p (point) struct)))
7040 (org-back-to-heading)
7041 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7042 (setq eos (save-excursion (org-end-of-subtree t t)
7043 (when (bolp) (backward-char)) (point)))
7044 (setq has-children
7045 (or (save-excursion
7046 (let ((level (funcall outline-level)))
7047 (outline-next-heading)
7048 (and (org-at-heading-p t)
7049 (> (funcall outline-level) level))))
7050 (save-excursion
7051 (org-list-search-forward (org-item-beginning-re) eos t)))))
7052 ;; Determine end invisible part of buffer (EOL)
7053 (beginning-of-line 2)
7054 (while (and (not (eobp)) ;This is like `next-line'.
7055 (get-char-property (1- (point)) 'invisible))
7056 (goto-char (next-single-char-property-change (point) 'invisible))
7057 (and (eolp) (beginning-of-line 2)))
7058 (setq eol (point)))
7059 ;; Find out what to do next and set `this-command'
7060 (cond
7061 ((= eos eoh)
7062 ;; Nothing is hidden behind this heading
7063 (unless (org-before-first-heading-p)
7064 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7065 (org-unlogged-message "EMPTY ENTRY")
7066 (setq org-cycle-subtree-status nil)
7067 (save-excursion
7068 (goto-char eos)
7069 (outline-next-heading)
7070 (when (org-invisible-p) (org-flag-heading nil))))
7071 ((and (or (>= eol eos)
7072 (not (string-match "\\S-" (buffer-substring eol eos))))
7073 (or has-children
7074 (not (setq children-skipped
7075 org-cycle-skip-children-state-if-no-children))))
7076 ;; Entire subtree is hidden in one line: children view
7077 (unless (org-before-first-heading-p)
7078 (run-hook-with-args 'org-pre-cycle-hook 'children))
7079 (if (org-at-item-p)
7080 (org-list-set-item-visibility (point-at-bol) struct 'children)
7081 (org-show-entry)
7082 (org-with-limited-levels (org-show-children))
7083 (org-show-set-visibility 'canonical)
7084 ;; Fold every list in subtree to top-level items.
7085 (when (eq org-cycle-include-plain-lists 'integrate)
7086 (save-excursion
7087 (org-back-to-heading)
7088 (while (org-list-search-forward (org-item-beginning-re) eos t)
7089 (beginning-of-line 1)
7090 (let* ((struct (org-list-struct))
7091 (prevs (org-list-prevs-alist struct))
7092 (end (org-list-get-bottom-point struct)))
7093 (dolist (e (org-list-get-all-items (point) struct prevs))
7094 (org-list-set-item-visibility e struct 'folded))
7095 (goto-char (if (< end eos) end eos)))))))
7096 (org-unlogged-message "CHILDREN")
7097 (save-excursion
7098 (goto-char eos)
7099 (outline-next-heading)
7100 (when (org-invisible-p) (org-flag-heading nil)))
7101 (setq org-cycle-subtree-status 'children)
7102 (unless (org-before-first-heading-p)
7103 (run-hook-with-args 'org-cycle-hook 'children)))
7104 ((or children-skipped
7105 (and (eq last-command this-command)
7106 (eq org-cycle-subtree-status 'children)))
7107 ;; We just showed the children, or no children are there,
7108 ;; now show everything.
7109 (unless (org-before-first-heading-p)
7110 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7111 (org-flag-region eoh eos nil 'outline)
7112 (org-unlogged-message
7113 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7114 (setq org-cycle-subtree-status 'subtree)
7115 (unless (org-before-first-heading-p)
7116 (run-hook-with-args 'org-cycle-hook 'subtree)))
7118 ;; Default action: hide the subtree.
7119 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7120 (org-flag-region eoh eos t 'outline)
7121 (org-unlogged-message "FOLDED")
7122 (setq org-cycle-subtree-status 'folded)
7123 (unless (org-before-first-heading-p)
7124 (run-hook-with-args 'org-cycle-hook 'folded))))))
7126 ;;;###autoload
7127 (defun org-global-cycle (&optional arg)
7128 "Cycle the global visibility. For details see `org-cycle'.
7129 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7130 With a numeric prefix, show all headlines up to that level."
7131 (interactive "P")
7132 (let ((org-cycle-include-plain-lists
7133 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7134 (cond
7135 ((integerp arg)
7136 (org-show-all '(headings blocks))
7137 (outline-hide-sublevels arg)
7138 (setq org-cycle-global-status 'contents))
7139 ((equal arg '(4))
7140 (org-set-startup-visibility)
7141 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7143 (org-cycle '(4))))))
7145 (defun org-set-startup-visibility ()
7146 "Set the visibility required by startup options and properties."
7147 (cond
7148 ((eq org-startup-folded t)
7149 (org-overview))
7150 ((eq org-startup-folded 'content)
7151 (org-content))
7152 ((or (eq org-startup-folded 'showeverything)
7153 (eq org-startup-folded nil))
7154 (org-show-all)))
7155 (unless (eq org-startup-folded 'showeverything)
7156 (when org-hide-block-startup (org-hide-block-all))
7157 (org-set-visibility-according-to-property)
7158 (org-cycle-hide-archived-subtrees 'all)
7159 (org-cycle-hide-drawers 'all)
7160 (org-cycle-show-empty-lines t)))
7162 (defun org-set-visibility-according-to-property ()
7163 "Switch subtree visibilities according to :VISIBILITY: property."
7164 (interactive)
7165 (org-with-wide-buffer
7166 (goto-char (point-min))
7167 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7168 (if (not (org-at-property-p)) (outline-next-heading)
7169 (let ((state (match-string 3)))
7170 (save-excursion
7171 (org-back-to-heading t)
7172 (outline-hide-subtree)
7173 (org-reveal)
7174 (cond
7175 ((equal state "folded")
7176 (outline-hide-subtree))
7177 ((equal state "children")
7178 (org-show-hidden-entry)
7179 (org-show-children))
7180 ((equal state "content")
7181 (save-excursion
7182 (save-restriction
7183 (org-narrow-to-subtree)
7184 (org-content))))
7185 ((member state '("all" "showall"))
7186 (outline-show-subtree)))))))))
7188 (defun org-overview ()
7189 "Switch to overview mode, showing only top-level headlines.
7190 This shows all headlines with a level equal or greater than the level
7191 of the first headline in the buffer. This is important, because if the
7192 first headline is not level one, then (hide-sublevels 1) gives confusing
7193 results."
7194 (interactive)
7195 (save-excursion
7196 (let ((level
7197 (save-excursion
7198 (goto-char (point-min))
7199 (when (re-search-forward org-outline-regexp-bol nil t)
7200 (goto-char (match-beginning 0))
7201 (funcall outline-level)))))
7202 (and level (outline-hide-sublevels level)))))
7204 (defun org-content (&optional arg)
7205 "Show all headlines in the buffer, like a table of contents.
7206 With numerical argument N, show content up to level N."
7207 (interactive "P")
7208 (org-overview)
7209 (save-excursion
7210 ;; Visit all headings and show their offspring
7211 (and (integerp arg) (org-overview))
7212 (goto-char (point-max))
7213 (catch 'exit
7214 (while (and (progn (condition-case nil
7215 (outline-previous-visible-heading 1)
7216 (error (goto-char (point-min))))
7218 (looking-at org-outline-regexp))
7219 (if (integerp arg)
7220 (org-show-children (1- arg))
7221 (outline-show-branches))
7222 (when (bobp) (throw 'exit nil))))))
7224 (defun org-optimize-window-after-visibility-change (state)
7225 "Adjust the window after a change in outline visibility.
7226 This function is the default value of the hook `org-cycle-hook'."
7227 (when (get-buffer-window (current-buffer))
7228 (cond
7229 ((eq state 'content) nil)
7230 ((eq state 'all) nil)
7231 ((eq state 'folded) nil)
7232 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7233 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7235 (defun org-clean-visibility-after-subtree-move ()
7236 "Fix visibility issues after moving a subtree."
7237 ;; First, find a reasonable region to look at:
7238 ;; Start two siblings above, end three below
7239 (let* ((beg (save-excursion
7240 (and (org-get-last-sibling)
7241 (org-get-last-sibling))
7242 (point)))
7243 (end (save-excursion
7244 (and (org-get-next-sibling)
7245 (org-get-next-sibling)
7246 (org-get-next-sibling))
7247 (if (org-at-heading-p)
7248 (point-at-eol)
7249 (point))))
7250 (level (looking-at "\\*+"))
7251 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7252 (save-excursion
7253 (save-restriction
7254 (narrow-to-region beg end)
7255 (when re
7256 ;; Properly fold already folded siblings
7257 (goto-char (point-min))
7258 (while (re-search-forward re nil t)
7259 (when (and (not (org-invisible-p))
7260 (org-invisible-p (line-end-position)))
7261 (outline-hide-entry))))
7262 (org-cycle-hide-drawers 'all)
7263 (org-cycle-show-empty-lines 'overview)))))
7265 (defun org-cycle-show-empty-lines (state)
7266 "Show empty lines above all visible headlines.
7267 The region to be covered depends on STATE when called through
7268 `org-cycle-hook'. Lisp program can use t for STATE to get the
7269 entire buffer covered. Note that an empty line is only shown if there
7270 are at least `org-cycle-separator-lines' empty lines before the headline."
7271 (when (/= org-cycle-separator-lines 0)
7272 (save-excursion
7273 (let* ((n (abs org-cycle-separator-lines))
7274 (re (cond
7275 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7276 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7277 (t (let ((ns (number-to-string (- n 2))))
7278 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7279 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7280 beg end)
7281 (cond
7282 ((memq state '(overview contents t))
7283 (setq beg (point-min) end (point-max)))
7284 ((memq state '(children folded))
7285 (setq beg (point)
7286 end (progn (org-end-of-subtree t t)
7287 (line-beginning-position 2)))))
7288 (when beg
7289 (goto-char beg)
7290 (while (re-search-forward re end t)
7291 (unless (get-char-property (match-end 1) 'invisible)
7292 (let ((e (match-end 1))
7293 (b (if (>= org-cycle-separator-lines 0)
7294 (match-beginning 1)
7295 (save-excursion
7296 (goto-char (match-beginning 0))
7297 (skip-chars-backward " \t\n")
7298 (line-end-position)))))
7299 (org-flag-region b e nil 'outline))))))))
7300 ;; Never hide empty lines at the end of the file.
7301 (save-excursion
7302 (goto-char (point-max))
7303 (outline-previous-heading)
7304 (outline-end-of-heading)
7305 (when (and (looking-at "[ \t\n]+")
7306 (= (match-end 0) (point-max)))
7307 (org-flag-region (point) (match-end 0) nil 'outline))))
7309 ;;;; Reveal point location
7311 (defun org-show-context (&optional key)
7312 "Make sure point and context are visible.
7313 Optional argument KEY, when non-nil, is a symbol. See
7314 `org-show-context-detail' for allowed values and how much is to
7315 be shown."
7316 (org-show-set-visibility
7317 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7318 ((cdr (assq key org-show-context-detail)))
7319 (t (cdr (assq 'default org-show-context-detail))))))
7321 (defun org-show-set-visibility (detail)
7322 "Set visibility around point according to DETAIL.
7323 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7324 `tree', `canonical' or t. See `org-show-context-detail' for more
7325 information."
7326 ;; Show current heading and possibly its entry, following headline
7327 ;; or all children.
7328 (if (and (org-at-heading-p) (not (eq detail 'local)))
7329 (org-flag-heading nil)
7330 (org-show-entry)
7331 ;; If point is hidden within a drawer or a block, make sure to
7332 ;; expose it.
7333 (dolist (o (overlays-at (point)))
7334 (when (memq (overlay-get o 'invisible)
7335 '(org-hide-block org-hide-drawer outline))
7336 (delete-overlay o)))
7337 (unless (org-before-first-heading-p)
7338 (org-with-limited-levels
7339 (cl-case detail
7340 ((tree canonical t) (org-show-children))
7341 ((nil minimal ancestors))
7342 (t (save-excursion
7343 (outline-next-heading)
7344 (org-flag-heading nil)))))))
7345 ;; Show all siblings.
7346 (when (eq detail 'lineage) (org-show-siblings))
7347 ;; Show ancestors, possibly with their children.
7348 (when (memq detail '(ancestors lineage tree canonical t))
7349 (save-excursion
7350 (while (org-up-heading-safe)
7351 (org-flag-heading nil)
7352 (when (memq detail '(canonical t)) (org-show-entry))
7353 (when (memq detail '(tree canonical t)) (org-show-children))))))
7355 (defvar org-reveal-start-hook nil
7356 "Hook run before revealing a location.")
7358 (defun org-reveal (&optional siblings)
7359 "Show current entry, hierarchy above it, and the following headline.
7361 This can be used to show a consistent set of context around
7362 locations exposed with `org-show-context'.
7364 With optional argument SIBLINGS, on each level of the hierarchy all
7365 siblings are shown. This repairs the tree structure to what it would
7366 look like when opened with hierarchical calls to `org-cycle'.
7368 With a \\[universal-argument] \\[universal-argument] prefix, \
7369 go to the parent and show the entire tree."
7370 (interactive "P")
7371 (run-hooks 'org-reveal-start-hook)
7372 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7373 ((equal siblings '(16))
7374 (save-excursion
7375 (when (org-up-heading-safe)
7376 (org-show-subtree)
7377 (run-hook-with-args 'org-cycle-hook 'subtree))))
7378 (t (org-show-set-visibility 'lineage))))
7381 ;;; Indirect buffer display of subtrees
7383 (defvar org-indirect-dedicated-frame nil
7384 "This is the frame being used for indirect tree display.")
7385 (defvar org-last-indirect-buffer nil)
7387 (defun org-tree-to-indirect-buffer (&optional arg)
7388 "Create indirect buffer and narrow it to current subtree.
7390 With a numerical prefix ARG, go up to this level and then take that tree.
7391 If ARG is negative, go up that many levels.
7393 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7394 indirect buffer previously made with this command, to avoid proliferation of
7395 indirect buffers. However, when you call the command with a \
7396 `\\[universal-argument]' prefix, or
7397 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7398 so that you can work with several indirect buffers at the same time. If
7399 `org-indirect-buffer-display' is `dedicated-frame', the \
7400 `\\[universal-argument]' prefix also
7401 requests that a new frame be made for the new buffer, so that the dedicated
7402 frame is not changed."
7403 (interactive "P")
7404 (let ((cbuf (current-buffer))
7405 (cwin (selected-window))
7406 (pos (point))
7407 beg end level heading ibuf)
7408 (save-excursion
7409 (org-back-to-heading t)
7410 (when (numberp arg)
7411 (setq level (org-outline-level))
7412 (when (< arg 0) (setq arg (+ level arg)))
7413 (while (> (setq level (org-outline-level)) arg)
7414 (org-up-heading-safe)))
7415 (setq beg (point)
7416 heading (org-get-heading 'no-tags))
7417 (org-end-of-subtree t t)
7418 (when (org-at-heading-p) (backward-char 1))
7419 (setq end (point)))
7420 (when (and (buffer-live-p org-last-indirect-buffer)
7421 (not (eq org-indirect-buffer-display 'new-frame))
7422 (not arg))
7423 (kill-buffer org-last-indirect-buffer))
7424 (setq ibuf (org-get-indirect-buffer cbuf heading)
7425 org-last-indirect-buffer ibuf)
7426 (cond
7427 ((or (eq org-indirect-buffer-display 'new-frame)
7428 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7429 (select-frame (make-frame))
7430 (delete-other-windows)
7431 (pop-to-buffer-same-window ibuf)
7432 (org-set-frame-title heading))
7433 ((eq org-indirect-buffer-display 'dedicated-frame)
7434 (raise-frame
7435 (select-frame (or (and org-indirect-dedicated-frame
7436 (frame-live-p org-indirect-dedicated-frame)
7437 org-indirect-dedicated-frame)
7438 (setq org-indirect-dedicated-frame (make-frame)))))
7439 (delete-other-windows)
7440 (pop-to-buffer-same-window ibuf)
7441 (org-set-frame-title (concat "Indirect: " heading)))
7442 ((eq org-indirect-buffer-display 'current-window)
7443 (pop-to-buffer-same-window ibuf))
7444 ((eq org-indirect-buffer-display 'other-window)
7445 (pop-to-buffer ibuf))
7446 (t (error "Invalid value")))
7447 (narrow-to-region beg end)
7448 (org-show-all '(headings blocks))
7449 (goto-char pos)
7450 (run-hook-with-args 'org-cycle-hook 'all)
7451 (and (window-live-p cwin) (select-window cwin))))
7453 (defun org-get-indirect-buffer (&optional buffer heading)
7454 (setq buffer (or buffer (current-buffer)))
7455 (let ((n 1) (base (buffer-name buffer)) bname)
7456 (while (buffer-live-p
7457 (get-buffer
7458 (setq bname
7459 (concat base "-"
7460 (if heading (concat heading "-" (number-to-string n))
7461 (number-to-string n))))))
7462 (setq n (1+ n)))
7463 (condition-case nil
7464 (make-indirect-buffer buffer bname 'clone)
7465 (error (make-indirect-buffer buffer bname)))))
7467 (defun org-set-frame-title (title)
7468 "Set the title of the current frame to the string TITLE."
7469 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7471 ;;;; Structure editing
7473 ;;; Inserting headlines
7475 (defun org--line-empty-p (n)
7476 "Is the Nth next line empty?
7478 Counts the current line as N = 1 and the previous line as N = 0;
7479 see `beginning-of-line'."
7480 (save-excursion
7481 (and (not (bobp))
7482 (or (beginning-of-line n) t)
7483 (save-match-data
7484 (looking-at "[ \t]*$")))))
7486 (defun org-previous-line-empty-p ()
7487 "Is the previous line a blank line?
7488 When NEXT is non-nil, check the next line instead."
7489 (org--line-empty-p 0))
7491 (defun org-next-line-empty-p ()
7492 "Is the previous line a blank line?
7493 When NEXT is non-nil, check the next line instead."
7494 (org--line-empty-p 2))
7496 (defun org--blank-before-heading-p (&optional parent)
7497 "Non-nil when an empty line should precede a new heading here.
7498 When optional argument PARENT is non-nil, consider parent
7499 headline instead of current one."
7500 (pcase (assq 'heading org-blank-before-new-entry)
7501 (`(heading . auto)
7502 (save-excursion
7503 (org-with-limited-levels
7504 (unless (and (org-before-first-heading-p)
7505 (not (outline-next-heading)))
7506 (org-back-to-heading t)
7507 (when parent (org-up-heading-safe))
7508 (cond ((not (bobp))
7509 (org-previous-line-empty-p))
7510 ((outline-next-heading)
7511 (org-previous-line-empty-p))
7512 ;; Ignore trailing spaces on last buffer line.
7513 ((progn (skip-chars-backward " \t") (bolp))
7514 (org-previous-line-empty-p))
7515 (t nil))))))
7516 (`(heading . ,value) value)
7517 (_ nil)))
7519 (defun org-insert-heading (&optional arg invisible-ok top)
7520 "Insert a new heading or an item with the same depth at point.
7522 If point is at the beginning of a heading, insert a new heading
7523 or a new headline above the current one. When at the beginning
7524 of a regular line of text, turn it into a heading.
7526 If point is in the middle of a line, split it and create a new
7527 headline with the text in the current line after point (see
7528 `org-M-RET-may-split-line' on how to modify this behavior). As
7529 a special case, on a headline, splitting can only happen on the
7530 title itself. E.g., this excludes breaking stars or tags.
7532 With a `\\[universal-argument]' prefix, set \
7533 `org-insert-heading-respect-content' to
7534 a non-nil value for the duration of the command. This forces the
7535 insertion of a heading after the current subtree, independently
7536 on the location of point.
7538 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7539 insert the heading at the end of the tree
7540 above the current heading. For example, if point is within a
7541 2nd-level heading, then it will insert a 2nd-level heading at
7542 the end of the 1st-level parent subtree.
7544 When INVISIBLE-OK is set, stop at invisible headlines when going
7545 back. This is important for non-interactive uses of the
7546 command.
7548 When optional argument TOP is non-nil, insert a level 1 heading,
7549 unconditionally."
7550 (interactive "P")
7551 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7552 (level (org-current-level))
7553 (stars (make-string (if (and level (not top)) level 1) ?*)))
7554 (cond
7555 ((or org-insert-heading-respect-content
7556 (member arg '((4) (16)))
7557 (and (not invisible-ok)
7558 (invisible-p (max (1- (point)) (point-min)))))
7559 ;; Position point at the location of insertion.
7560 (if (not level) ;before first headline
7561 (org-with-limited-levels (outline-next-heading))
7562 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7563 ;; is nil.
7564 (org-with-limited-levels (org-back-to-heading invisible-ok))
7565 (cond ((equal arg '(16))
7566 (org-up-heading-safe)
7567 (org-end-of-subtree t t))
7569 (org-end-of-subtree t t))))
7570 (unless (bolp) (insert "\n")) ;ensure final newline
7571 (unless (and blank? (org-previous-line-empty-p))
7572 (org-N-empty-lines-before-current (if blank? 1 0)))
7573 (insert stars " \n")
7574 (forward-char -1))
7575 ;; At a headline...
7576 ((org-at-heading-p)
7577 (cond ((bolp)
7578 (when blank? (save-excursion (insert "\n")))
7579 (save-excursion (insert stars " \n"))
7580 (unless (and blank? (org-previous-line-empty-p))
7581 (org-N-empty-lines-before-current (if blank? 1 0)))
7582 (end-of-line))
7583 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7584 (org-match-line org-complex-heading-regexp)
7585 (org-pos-in-match-range (point) 4))
7586 ;; Grab the text that should moved to the new headline.
7587 ;; Preserve tags.
7588 (let ((split (delete-and-extract-region (point) (match-end 4))))
7589 (if (looking-at "[ \t]*$") (replace-match "")
7590 (org-set-tags nil t))
7591 (end-of-line)
7592 (when blank? (insert "\n"))
7593 (insert "\n" stars " ")
7594 (when (org-string-nw-p split) (insert split))
7595 (when (eobp) (save-excursion (insert "\n")))))
7597 (end-of-line)
7598 (when blank? (insert "\n"))
7599 (insert "\n" stars " ")
7600 (when (eobp) (save-excursion (insert "\n"))))))
7601 ;; On regular text, turn line into a headline or split, if
7602 ;; appropriate.
7603 ((bolp)
7604 (insert stars " ")
7605 (unless (and blank? (org-previous-line-empty-p))
7606 (org-N-empty-lines-before-current (if blank? 1 0))))
7608 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7609 (end-of-line))
7610 (insert "\n" stars " ")
7611 (unless (and blank? (org-previous-line-empty-p))
7612 (org-N-empty-lines-before-current (if blank? 1 0))))))
7613 (run-hooks 'org-insert-heading-hook))
7615 (defun org-N-empty-lines-before-current (n)
7616 "Make the number of empty lines before current exactly N.
7617 So this will delete or add empty lines."
7618 (let ((column (current-column)))
7619 (beginning-of-line)
7620 (unless (bobp)
7621 (let ((start (save-excursion
7622 (skip-chars-backward " \r\t\n")
7623 (line-end-position))))
7624 (delete-region start (line-end-position 0))))
7625 (insert (make-string n ?\n))
7626 (move-to-column column)))
7628 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7629 "Return the heading of the current entry, without the stars.
7630 When NO-TAGS is non-nil, don't include tags.
7631 When NO-TODO is non-nil, don't include TODO keywords.
7632 When NO-PRIORITY is non-nil, don't include priority cookie.
7633 When NO-COMMENT is non-nil, don't include COMMENT string."
7634 (save-excursion
7635 (org-back-to-heading t)
7636 (let ((case-fold-search nil))
7637 (looking-at org-complex-heading-regexp)
7638 (let ((todo (and (not no-todo) (match-string 2)))
7639 (priority (and (not no-priority) (match-string 3)))
7640 (headline (pcase (match-string 4)
7641 (`nil "")
7642 ((and (guard no-comment) h)
7643 (replace-regexp-in-string
7644 (eval-when-compile
7645 (format "\\`%s[ \t]+" org-comment-string))
7646 "" h))
7647 (h h)))
7648 (tags (and (not no-tags) (match-string 5))))
7649 (mapconcat #'identity
7650 (delq nil (list todo priority headline tags))
7651 " ")))))
7653 (defun org-heading-components ()
7654 "Return the components of the current heading.
7655 This is a list with the following elements:
7656 - the level as an integer
7657 - the reduced level, different if `org-odd-levels-only' is set.
7658 - the TODO keyword, or nil
7659 - the priority character, like ?A, or nil if no priority is given
7660 - the headline text itself, or the tags string if no headline text
7661 - the tags string, or nil."
7662 (save-excursion
7663 (org-back-to-heading t)
7664 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7665 (list (length (match-string 1))
7666 (org-reduced-level (length (match-string 1)))
7667 (match-string-no-properties 2)
7668 (and (match-end 3) (aref (match-string 3) 2))
7669 (match-string-no-properties 4)
7670 (match-string-no-properties 5)))))
7672 (defun org-get-entry ()
7673 "Get the entry text, after heading, entire subtree."
7674 (save-excursion
7675 (org-back-to-heading t)
7676 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7678 (defun org-edit-headline (&optional heading)
7679 "Edit the current headline.
7680 Set it to HEADING when provided."
7681 (interactive)
7682 (org-with-wide-buffer
7683 (org-back-to-heading t)
7684 (let ((case-fold-search nil))
7685 (when (looking-at org-complex-heading-regexp)
7686 (let* ((old (match-string-no-properties 4))
7687 (new (save-match-data
7688 (org-trim (or heading (read-string "Edit: " old))))))
7689 (unless (equal old new)
7690 (if old (replace-match new t t nil 4)
7691 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7692 (insert " " new))
7693 (org-set-tags nil t)
7694 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7696 (defun org-insert-heading-after-current ()
7697 "Insert a new heading with same level as current, after current subtree."
7698 (interactive)
7699 (org-back-to-heading)
7700 (org-insert-heading)
7701 (org-move-subtree-down)
7702 (end-of-line 1))
7704 (defun org-insert-heading-respect-content (&optional invisible-ok)
7705 "Insert heading with `org-insert-heading-respect-content' set to t."
7706 (interactive)
7707 (org-insert-heading '(4) invisible-ok))
7709 (defun org-insert-todo-heading-respect-content (&optional force-state)
7710 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7711 (interactive)
7712 (org-insert-todo-heading force-state '(4)))
7714 (defun org-insert-todo-heading (arg &optional force-heading)
7715 "Insert a new heading with the same level and TODO state as current heading.
7717 If the heading has no TODO state, or if the state is DONE, use
7718 the first state (TODO by default). Also with one prefix arg,
7719 force first state. With two prefix args, force inserting at the
7720 end of the parent subtree.
7722 When called at a plain list item, insert a new item with an
7723 unchecked check box."
7724 (interactive "P")
7725 (when (or force-heading (not (org-insert-item 'checkbox)))
7726 (org-insert-heading (or (and (equal arg '(16)) '(16))
7727 force-heading))
7728 (save-excursion
7729 (org-forward-heading-same-level -1)
7730 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7731 (let* ((new-mark-x
7732 (if (or (equal arg '(4))
7733 (not (match-beginning 2))
7734 (member (match-string 2) org-done-keywords))
7735 (car org-todo-keywords-1)
7736 (match-string 2)))
7737 (new-mark
7739 (run-hook-with-args-until-success
7740 'org-todo-get-default-hook new-mark-x nil)
7741 new-mark-x)))
7742 (beginning-of-line 1)
7743 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7744 (if org-treat-insert-todo-heading-as-state-change
7745 (org-todo new-mark)
7746 (insert new-mark " "))))
7747 (when org-provide-todo-statistics
7748 (org-update-parent-todo-statistics))))
7750 (defun org-insert-subheading (arg)
7751 "Insert a new subheading and demote it.
7752 Works for outline headings and for plain lists alike."
7753 (interactive "P")
7754 (org-insert-heading arg)
7755 (cond
7756 ((org-at-heading-p) (org-do-demote))
7757 ((org-at-item-p) (org-indent-item))))
7759 (defun org-insert-todo-subheading (arg)
7760 "Insert a new subheading with TODO keyword or checkbox and demote it.
7761 Works for outline headings and for plain lists alike."
7762 (interactive "P")
7763 (org-insert-todo-heading arg)
7764 (cond
7765 ((org-at-heading-p) (org-do-demote))
7766 ((org-at-item-p) (org-indent-item))))
7768 ;;; Promotion and Demotion
7770 (defvar org-after-demote-entry-hook nil
7771 "Hook run after an entry has been demoted.
7772 The cursor will be at the beginning of the entry.
7773 When a subtree is being demoted, the hook will be called for each node.")
7775 (defvar org-after-promote-entry-hook nil
7776 "Hook run after an entry has been promoted.
7777 The cursor will be at the beginning of the entry.
7778 When a subtree is being promoted, the hook will be called for each node.")
7780 (defun org-promote-subtree ()
7781 "Promote the entire subtree.
7782 See also `org-promote'."
7783 (interactive)
7784 (save-excursion
7785 (org-with-limited-levels (org-map-tree 'org-promote)))
7786 (org-fix-position-after-promote))
7788 (defun org-demote-subtree ()
7789 "Demote the entire subtree.
7790 See `org-demote' and `org-promote'."
7791 (interactive)
7792 (save-excursion
7793 (org-with-limited-levels (org-map-tree 'org-demote)))
7794 (org-fix-position-after-promote))
7796 (defun org-do-promote ()
7797 "Promote the current heading higher up the tree.
7798 If the region is active in `transient-mark-mode', promote all
7799 headings in the region."
7800 (interactive)
7801 (save-excursion
7802 (if (org-region-active-p)
7803 (org-map-region 'org-promote (region-beginning) (region-end))
7804 (org-promote)))
7805 (org-fix-position-after-promote))
7807 (defun org-do-demote ()
7808 "Demote the current heading lower down the tree.
7809 If the region is active in `transient-mark-mode', demote all
7810 headings in the region."
7811 (interactive)
7812 (save-excursion
7813 (if (org-region-active-p)
7814 (org-map-region 'org-demote (region-beginning) (region-end))
7815 (org-demote)))
7816 (org-fix-position-after-promote))
7818 (defun org-fix-position-after-promote ()
7819 "Fix cursor position and indentation after demoting/promoting."
7820 (let ((pos (point)))
7821 (when (save-excursion
7822 (beginning-of-line)
7823 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7824 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7825 (cond ((eobp) (insert " "))
7826 ((eolp) (insert " "))
7827 ((equal (char-after) ?\s) (forward-char 1))))))
7829 (defun org-current-level ()
7830 "Return the level of the current entry, or nil if before the first headline.
7831 The level is the number of stars at the beginning of the
7832 headline. Use `org-reduced-level' to remove the effect of
7833 `org-odd-levels'. Unlike to `org-outline-level', this function
7834 ignores inlinetasks."
7835 (let ((level (org-with-limited-levels (org-outline-level))))
7836 (and (> level 0) level)))
7838 (defun org-get-previous-line-level ()
7839 "Return the outline depth of the last headline before the current line.
7840 Returns 0 for the first headline in the buffer, and nil if before the
7841 first headline."
7842 (and (org-current-level)
7843 (or (and (/= (line-beginning-position) (point-min))
7844 (save-excursion (beginning-of-line 0) (org-current-level)))
7845 0)))
7847 (defun org-reduced-level (l)
7848 "Compute the effective level of a heading.
7849 This takes into account the setting of `org-odd-levels-only'."
7850 (cond
7851 ((zerop l) 0)
7852 (org-odd-levels-only (1+ (floor (/ l 2))))
7853 (t l)))
7855 (defun org-level-increment ()
7856 "Return the number of stars that will be added or removed at a
7857 time to headlines when structure editing, based on the value of
7858 `org-odd-levels-only'."
7859 (if org-odd-levels-only 2 1))
7861 (defun org-get-valid-level (level &optional change)
7862 "Rectify a level change under the influence of `org-odd-levels-only'.
7863 LEVEL is a current level, CHANGE is by how much the level should
7864 be modified. Even if CHANGE is nil, LEVEL may be returned
7865 modified because even level numbers will become the next higher
7866 odd number. Returns values greater than 0."
7867 (if org-odd-levels-only
7868 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7869 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7870 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7871 (max 1 (+ level (or change 0)))))
7873 (defun org-promote ()
7874 "Promote the current heading higher up the tree."
7875 (org-with-wide-buffer
7876 (org-back-to-heading t)
7877 (let* ((after-change-functions (remq 'flyspell-after-change-function
7878 after-change-functions))
7879 (level (save-match-data (funcall outline-level)))
7880 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7881 (diff (abs (- level (length up-head) -1))))
7882 (cond
7883 ((and (= level 1) org-allow-promoting-top-level-subtree)
7884 (replace-match "# " nil t))
7885 ((= level 1)
7886 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7887 (t (replace-match up-head nil t)))
7888 (unless (= level 1)
7889 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7890 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7891 (run-hooks 'org-after-promote-entry-hook))))
7893 (defun org-demote ()
7894 "Demote the current heading lower down the tree."
7895 (org-with-wide-buffer
7896 (org-back-to-heading t)
7897 (let* ((after-change-functions (remq 'flyspell-after-change-function
7898 after-change-functions))
7899 (level (save-match-data (funcall outline-level)))
7900 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7901 (diff (abs (- level (length down-head) -1))))
7902 (replace-match down-head nil t)
7903 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7904 (when org-adapt-indentation (org-fixup-indentation diff))
7905 (run-hooks 'org-after-demote-entry-hook))))
7907 (defun org-cycle-level ()
7908 "Cycle the level of an empty headline through possible states.
7909 This goes first to child, then to parent, level, then up the hierarchy.
7910 After top level, it switches back to sibling level."
7911 (interactive)
7912 (let ((org-adapt-indentation nil))
7913 (when (org-point-at-end-of-empty-headline)
7914 (setq this-command 'org-cycle-level) ; Only needed for caching
7915 (let ((cur-level (org-current-level))
7916 (prev-level (org-get-previous-line-level)))
7917 (cond
7918 ;; If first headline in file, promote to top-level.
7919 ((= prev-level 0)
7920 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7921 do (org-do-promote)))
7922 ;; If same level as prev, demote one.
7923 ((= prev-level cur-level)
7924 (org-do-demote))
7925 ;; If parent is top-level, promote to top level if not already.
7926 ((= prev-level 1)
7927 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7928 do (org-do-promote)))
7929 ;; If top-level, return to prev-level.
7930 ((= cur-level 1)
7931 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7932 do (org-do-demote)))
7933 ;; If less than prev-level, promote one.
7934 ((< cur-level prev-level)
7935 (org-do-promote))
7936 ;; If deeper than prev-level, promote until higher than
7937 ;; prev-level.
7938 ((> cur-level prev-level)
7939 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7940 do (org-do-promote))))
7941 t))))
7943 (defun org-map-tree (fun)
7944 "Call FUN for every heading underneath the current one."
7945 (org-back-to-heading t)
7946 (let ((level (funcall outline-level)))
7947 (save-excursion
7948 (funcall fun)
7949 (while (and (progn
7950 (outline-next-heading)
7951 (> (funcall outline-level) level))
7952 (not (eobp)))
7953 (funcall fun)))))
7955 (defun org-map-region (fun beg end)
7956 "Call FUN for every heading between BEG and END."
7957 (let ((org-ignore-region t))
7958 (save-excursion
7959 (setq end (copy-marker end))
7960 (goto-char beg)
7961 (when (and (re-search-forward org-outline-regexp-bol nil t)
7962 (< (point) end))
7963 (funcall fun))
7964 (while (and (progn
7965 (outline-next-heading)
7966 (< (point) end))
7967 (not (eobp)))
7968 (funcall fun)))))
7970 (defun org-fixup-indentation (diff)
7971 "Change the indentation in the current entry by DIFF.
7973 DIFF is an integer. Indentation is done according to the
7974 following rules:
7976 - Planning information and property drawers are always indented
7977 according to the new level of the headline;
7979 - Footnote definitions and their contents are ignored;
7981 - Inlinetasks' boundaries are not shifted;
7983 - Empty lines are ignored;
7985 - Other lines' indentation are shifted by DIFF columns, unless
7986 it would introduce a structural change in the document, in
7987 which case no shifting is done at all.
7989 Assume point is at a heading or an inlinetask beginning."
7990 (org-with-wide-buffer
7991 (narrow-to-region (line-beginning-position)
7992 (save-excursion
7993 (if (org-with-limited-levels (org-at-heading-p))
7994 (org-with-limited-levels (outline-next-heading))
7995 (org-inlinetask-goto-end))
7996 (point)))
7997 (forward-line)
7998 ;; Indent properly planning info and property drawer.
7999 (when (looking-at-p org-planning-line-re)
8000 (org-indent-line)
8001 (forward-line))
8002 (when (looking-at org-property-drawer-re)
8003 (goto-char (match-end 0))
8004 (forward-line)
8005 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8006 (catch 'no-shift
8007 (when (zerop diff) (throw 'no-shift nil))
8008 ;; If DIFF is negative, first check if a shift is possible at all
8009 ;; (e.g., it doesn't break structure). This can only happen if
8010 ;; some contents are not properly indented.
8011 (let ((case-fold-search t))
8012 (when (< diff 0)
8013 (let ((diff (- diff))
8014 (forbidden-re (concat org-outline-regexp
8015 "\\|"
8016 (substring org-footnote-definition-re 1))))
8017 (save-excursion
8018 (while (not (eobp))
8019 (cond
8020 ((looking-at-p "[ \t]*$") (forward-line))
8021 ((and (looking-at-p org-footnote-definition-re)
8022 (let ((e (org-element-at-point)))
8023 (and (eq (org-element-type e) 'footnote-definition)
8024 (goto-char (org-element-property :end e))))))
8025 ((looking-at-p org-outline-regexp) (forward-line))
8026 ;; Give up if shifting would move before column 0 or
8027 ;; if it would introduce a headline or a footnote
8028 ;; definition.
8030 (skip-chars-forward " \t")
8031 (let ((ind (current-column)))
8032 (when (or (< ind diff)
8033 (and (= ind diff) (looking-at-p forbidden-re)))
8034 (throw 'no-shift nil)))
8035 ;; Ignore contents of example blocks and source
8036 ;; blocks if their indentation is meant to be
8037 ;; preserved. Jump to block's closing line.
8038 (beginning-of-line)
8039 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8040 (let ((e (org-element-at-point)))
8041 (and (memq (org-element-type e)
8042 '(example-block src-block))
8043 (or org-src-preserve-indentation
8044 (org-element-property :preserve-indent e))
8045 (goto-char (org-element-property :end e))
8046 (progn (skip-chars-backward " \r\t\n")
8047 (beginning-of-line)
8048 t))))
8049 (forward-line))))))))
8050 ;; Shift lines but footnote definitions, inlinetasks boundaries
8051 ;; by DIFF. Also skip contents of source or example blocks
8052 ;; when indentation is meant to be preserved.
8053 (while (not (eobp))
8054 (cond
8055 ((and (looking-at-p org-footnote-definition-re)
8056 (let ((e (org-element-at-point)))
8057 (and (eq (org-element-type e) 'footnote-definition)
8058 (goto-char (org-element-property :end e))))))
8059 ((looking-at-p org-outline-regexp) (forward-line))
8060 ((looking-at-p "[ \t]*$") (forward-line))
8062 (indent-line-to (+ (org-get-indentation) diff))
8063 (beginning-of-line)
8064 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8065 (let ((e (org-element-at-point)))
8066 (and (memq (org-element-type e)
8067 '(example-block src-block))
8068 (or org-src-preserve-indentation
8069 (org-element-property :preserve-indent e))
8070 (goto-char (org-element-property :end e))
8071 (progn (skip-chars-backward " \r\t\n")
8072 (beginning-of-line)
8073 t))))
8074 (forward-line)))))))))
8076 (defun org-convert-to-odd-levels ()
8077 "Convert an Org file with all levels allowed to one with odd levels.
8078 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8079 level 5 etc."
8080 (interactive)
8081 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8082 (let ((outline-level 'org-outline-level)
8083 (org-odd-levels-only nil) n)
8084 (save-excursion
8085 (goto-char (point-min))
8086 (while (re-search-forward "^\\*\\*+ " nil t)
8087 (setq n (- (length (match-string 0)) 2))
8088 (while (>= (setq n (1- n)) 0)
8089 (org-demote))
8090 (end-of-line 1))))))
8092 (defun org-convert-to-oddeven-levels ()
8093 "Convert an Org file with only odd levels to one with odd/even levels.
8094 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8095 file contains a section with an even level, conversion would
8096 destroy the structure of the file. An error is signaled in this
8097 case."
8098 (interactive)
8099 (goto-char (point-min))
8100 ;; First check if there are no even levels
8101 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8102 (org-show-set-visibility 'canonical)
8103 (error "Not all levels are odd in this file. Conversion not possible"))
8104 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8105 (let ((outline-regexp org-outline-regexp)
8106 (outline-level 'org-outline-level)
8107 (org-odd-levels-only nil) n)
8108 (save-excursion
8109 (goto-char (point-min))
8110 (while (re-search-forward "^\\*\\*+ " nil t)
8111 (setq n (/ (1- (length (match-string 0))) 2))
8112 (while (>= (setq n (1- n)) 0)
8113 (org-promote))
8114 (end-of-line 1))))))
8116 (defun org-tr-level (n)
8117 "Make N odd if required."
8118 (if org-odd-levels-only (1+ (/ n 2)) n))
8120 ;;; Vertical tree motion, cutting and pasting of subtrees
8122 (defun org-move-subtree-up (&optional arg)
8123 "Move the current subtree up past ARG headlines of the same level."
8124 (interactive "p")
8125 (org-move-subtree-down (- (prefix-numeric-value arg))))
8127 (defun org-move-subtree-down (&optional arg)
8128 "Move the current subtree down past ARG headlines of the same level."
8129 (interactive "p")
8130 (setq arg (prefix-numeric-value arg))
8131 (org-preserve-local-variables
8132 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8133 'org-get-last-sibling))
8134 (ins-point (make-marker))
8135 (cnt (abs arg))
8136 (col (current-column))
8137 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8138 ;; Select the tree
8139 (org-back-to-heading)
8140 (setq beg0 (point))
8141 (save-excursion
8142 (setq ne-beg (org-back-over-empty-lines))
8143 (setq beg (point)))
8144 (save-match-data
8145 (save-excursion (outline-end-of-heading)
8146 (setq folded (org-invisible-p)))
8147 (progn (org-end-of-subtree nil t)
8148 (unless (eobp) (backward-char))))
8149 (outline-next-heading)
8150 (setq ne-end (org-back-over-empty-lines))
8151 (setq end (point))
8152 (goto-char beg0)
8153 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8154 ;; include less whitespace
8155 (save-excursion
8156 (goto-char beg)
8157 (forward-line (- ne-beg ne-end))
8158 (setq beg (point))))
8159 ;; Find insertion point, with error handling
8160 (while (> cnt 0)
8161 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8162 (goto-char beg0)
8163 (user-error "Cannot move past superior level or buffer limit"))
8164 (setq cnt (1- cnt)))
8165 (when (> arg 0)
8166 ;; Moving forward - still need to move over subtree
8167 (org-end-of-subtree t t)
8168 (save-excursion
8169 (org-back-over-empty-lines)
8170 (or (bolp) (newline))))
8171 (setq ne-ins (org-back-over-empty-lines))
8172 (move-marker ins-point (point))
8173 (setq txt (buffer-substring beg end))
8174 (org-save-markers-in-region beg end)
8175 (delete-region beg end)
8176 (org-remove-empty-overlays-at beg)
8177 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8178 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8179 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8180 (let ((bbb (point)))
8181 (insert-before-markers txt)
8182 (org-reinstall-markers-in-region bbb)
8183 (move-marker ins-point bbb))
8184 (or (bolp) (insert "\n"))
8185 (setq ins-end (point))
8186 (goto-char ins-point)
8187 (org-skip-whitespace)
8188 (when (and (< arg 0)
8189 (org-first-sibling-p)
8190 (> ne-ins ne-beg))
8191 ;; Move whitespace back to beginning
8192 (save-excursion
8193 (goto-char ins-end)
8194 (let ((kill-whole-line t))
8195 (kill-line (- ne-ins ne-beg)) (point)))
8196 (insert (make-string (- ne-ins ne-beg) ?\n)))
8197 (move-marker ins-point nil)
8198 (if folded
8199 (outline-hide-subtree)
8200 (org-show-entry)
8201 (org-show-children))
8202 (org-clean-visibility-after-subtree-move)
8203 ;; move back to the initial column we were at
8204 (move-to-column col))))
8206 (defvar org-subtree-clip ""
8207 "Clipboard for cut and paste of subtrees.
8208 This is actually only a copy of the kill, because we use the normal kill
8209 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8211 (defvar org-subtree-clip-folded nil
8212 "Was the last copied subtree folded?
8213 This is used to fold the tree back after pasting.")
8215 (defun org-cut-subtree (&optional n)
8216 "Cut the current subtree into the clipboard.
8217 With prefix arg N, cut this many sequential subtrees.
8218 This is a short-hand for marking the subtree and then cutting it."
8219 (interactive "p")
8220 (org-copy-subtree n 'cut))
8222 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8223 "Copy the current subtree into the clipboard.
8224 With prefix arg N, copy this many sequential subtrees.
8225 This is a short-hand for marking the subtree and then copying it.
8226 If CUT is non-nil, actually cut the subtree.
8227 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8228 of some markers in the region, even if CUT is non-nil. This is
8229 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8230 (interactive "p")
8231 (org-preserve-local-variables
8232 (let (beg end folded (beg0 (point)))
8233 (if (called-interactively-p 'any)
8234 (org-back-to-heading nil) ; take what looks like a subtree
8235 (org-back-to-heading t)) ; take what is really there
8236 (setq beg (point))
8237 (skip-chars-forward " \t\r\n")
8238 (save-match-data
8239 (if nosubtrees
8240 (outline-next-heading)
8241 (save-excursion (outline-end-of-heading)
8242 (setq folded (org-invisible-p)))
8243 (ignore-errors (org-forward-heading-same-level (1- n) t))
8244 (org-end-of-subtree t t)))
8245 ;; Include the end of an inlinetask
8246 (when (and (featurep 'org-inlinetask)
8247 (looking-at-p (concat (org-inlinetask-outline-regexp)
8248 "END[ \t]*$")))
8249 (end-of-line))
8250 (setq end (point))
8251 (goto-char beg0)
8252 (when (> end beg)
8253 (setq org-subtree-clip-folded folded)
8254 (when (or cut force-store-markers)
8255 (org-save-markers-in-region beg end))
8256 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8257 (setq org-subtree-clip (current-kill 0))
8258 (message "%s: Subtree(s) with %d characters"
8259 (if cut "Cut" "Copied")
8260 (length org-subtree-clip))))))
8262 (defun org-paste-subtree (&optional level tree for-yank remove)
8263 "Paste the clipboard as a subtree, with modification of headline level.
8265 The entire subtree is promoted or demoted in order to match a new headline
8266 level.
8268 If the cursor is at the beginning of a headline, the same level as
8269 that headline is used to paste the tree.
8271 If not, the new level is derived from the *visible* headings
8272 before and after the insertion point, and taken to be the inferior headline
8273 level of the two. So if the previous visible heading is level 3 and the
8274 next is level 4 (or vice versa), level 4 will be used for insertion.
8275 This makes sure that the subtree remains an independent subtree and does
8276 not swallow low level entries.
8278 You can also force a different level, either by using a numeric prefix
8279 argument, or by inserting the heading marker by hand. For example, if the
8280 cursor is after \"*****\", then the tree will be shifted to level 5.
8282 If optional TREE is given, use this text instead of the kill ring.
8284 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8285 move back over whitespace before inserting, and move point to the end of
8286 the inserted text when done.
8288 When REMOVE is non-nil, remove the subtree from the clipboard."
8289 (interactive "P")
8290 (setq tree (or tree (and kill-ring (current-kill 0))))
8291 (unless (org-kill-is-subtree-p tree)
8292 (user-error
8293 (substitute-command-keys
8294 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8295 (org-with-limited-levels
8296 (let* ((visp (not (org-invisible-p)))
8297 (txt tree)
8298 (old-level (if (string-match org-outline-regexp-bol txt)
8299 (- (match-end 0) (match-beginning 0) 1)
8300 -1))
8301 (force-level
8302 (cond
8303 (level (prefix-numeric-value level))
8304 ;; When point is right after the stars in an otherwise
8305 ;; empty headline, use stars as the forced level.
8306 ((and (looking-at-p "[ \t]*$")
8307 (string-match-p "^\\*+ *"
8308 (buffer-substring (line-beginning-position)
8309 (point))))
8310 (org-outline-level))
8311 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8312 (previous-level
8313 (save-excursion
8314 (org-previous-visible-heading 1)
8315 (if (org-at-heading-p) (org-outline-level) 1)))
8316 (next-level
8317 (save-excursion
8318 (if (org-at-heading-p) (org-outline-level)
8319 (org-next-visible-heading 1)
8320 (if (org-at-heading-p) (org-outline-level) 1))))
8321 (new-level (or force-level (max previous-level next-level)))
8322 (shift (if (or (= old-level -1)
8323 (= new-level -1)
8324 (= old-level new-level))
8326 (- new-level old-level)))
8327 (delta (if (> shift 0) -1 1))
8328 (func (if (> shift 0) #'org-demote #'org-promote))
8329 (org-odd-levels-only nil)
8330 beg end newend)
8331 ;; Remove the forced level indicator.
8332 (when (and force-level (not level))
8333 (delete-region (line-beginning-position) (point)))
8334 ;; Paste before the next visible heading or at end of buffer,
8335 ;; unless point is at the beginning of a headline.
8336 (unless (and (bolp) (org-at-heading-p))
8337 (org-next-visible-heading 1)
8338 (unless (bolp) (insert "\n")))
8339 (setq beg (point))
8340 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8341 (insert-before-markers txt)
8342 (unless (string-suffix-p "\n" txt) (insert "\n"))
8343 (setq newend (point))
8344 (org-reinstall-markers-in-region beg)
8345 (setq end (point))
8346 (goto-char beg)
8347 (skip-chars-forward " \t\n\r")
8348 (setq beg (point))
8349 (when (and (org-invisible-p) visp)
8350 (save-excursion (outline-show-heading)))
8351 ;; Shift if necessary.
8352 (unless (= shift 0)
8353 (save-restriction
8354 (narrow-to-region beg end)
8355 (while (not (= shift 0))
8356 (org-map-region func (point-min) (point-max))
8357 (setq shift (+ delta shift)))
8358 (goto-char (point-min))
8359 (setq newend (point-max))))
8360 (when (or for-yank (called-interactively-p 'interactive))
8361 (message "Clipboard pasted as level %d subtree" new-level))
8362 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8363 kill-ring
8364 (equal org-subtree-clip (current-kill 0))
8365 org-subtree-clip-folded)
8366 ;; The tree was folded before it was killed/copied
8367 (outline-hide-subtree))
8368 (when for-yank (goto-char newend))
8369 (when remove (pop kill-ring)))))
8371 (defun org-kill-is-subtree-p (&optional txt)
8372 "Check if the current kill is an outline subtree, or a set of trees.
8373 Returns nil if kill does not start with a headline, or if the first
8374 headline level is not the largest headline level in the tree.
8375 So this will actually accept several entries of equal levels as well,
8376 which is OK for `org-paste-subtree'.
8377 If optional TXT is given, check this string instead of the current kill."
8378 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8379 (re (org-get-limited-outline-regexp))
8380 (^re (concat "^" re))
8381 (start-level (and kill
8382 (string-match
8383 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8384 kill)
8385 (- (match-end 2) (match-beginning 2) 1)))
8386 (start (1+ (or (match-beginning 2) -1))))
8387 (if (not start-level)
8388 (progn
8389 nil) ;; does not even start with a heading
8390 (catch 'exit
8391 (while (setq start (string-match ^re kill (1+ start)))
8392 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8393 (throw 'exit nil)))
8394 t))))
8396 (defvar org-markers-to-move nil
8397 "Markers that should be moved with a cut-and-paste operation.
8398 Those markers are stored together with their positions relative to
8399 the start of the region.")
8401 (defun org-save-markers-in-region (beg end)
8402 "Check markers in region.
8403 If these markers are between BEG and END, record their position relative
8404 to BEG, so that after moving the block of text, we can put the markers back
8405 into place.
8406 This function gets called just before an entry or tree gets cut from the
8407 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8408 called immediately, to move the markers with the entries."
8409 (setq org-markers-to-move nil)
8410 (when (featurep 'org-clock)
8411 (org-clock-save-markers-for-cut-and-paste beg end))
8412 (when (featurep 'org-agenda)
8413 (org-agenda-save-markers-for-cut-and-paste beg end)))
8415 (defun org-check-and-save-marker (marker beg end)
8416 "Check if MARKER is between BEG and END.
8417 If yes, remember the marker and the distance to BEG."
8418 (when (and (marker-buffer marker)
8419 (equal (marker-buffer marker) (current-buffer))
8420 (>= marker beg) (< marker end))
8421 (push (cons marker (- marker beg)) org-markers-to-move)))
8423 (defun org-reinstall-markers-in-region (beg)
8424 "Move all remembered markers to their position relative to BEG."
8425 (dolist (x org-markers-to-move)
8426 (move-marker (car x) (+ beg (cdr x))))
8427 (setq org-markers-to-move nil))
8429 (defun org-narrow-to-subtree ()
8430 "Narrow buffer to the current subtree."
8431 (interactive)
8432 (save-excursion
8433 (save-match-data
8434 (org-with-limited-levels
8435 (narrow-to-region
8436 (progn (org-back-to-heading t) (point))
8437 (progn (org-end-of-subtree t t)
8438 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8439 (point)))))))
8441 (defun org-narrow-to-block ()
8442 "Narrow buffer to the current block."
8443 (interactive)
8444 (let* ((case-fold-search t)
8445 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8446 "^[ \t]*#\\+end_.*")))
8447 (if blockp
8448 (narrow-to-region (car blockp) (cdr blockp))
8449 (user-error "Not in a block"))))
8451 (defun org-clone-subtree-with-time-shift (n &optional shift)
8452 "Clone the task (subtree) at point N times.
8453 The clones will be inserted as siblings.
8455 In interactive use, the user will be prompted for the number of
8456 clones to be produced. If the entry has a timestamp, the user
8457 will also be prompted for a time shift, which may be a repeater
8458 as used in time stamps, for example `+3d'. To disable this,
8459 you can call the function with a universal prefix argument.
8461 When a valid repeater is given and the entry contains any time
8462 stamps, the clones will become a sequence in time, with time
8463 stamps in the subtree shifted for each clone produced. If SHIFT
8464 is nil or the empty string, time stamps will be left alone. The
8465 ID property of the original subtree is removed.
8467 In each clone, all the CLOCK entries will be removed. This
8468 prevents Org from considering that the clocked times overlap.
8470 If the original subtree did contain time stamps with a repeater,
8471 the following will happen:
8472 - the repeater will be removed in each clone
8473 - an additional clone will be produced, with the current, unshifted
8474 date(s) in the entry.
8475 - the original entry will be placed *after* all the clones, with
8476 repeater intact.
8477 - the start days in the repeater in the original entry will be shifted
8478 to past the last clone.
8479 In this way you can spell out a number of instances of a repeating task,
8480 and still retain the repeater to cover future instances of the task.
8482 As described above, N+1 clones are produced when the original
8483 subtree has a repeater. Setting N to 0, then, can be used to
8484 remove the repeater from a subtree and create a shifted clone
8485 with the original repeater."
8486 (interactive "nNumber of clones to produce: ")
8487 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8488 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8489 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8490 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8491 (shift
8492 (or shift
8493 (if (and (not (equal current-prefix-arg '(4)))
8494 (save-excursion
8495 (goto-char beg)
8496 (re-search-forward org-ts-regexp-both end-of-tree t)))
8497 (read-from-minibuffer
8498 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8499 ""))) ;No time shift
8500 (doshift
8501 (and (org-string-nw-p shift)
8502 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8503 shift)
8504 (user-error "Invalid shift specification %s" shift)))))
8505 (goto-char end-of-tree)
8506 (unless (bolp) (insert "\n"))
8507 (let* ((end (point))
8508 (template (buffer-substring beg end))
8509 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8510 (shift-what (pcase (and doshift (match-string 2 shift))
8511 (`nil nil)
8512 ("d" 'day)
8513 ("w" (setq shift-n (* 7 shift-n)) 'day)
8514 ("m" 'month)
8515 ("y" 'year)
8516 (_ (error "Unsupported time unit"))))
8517 (nmin 1)
8518 (nmax n)
8519 (n-no-remove -1)
8520 (idprop (org-entry-get nil "ID")))
8521 (when (and doshift
8522 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8523 template))
8524 (delete-region beg end)
8525 (setq end beg)
8526 (setq nmin 0)
8527 (setq nmax (1+ nmax))
8528 (setq n-no-remove nmax))
8529 (goto-char end)
8530 (cl-loop for n from nmin to nmax do
8531 (insert
8532 ;; Prepare clone.
8533 (with-temp-buffer
8534 (insert template)
8535 (org-mode)
8536 (goto-char (point-min))
8537 (org-show-subtree)
8538 (and idprop (if org-clone-delete-id
8539 (org-entry-delete nil "ID")
8540 (org-id-get-create t)))
8541 (unless (= n 0)
8542 (while (re-search-forward org-clock-line-re nil t)
8543 (delete-region (line-beginning-position)
8544 (line-beginning-position 2)))
8545 (goto-char (point-min))
8546 (while (re-search-forward org-drawer-regexp nil t)
8547 (org-remove-empty-drawer-at (point))))
8548 (goto-char (point-min))
8549 (when doshift
8550 (while (re-search-forward org-ts-regexp-both nil t)
8551 (org-timestamp-change (* n shift-n) shift-what))
8552 (unless (= n n-no-remove)
8553 (goto-char (point-min))
8554 (while (re-search-forward org-ts-regexp nil t)
8555 (save-excursion
8556 (goto-char (match-beginning 0))
8557 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8558 (delete-region (match-beginning 1) (match-end 1)))))))
8559 (buffer-string)))))
8560 (goto-char beg)))
8562 ;;; Outline Sorting
8564 (defun org-sort (&optional with-case)
8565 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8566 Optional argument WITH-CASE means sort case-sensitively."
8567 (interactive "P")
8568 (org-call-with-arg
8569 (cond ((org-at-table-p) #'org-table-sort-lines)
8570 ((org-at-item-p) #'org-sort-list)
8571 (t #'org-sort-entries))
8572 with-case))
8574 (defun org-sort-remove-invisible (s)
8575 "Remove invisible part of links and emphasis markers from string S."
8576 (remove-text-properties 0 (length s) org-rm-props s)
8577 (replace-regexp-in-string
8578 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8579 (replace-regexp-in-string
8580 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8581 (org-link-display-format s)
8582 t t) t t))
8584 (defvar org-priority-regexp) ; defined later in the file
8586 (defvar org-after-sorting-entries-or-items-hook nil
8587 "Hook that is run after a bunch of entries or items have been sorted.
8588 When children are sorted, the cursor is in the parent line when this
8589 hook gets called. When a region or a plain list is sorted, the cursor
8590 will be in the first entry of the sorted region/list.")
8592 (defun org-sort-entries
8593 (&optional with-case sorting-type getkey-func compare-func property
8594 interactive?)
8595 "Sort entries on a certain level of an outline tree.
8596 If there is an active region, the entries in the region are sorted.
8597 Else, if the cursor is before the first entry, sort the top-level items.
8598 Else, the children of the entry at point are sorted.
8600 Sorting can be alphabetically, numerically, by date/time as given by
8601 a time stamp, by a property, by priority order, or by a custom function.
8603 The command prompts for the sorting type unless it has been given to the
8604 function through the SORTING-TYPE argument, which needs to be a character,
8605 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8606 the precise meaning of each character:
8608 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8609 c By creation time, which is assumed to be the first inactive time stamp
8610 at the beginning of a line.
8611 d By deadline date/time.
8612 k By clocking time.
8613 n Numerically, by converting the beginning of the entry/item to a number.
8614 o By order of TODO keywords.
8615 p By priority according to the cookie.
8616 r By the value of a property.
8617 s By scheduled date/time.
8618 t By date/time, either the first active time stamp in the entry, or, if
8619 none exist, by the first inactive one.
8621 Capital letters will reverse the sort order.
8623 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8624 called with point at the beginning of the record. It must return a
8625 value that is compatible with COMPARE-FUNC, the function used to
8626 compare entries.
8628 Comparing entries ignores case by default. However, with an optional argument
8629 WITH-CASE, the sorting considers case as well.
8631 Sorting is done against the visible part of the headlines, it ignores hidden
8632 links.
8634 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8636 A non-nil value for INTERACTIVE? is used to signal that this
8637 function is being called interactively."
8638 (interactive (list current-prefix-arg nil nil nil nil t))
8639 (let ((case-func (if with-case 'identity 'downcase))
8640 start beg end stars re re2
8641 txt what tmp)
8642 ;; Find beginning and end of region to sort
8643 (cond
8644 ((org-region-active-p)
8645 ;; we will sort the region
8646 (setq end (region-end)
8647 what "region")
8648 (goto-char (region-beginning))
8649 (unless (org-at-heading-p) (outline-next-heading))
8650 (setq start (point)))
8651 ((or (org-at-heading-p)
8652 (ignore-errors (progn (org-back-to-heading) t)))
8653 ;; we will sort the children of the current headline
8654 (org-back-to-heading)
8655 (setq start (point)
8656 end (progn (org-end-of-subtree t t)
8657 (or (bolp) (insert "\n"))
8658 (when (>= (org-back-over-empty-lines) 1)
8659 (forward-line 1))
8660 (point))
8661 what "children")
8662 (goto-char start)
8663 (outline-show-subtree)
8664 (outline-next-heading))
8666 ;; we will sort the top-level entries in this file
8667 (goto-char (point-min))
8668 (or (org-at-heading-p) (outline-next-heading))
8669 (setq start (point))
8670 (goto-char (point-max))
8671 (beginning-of-line 1)
8672 (when (looking-at ".*?\\S-")
8673 ;; File ends in a non-white line
8674 (end-of-line 1)
8675 (insert "\n"))
8676 (setq end (point-max))
8677 (setq what "top-level")
8678 (goto-char start)
8679 (org-show-all '(headings blocks))))
8681 (setq beg (point))
8682 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8684 (looking-at "\\(\\*+\\)")
8685 (setq stars (match-string 1)
8686 re (concat "^" (regexp-quote stars) " +")
8687 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8688 txt (buffer-substring beg end))
8689 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8690 (when (and (not (equal stars "*")) (string-match re2 txt))
8691 (user-error "Region to sort contains a level above the first entry"))
8693 (unless sorting-type
8694 (message
8695 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8696 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8697 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8698 what)
8699 (setq sorting-type (read-char-exclusive)))
8701 (unless getkey-func
8702 (and (= (downcase sorting-type) ?f)
8703 (setq getkey-func
8704 (or (and interactive?
8705 (org-read-function
8706 "Function for extracting keys: "))
8707 (error "Missing key extractor")))))
8709 (and (= (downcase sorting-type) ?r)
8710 (not property)
8711 (setq property
8712 (completing-read "Property: "
8713 (mapcar #'list (org-buffer-property-keys t))
8714 nil t)))
8716 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8717 (message "Sorting entries...")
8719 (save-restriction
8720 (narrow-to-region start end)
8721 (let ((restore-clock?
8722 ;; The clock marker is lost when using `sort-subr'; mark
8723 ;; the clock with temporary `:org-clock-marker-backup'
8724 ;; text property.
8725 (when (and (eq (org-clock-is-active) (current-buffer))
8726 (<= start (marker-position org-clock-marker))
8727 (>= end (marker-position org-clock-marker)))
8728 (org-with-silent-modifications
8729 (put-text-property (1- org-clock-marker) org-clock-marker
8730 :org-clock-marker-backup t))
8732 (dcst (downcase sorting-type))
8733 (case-fold-search nil)
8734 (now (current-time)))
8735 (org-preserve-local-variables
8736 (sort-subr
8737 (/= dcst sorting-type)
8738 ;; This function moves to the beginning character of the
8739 ;; "record" to be sorted.
8740 (lambda nil
8741 (if (re-search-forward re nil t)
8742 (goto-char (match-beginning 0))
8743 (goto-char (point-max))))
8744 ;; This function moves to the last character of the "record" being
8745 ;; sorted.
8746 (lambda nil
8747 (save-match-data
8748 (condition-case nil
8749 (outline-forward-same-level 1)
8750 (error
8751 (goto-char (point-max))))))
8752 ;; This function returns the value that gets sorted against.
8753 (lambda ()
8754 (cond
8755 ((= dcst ?n)
8756 (string-to-number
8757 (org-sort-remove-invisible (org-get-heading t t t t))))
8758 ((= dcst ?a)
8759 (funcall case-func
8760 (org-sort-remove-invisible (org-get-heading t t t t))))
8761 ((= dcst ?k)
8762 (or (get-text-property (point) :org-clock-minutes) 0))
8763 ((= dcst ?t)
8764 (let ((end (save-excursion (outline-next-heading) (point))))
8765 (if (or (re-search-forward org-ts-regexp end t)
8766 (re-search-forward org-ts-regexp-both end t))
8767 (org-time-string-to-seconds (match-string 0))
8768 (float-time now))))
8769 ((= dcst ?c)
8770 (let ((end (save-excursion (outline-next-heading) (point))))
8771 (if (re-search-forward
8772 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8773 end t)
8774 (org-time-string-to-seconds (match-string 0))
8775 (float-time now))))
8776 ((= dcst ?s)
8777 (let ((end (save-excursion (outline-next-heading) (point))))
8778 (if (re-search-forward org-scheduled-time-regexp end t)
8779 (org-time-string-to-seconds (match-string 1))
8780 (float-time now))))
8781 ((= dcst ?d)
8782 (let ((end (save-excursion (outline-next-heading) (point))))
8783 (if (re-search-forward org-deadline-time-regexp end t)
8784 (org-time-string-to-seconds (match-string 1))
8785 (float-time now))))
8786 ((= dcst ?p)
8787 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8788 (string-to-char (match-string 2))
8789 org-default-priority))
8790 ((= dcst ?r)
8791 (or (org-entry-get nil property) ""))
8792 ((= dcst ?o)
8793 (when (looking-at org-complex-heading-regexp)
8794 (let* ((m (match-string 2))
8795 (s (if (member m org-done-keywords) '- '+)))
8796 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8797 ((= dcst ?f)
8798 (if getkey-func
8799 (progn
8800 (setq tmp (funcall getkey-func))
8801 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8802 tmp)
8803 (error "Invalid key function `%s'" getkey-func)))
8804 (t (error "Invalid sorting type `%c'" sorting-type))))
8806 (cond
8807 ((= dcst ?a) 'org-string-collate-lessp)
8808 ((= dcst ?f)
8809 (or compare-func
8810 (and interactive?
8811 (org-read-function
8812 (concat "Function for comparing keys "
8813 "(empty for default `sort-subr' predicate): ")
8814 'allow-empty))))
8815 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8816 (when restore-clock?
8817 (move-marker org-clock-marker
8818 (1+ (next-single-property-change
8819 start :org-clock-marker-backup)))
8820 (remove-text-properties (1- org-clock-marker) org-clock-marker
8821 '(:org-clock-marker-backup t)))))
8822 (run-hooks 'org-after-sorting-entries-or-items-hook)
8823 (message "Sorting entries...done")))
8825 (defun org-contextualize-keys (alist contexts)
8826 "Return valid elements in ALIST depending on CONTEXTS.
8828 `org-agenda-custom-commands' or `org-capture-templates' are the
8829 values used for ALIST, and `org-agenda-custom-commands-contexts'
8830 or `org-capture-templates-contexts' are the associated contexts
8831 definitions."
8832 (let ((contexts
8833 ;; normalize contexts
8834 (mapcar
8835 (lambda(c) (cond ((listp (cadr c))
8836 (list (car c) (car c) (nth 1 c)))
8837 ((string= "" (cadr c))
8838 (list (car c) (car c) (nth 2 c)))
8839 (t c)))
8840 contexts))
8841 (a alist) r s)
8842 ;; loop over all commands or templates
8843 (dolist (c a)
8844 (let (vrules repl)
8845 (cond
8846 ((not (assoc (car c) contexts))
8847 (push c r))
8848 ((and (assoc (car c) contexts)
8849 (setq vrules (org-contextualize-validate-key
8850 (car c) contexts)))
8851 (mapc (lambda (vr)
8852 (unless (equal (car vr) (cadr vr))
8853 (setq repl vr)))
8854 vrules)
8855 (if (not repl) (push c r)
8856 (push (cadr repl) s)
8857 (push
8858 (cons (car c)
8859 (cdr (or (assoc (cadr repl) alist)
8860 (error "Undefined key `%s' as contextual replacement for `%s'"
8861 (cadr repl) (car c)))))
8862 r))))))
8863 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8864 (delq
8866 (delete-dups
8867 (mapcar (lambda (x)
8868 (let ((tpl (car x)))
8869 (unless (delq
8871 (mapcar (lambda (y)
8872 (equal y tpl))
8874 x)))
8875 (reverse r))))))
8877 (defun org-contextualize-validate-key (key contexts)
8878 "Check CONTEXTS for agenda or capture KEY."
8879 (let (res)
8880 (dolist (r contexts)
8881 (dolist (rr (car (last r)))
8882 (when
8883 (and (equal key (car r))
8884 (if (functionp rr) (funcall rr)
8885 (or (and (eq (car rr) 'in-file)
8886 (buffer-file-name)
8887 (string-match (cdr rr) (buffer-file-name)))
8888 (and (eq (car rr) 'in-mode)
8889 (string-match (cdr rr) (symbol-name major-mode)))
8890 (and (eq (car rr) 'in-buffer)
8891 (string-match (cdr rr) (buffer-name)))
8892 (when (and (eq (car rr) 'not-in-file)
8893 (buffer-file-name))
8894 (not (string-match (cdr rr) (buffer-file-name))))
8895 (when (eq (car rr) 'not-in-mode)
8896 (not (string-match (cdr rr) (symbol-name major-mode))))
8897 (when (eq (car rr) 'not-in-buffer)
8898 (not (string-match (cdr rr) (buffer-name)))))))
8899 (push r res))))
8900 (delete-dups (delq nil res))))
8902 ;; Defined to provide a value for defcustom, since there is no
8903 ;; string-collate-greaterp in Emacs.
8904 (defun org-string-collate-greaterp (s1 s2)
8905 "Return non-nil if S1 is greater than S2 in collation order."
8906 (not (org-string-collate-lessp s1 s2)))
8908 ;;;###autoload
8909 (defun org-run-like-in-org-mode (cmd)
8910 "Run a command, pretending that the current buffer is in Org mode.
8911 This will temporarily bind local variables that are typically bound in
8912 Org mode to the values they have in Org mode, and then interactively
8913 call CMD."
8914 (org-load-modules-maybe)
8915 (let (binds)
8916 (dolist (var (org-get-local-variables))
8917 (when (or (not (boundp (car var)))
8918 (eq (symbol-value (car var))
8919 (default-value (car var))))
8920 (push (list (car var) `(quote ,(cadr var))) binds)))
8921 (eval `(let ,binds
8922 (call-interactively (quote ,cmd))))))
8924 (defun org-get-category (&optional pos force-refresh)
8925 "Get the category applying to position POS."
8926 (save-match-data
8927 (when force-refresh (org-refresh-category-properties))
8928 (let ((pos (or pos (point))))
8929 (or (get-text-property pos 'org-category)
8930 (progn (org-refresh-category-properties)
8931 (get-text-property pos 'org-category))))))
8933 ;;; Refresh properties
8935 (defun org-refresh-properties (dprop tprop)
8936 "Refresh buffer text properties.
8937 DPROP is the drawer property and TPROP is either the
8938 corresponding text property to set, or an alist with each element
8939 being a text property (as a symbol) and a function to apply to
8940 the value of the drawer property."
8941 (let* ((case-fold-search t)
8942 (inhibit-read-only t)
8943 (inherit? (org-property-inherit-p dprop))
8944 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8945 (global (and inherit? (org--property-global-value dprop nil))))
8946 (org-with-silent-modifications
8947 (org-with-point-at 1
8948 ;; Set global values (e.g., values defined through
8949 ;; "#+PROPERTY:" keywords) to the whole buffer.
8950 (when global (put-text-property (point-min) (point-max) tprop global))
8951 ;; Set local values.
8952 (while (re-search-forward property-re nil t)
8953 (when (org-at-property-p)
8954 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8955 (outline-next-heading))))))
8957 (defun org-refresh-property (tprop p &optional inherit)
8958 "Refresh the buffer text property TPROP from the drawer property P.
8959 The refresh happens only for the current headline, or the whole
8960 sub-tree if optional argument INHERIT is non-nil."
8961 (unless (org-before-first-heading-p)
8962 (save-excursion
8963 (org-back-to-heading t)
8964 (let ((start (point))
8965 (end (save-excursion
8966 (if inherit (org-end-of-subtree t t)
8967 (or (outline-next-heading) (point-max))))))
8968 (if (symbolp tprop)
8969 ;; TPROP is a text property symbol.
8970 (put-text-property start end tprop p)
8971 ;; TPROP is an alist with (property . function) elements.
8972 (pcase-dolist (`(,prop . ,f) tprop)
8973 (put-text-property start end prop (funcall f p))))))))
8975 (defun org-refresh-category-properties ()
8976 "Refresh category text properties in the buffer."
8977 (let ((case-fold-search t)
8978 (inhibit-read-only t)
8979 (default-category
8980 (cond ((null org-category)
8981 (if buffer-file-name
8982 (file-name-sans-extension
8983 (file-name-nondirectory buffer-file-name))
8984 "???"))
8985 ((symbolp org-category) (symbol-name org-category))
8986 (t org-category))))
8987 (org-with-silent-modifications
8988 (org-with-wide-buffer
8989 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8990 ;; This is the default category for the buffer. If none is
8991 ;; found, fall-back to `org-category' or buffer file name.
8992 (put-text-property
8993 (point-min) (point-max)
8994 'org-category
8995 (catch 'buffer-category
8996 (goto-char (point-max))
8997 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8998 (let ((element (org-element-at-point)))
8999 (when (eq (org-element-type element) 'keyword)
9000 (throw 'buffer-category
9001 (org-element-property :value element)))))
9002 default-category))
9003 ;; Set sub-tree specific categories.
9004 (goto-char (point-min))
9005 (let ((regexp (org-re-property "CATEGORY")))
9006 (while (re-search-forward regexp nil t)
9007 (let ((value (match-string-no-properties 3)))
9008 (when (org-at-property-p)
9009 (put-text-property
9010 (save-excursion (org-back-to-heading t) (point))
9011 (save-excursion (org-end-of-subtree t t) (point))
9012 'org-category
9013 value)))))))))
9015 (defun org-refresh-stats-properties ()
9016 "Refresh stats text properties in the buffer."
9017 (org-with-silent-modifications
9018 (org-with-point-at 1
9019 (let ((regexp (concat org-outline-regexp-bol
9020 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9021 (while (re-search-forward regexp nil t)
9022 (let* ((numerator (string-to-number (match-string 1)))
9023 (denominator (and (match-end 2)
9024 (string-to-number (match-string 2))))
9025 (stats (cond ((not denominator) numerator) ;percent
9026 ((= denominator 0) 0)
9027 (t (/ (* numerator 100) denominator)))))
9028 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9029 'org-stats stats)))))))
9031 (defun org-refresh-effort-properties ()
9032 "Refresh effort properties"
9033 (org-refresh-properties
9034 org-effort-property
9035 '((effort . identity)
9036 (effort-minutes . org-duration-to-minutes))))
9038 ;;;; Link Stuff
9040 ;;; Link abbreviations
9042 (defun org-link-expand-abbrev (link)
9043 "Apply replacements as defined in `org-link-abbrev-alist'."
9044 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9045 (let* ((key (match-string 1 link))
9046 (as (or (assoc key org-link-abbrev-alist-local)
9047 (assoc key org-link-abbrev-alist)))
9048 (tag (and (match-end 2) (match-string 3 link)))
9049 rpl)
9050 (if (not as)
9051 link
9052 (setq rpl (cdr as))
9053 (cond
9054 ((symbolp rpl) (funcall rpl tag))
9055 ((string-match "%(\\([^)]+\\))" rpl)
9056 (replace-match
9057 (save-match-data
9058 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9059 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9060 ((string-match "%h" rpl)
9061 (replace-match (url-hexify-string (or tag "")) t t rpl))
9062 (t (concat rpl tag)))))
9063 link))
9065 ;;; Storing and inserting links
9067 (defvar org-insert-link-history nil
9068 "Minibuffer history for links inserted with `org-insert-link'.")
9070 (defvar org-stored-links nil
9071 "Contains the links stored with `org-store-link'.")
9073 (defvar org-store-link-plist nil
9074 "Plist with info about the most recently link created with `org-store-link'.")
9076 (defun org-store-link-functions ()
9077 "Return a list of functions that are called to create and store a link.
9078 The functions defined in the :store property of
9079 `org-link-parameters'.
9081 Each function will be called in turn until one returns a non-nil
9082 value. Each function should check if it is responsible for
9083 creating this link (for example by looking at the major mode).
9084 If not, it must exit and return nil. If yes, it should return
9085 a non-nil value after calling `org-store-link-props' with a list
9086 of properties and values. Special properties are:
9088 :type The link prefix, like \"http\". This must be given.
9089 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9090 This is obligatory as well.
9091 :description Optional default description for the second pair
9092 of brackets in an Org mode link. The user can still change
9093 this when inserting this link into an Org mode buffer.
9095 In addition to these, any additional properties can be specified
9096 and then used in capture templates."
9097 (cl-loop for link in org-link-parameters
9098 with store-func
9099 do (setq store-func (org-link-get-parameter (car link) :store))
9100 if store-func
9101 collect store-func))
9103 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9104 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9106 ;;;###autoload
9107 (defun org-store-link (arg &optional interactive?)
9108 "Store an org-link to the current location.
9109 \\<org-mode-map>
9110 This link is added to `org-stored-links' and can later be inserted
9111 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9113 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9114 A single
9115 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9116 `org-gnus-prefer-web-links' for links to Usenet articles.
9118 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9119 skipping storing functions that are not
9120 part of Org core.
9122 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9123 prefix ARG forces storing a link for each line in the
9124 active region.
9126 Assume the function is called interactively if INTERACTIVE? is
9127 non-nil."
9128 (interactive "P\np")
9129 (org-load-modules-maybe)
9130 (if (and (equal arg '(64)) (org-region-active-p))
9131 (save-excursion
9132 (let ((end (region-end)))
9133 (goto-char (region-beginning))
9134 (set-mark (point))
9135 (while (< (point-at-eol) end)
9136 (move-end-of-line 1) (activate-mark)
9137 (let (current-prefix-arg)
9138 (call-interactively 'org-store-link))
9139 (move-beginning-of-line 2)
9140 (set-mark (point)))))
9141 (setq org-store-link-plist nil)
9142 (let (link cpltxt desc description search txt custom-id agenda-link)
9143 (cond
9144 ;; Store a link using an external link type, if any function is
9145 ;; available. If more than one can generate a link from current
9146 ;; location, ask which one to use.
9147 ((and (not (equal arg '(16)))
9148 (let ((results-alist nil))
9149 (dolist (f (org-store-link-functions))
9150 (when (funcall f)
9151 ;; XXX: return value is not link's plist, so we
9152 ;; store the new value before it is modified. It
9153 ;; would be cleaner to ask store link functions to
9154 ;; return the plist instead.
9155 (push (cons f (copy-sequence org-store-link-plist))
9156 results-alist)))
9157 (pcase results-alist
9158 (`nil nil)
9159 (`((,_ . ,_)) t) ;single choice: nothing to do
9160 (`((,name . ,_) . ,_)
9161 ;; Reinstate link plist associated to the chosen
9162 ;; function.
9163 (apply #'org-store-link-props
9164 (cdr (assoc-string
9165 (completing-read
9166 "Which function for creating the link? "
9167 (mapcar #'car results-alist)
9168 nil t (symbol-name name))
9169 results-alist)))
9170 t))))
9171 (setq link (plist-get org-store-link-plist :link))
9172 (setq desc (or (plist-get org-store-link-plist :description)
9173 link)))
9175 ;; Store a link from a source code buffer.
9176 ((org-src-edit-buffer-p)
9177 (let ((coderef-format (org-src-coderef-format)))
9178 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9179 (setq link (format "(%s)" (match-string-no-properties 3))))
9180 (interactive?
9181 (let ((label (read-string "Code line label: ")))
9182 (end-of-line)
9183 (setq link (format coderef-format label))
9184 (let ((gc (- 79 (length link))))
9185 (if (< (current-column) gc)
9186 (org-move-to-column gc t)
9187 (insert " ")))
9188 (insert link)
9189 (setq link (concat "(" label ")"))
9190 (setq desc nil)))
9191 (t (setq link nil)))))
9193 ;; We are in the agenda, link to referenced location
9194 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9195 (let ((m (or (get-text-property (point) 'org-hd-marker)
9196 (get-text-property (point) 'org-marker))))
9197 (when m
9198 (org-with-point-at m
9199 (setq agenda-link (org-store-link nil interactive?))))))
9201 ((eq major-mode 'calendar-mode)
9202 (let ((cd (calendar-cursor-to-date)))
9203 (setq link
9204 (format-time-string
9205 (car org-time-stamp-formats)
9206 (apply 'encode-time
9207 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9208 nil nil nil))))
9209 (org-store-link-props :type "calendar" :date cd)))
9211 ((eq major-mode 'help-mode)
9212 (setq link (concat "help:" (save-excursion
9213 (goto-char (point-min))
9214 (looking-at "^[^ ]+")
9215 (match-string 0))))
9216 (org-store-link-props :type "help"))
9218 ((eq major-mode 'w3-mode)
9219 (setq cpltxt (if (and (buffer-name)
9220 (not (string-match "Untitled" (buffer-name))))
9221 (buffer-name)
9222 (url-view-url t))
9223 link (url-view-url t))
9224 (org-store-link-props :type "w3" :url (url-view-url t)))
9226 ((eq major-mode 'image-mode)
9227 (setq cpltxt (concat "file:"
9228 (abbreviate-file-name buffer-file-name))
9229 link cpltxt)
9230 (org-store-link-props :type "image" :file buffer-file-name))
9232 ;; In dired, store a link to the file of the current line
9233 ((derived-mode-p 'dired-mode)
9234 (let ((file (dired-get-filename nil t)))
9235 (setq file (if file
9236 (abbreviate-file-name
9237 (expand-file-name (dired-get-filename nil t)))
9238 ;; otherwise, no file so use current directory.
9239 default-directory))
9240 (setq cpltxt (concat "file:" file)
9241 link cpltxt)))
9243 ((setq search (run-hook-with-args-until-success
9244 'org-create-file-search-functions))
9245 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9246 "::" search))
9247 (setq cpltxt (or description link)))
9249 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9250 (org-with-limited-levels
9251 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9252 (cond
9253 ;; Store a link using the target at point
9254 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9255 (setq cpltxt
9256 (concat "file:"
9257 (abbreviate-file-name
9258 (buffer-file-name (buffer-base-buffer)))
9259 "::" (match-string 1))
9260 link cpltxt))
9261 ((and (featurep 'org-id)
9262 (or (eq org-id-link-to-org-use-id t)
9263 (and interactive?
9264 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9265 (and (eq org-id-link-to-org-use-id
9266 'create-if-interactive-and-no-custom-id)
9267 (not custom-id))))
9268 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9269 ;; Store a link using the ID at point
9270 (setq link (condition-case nil
9271 (prog1 (org-id-store-link)
9272 (setq desc (or (plist-get org-store-link-plist
9273 :description)
9274 "")))
9275 (error
9276 ;; Probably before first headline, link only to file
9277 (concat "file:"
9278 (abbreviate-file-name
9279 (buffer-file-name (buffer-base-buffer))))))))
9281 ;; Just link to current headline
9282 (setq cpltxt (concat "file:"
9283 (abbreviate-file-name
9284 (buffer-file-name (buffer-base-buffer)))))
9285 ;; Add a context search string
9286 (when (org-xor org-context-in-file-links
9287 (equal arg '(4)))
9288 (let* ((element (org-element-at-point))
9289 (name (org-element-property :name element)))
9290 (setq txt (cond
9291 ((org-at-heading-p) nil)
9292 (name)
9293 ((org-region-active-p)
9294 (buffer-substring (region-beginning) (region-end)))))
9295 (when (or (null txt) (string-match "\\S-" txt))
9296 (setq cpltxt
9297 (concat cpltxt "::"
9298 (condition-case nil
9299 (org-make-org-heading-search-string txt)
9300 (error "")))
9301 desc (or name
9302 (nth 4 (ignore-errors (org-heading-components)))
9303 "NONE")))))
9304 (when (string-match "::\\'" cpltxt)
9305 (setq cpltxt (substring cpltxt 0 -2)))
9306 (setq link cpltxt)))))
9308 ((buffer-file-name (buffer-base-buffer))
9309 ;; Just link to this file here.
9310 (setq cpltxt (concat "file:"
9311 (abbreviate-file-name
9312 (buffer-file-name (buffer-base-buffer)))))
9313 ;; Add a context string.
9314 (when (org-xor org-context-in-file-links
9315 (equal arg '(4)))
9316 (setq txt (if (org-region-active-p)
9317 (buffer-substring (region-beginning) (region-end))
9318 (buffer-substring (point-at-bol) (point-at-eol))))
9319 ;; Only use search option if there is some text.
9320 (when (string-match "\\S-" txt)
9321 (setq cpltxt
9322 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9323 desc "NONE")))
9324 (setq link cpltxt))
9326 (interactive?
9327 (user-error "No method for storing a link from this buffer"))
9329 (t (setq link nil)))
9331 ;; We're done setting link and desc, clean up
9332 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9333 (setq link (or link cpltxt)
9334 desc (or desc cpltxt))
9335 (cond ((not desc))
9336 ((equal desc "NONE") (setq desc nil))
9337 (t (setq desc
9338 (replace-regexp-in-string
9339 org-bracket-link-analytic-regexp
9340 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9341 desc))))
9342 ;; Return the link
9343 (if (not (and interactive? link))
9344 (or agenda-link (and link (org-make-link-string link desc)))
9345 (push (list link desc) org-stored-links)
9346 (message "Stored: %s" (or desc link))
9347 (when custom-id
9348 (setq link (concat "file:" (abbreviate-file-name
9349 (buffer-file-name)) "::#" custom-id))
9350 (push (list link desc) org-stored-links))
9351 (car org-stored-links)))))
9353 (defun org-store-link-props (&rest plist)
9354 "Store link properties.
9355 The properties are pre-processed by extracting names, addresses
9356 and dates."
9357 (let ((x (plist-get plist :from)))
9358 (when x
9359 (let ((adr (mail-extract-address-components x)))
9360 (setq plist (plist-put plist :fromname (car adr)))
9361 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9362 (let ((x (plist-get plist :to)))
9363 (when x
9364 (let ((adr (mail-extract-address-components x)))
9365 (setq plist (plist-put plist :toname (car adr)))
9366 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9367 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9368 (when x
9369 (setq plist (plist-put plist :date-timestamp
9370 (format-time-string
9371 (org-time-stamp-format t) x)))
9372 (setq plist (plist-put plist :date-timestamp-inactive
9373 (format-time-string
9374 (org-time-stamp-format t t) x)))))
9375 (let ((from (plist-get plist :from))
9376 (to (plist-get plist :to)))
9377 (when (and from to org-from-is-user-regexp)
9378 (setq plist
9379 (plist-put plist :fromto
9380 (if (string-match org-from-is-user-regexp from)
9381 (concat "to %t")
9382 (concat "from %f"))))))
9383 (setq org-store-link-plist plist))
9385 (defun org-add-link-props (&rest plist)
9386 "Add these properties to the link property list."
9387 (let (key value)
9388 (while plist
9389 (setq key (pop plist) value (pop plist))
9390 (setq org-store-link-plist
9391 (plist-put org-store-link-plist key value)))))
9393 (defun org-email-link-description (&optional fmt)
9394 "Return the description part of an email link.
9395 This takes information from `org-store-link-plist' and formats it
9396 according to FMT (default from `org-email-link-description-format')."
9397 (setq fmt (or fmt org-email-link-description-format))
9398 (let* ((p org-store-link-plist)
9399 (to (plist-get p :toaddress))
9400 (from (plist-get p :fromaddress))
9401 (table
9402 (list
9403 (cons "%c" (plist-get p :fromto))
9404 (cons "%F" (plist-get p :from))
9405 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9406 (cons "%T" (plist-get p :to))
9407 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9408 (cons "%s" (plist-get p :subject))
9409 (cons "%d" (plist-get p :date))
9410 (cons "%m" (plist-get p :message-id)))))
9411 (when (string-match "%c" fmt)
9412 ;; Check if the user wrote this message
9413 (if (and org-from-is-user-regexp from to
9414 (save-match-data (string-match org-from-is-user-regexp from)))
9415 (setq fmt (replace-match "to %t" t t fmt))
9416 (setq fmt (replace-match "from %f" t t fmt))))
9417 (org-replace-escapes fmt table)))
9419 (defun org-make-org-heading-search-string (&optional string)
9420 "Make search string for the current headline or STRING."
9421 (let ((s (or string
9422 (and (derived-mode-p 'org-mode)
9423 (save-excursion
9424 (org-back-to-heading t)
9425 (org-element-property :raw-value (org-element-at-point))))))
9426 (lines org-context-in-file-links))
9427 (unless string (setq s (concat "*" s))) ;Add * for headlines
9428 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9429 (when (and string (integerp lines) (> lines 0))
9430 (let ((slines (org-split-string s "\n")))
9431 (when (< lines (length slines))
9432 (setq s (mapconcat
9433 'identity
9434 (reverse (nthcdr (- (length slines) lines)
9435 (reverse slines))) "\n")))))
9436 (mapconcat #'identity (split-string s) " ")))
9438 (defconst org-link-escape-chars
9439 ;;%20 %5B %5D %25
9440 '(?\s ?\[ ?\] ?%)
9441 "List of characters that should be escaped in a link when stored to Org.
9442 This is the list that is used for internal purposes.")
9444 (defun org-make-link-string (link &optional description)
9445 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9446 (unless (org-string-nw-p link) (error "Empty link"))
9447 (let ((uri (cond ((string-match org-link-types-re link)
9448 (concat (match-string 1 link)
9449 (org-link-escape (substring link (match-end 1)))))
9450 ((or (file-name-absolute-p link)
9451 (string-match-p "\\`\\.\\.?/" link))
9452 (org-link-escape link))
9453 ;; For readability, do not encode space characters
9454 ;; in fuzzy links.
9455 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9456 (description
9457 (and (org-string-nw-p description)
9458 ;; Remove brackets from description, as they are fatal.
9459 (replace-regexp-in-string
9460 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9461 (org-trim description)))))
9462 (format "[[%s]%s]"
9464 (if description (format "[%s]" description) ""))))
9466 (defun org-link-escape (text &optional table merge)
9467 "Return percent escaped representation of TEXT.
9468 TEXT is a string with the text to escape.
9469 Optional argument TABLE is a list with characters that should be
9470 escaped. When nil, `org-link-escape-chars' is used.
9471 If optional argument MERGE is set, merge TABLE into
9472 `org-link-escape-chars'."
9473 (let ((characters-to-encode
9474 (cond ((null table) org-link-escape-chars)
9475 (merge (append org-link-escape-chars table))
9476 (t table))))
9477 (mapconcat
9478 (lambda (c)
9479 (if (or (memq c characters-to-encode)
9480 (and org-url-hexify-p (or (< c 32) (> c 126))))
9481 (mapconcat (lambda (e) (format "%%%.2X" e))
9482 (or (encode-coding-char c 'utf-8)
9483 (error "Unable to percent escape character: %c" c))
9485 (char-to-string c)))
9486 text "")))
9488 (defun org-link-unescape (str)
9489 "Unhex hexified Unicode parts in string STR.
9490 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9491 reciprocal of `org-link-escape', which see."
9492 (if (org-string-nw-p str)
9493 (replace-regexp-in-string
9494 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9495 str))
9497 (defun org-link-unescape-compound (hex)
9498 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9499 Note: this function also decodes single byte encodings like
9500 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9501 (save-match-data
9502 (let* ((bytes (cdr (split-string hex "%")))
9503 (ret "")
9504 (eat 0)
9505 (sum 0))
9506 (while bytes
9507 (let* ((val (string-to-number (pop bytes) 16))
9508 (shift-xor
9509 (if (= 0 eat)
9510 (cond
9511 ((>= val 252) (cons 6 252))
9512 ((>= val 248) (cons 5 248))
9513 ((>= val 240) (cons 4 240))
9514 ((>= val 224) (cons 3 224))
9515 ((>= val 192) (cons 2 192))
9516 (t (cons 0 0)))
9517 (cons 6 128))))
9518 (when (>= val 192) (setq eat (car shift-xor)))
9519 (setq val (logxor val (cdr shift-xor)))
9520 (setq sum (+ (lsh sum (car shift-xor)) val))
9521 (when (> eat 0) (setq eat (- eat 1)))
9522 (cond
9523 ((= 0 eat) ;multi byte
9524 (setq ret (concat ret (char-to-string sum)))
9525 (setq sum 0))
9526 ((not bytes) ; single byte(s)
9527 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9528 ret)))
9530 (defun org-link-unescape-single-byte-sequence (hex)
9531 "Unhexify hex-encoded single byte character sequences."
9532 (mapconcat (lambda (byte)
9533 (char-to-string (string-to-number byte 16)))
9534 (cdr (split-string hex "%")) ""))
9536 (defun org-fixup-message-id-for-http (s)
9537 "Replace special characters in a message id, so it can be used in an http query."
9538 (when (string-match "%" s)
9539 (setq s (mapconcat (lambda (c)
9540 (if (eq c ?%)
9541 "%25"
9542 (char-to-string c)))
9543 s "")))
9544 (while (string-match "<" s)
9545 (setq s (replace-match "%3C" t t s)))
9546 (while (string-match ">" s)
9547 (setq s (replace-match "%3E" t t s)))
9548 (while (string-match "@" s)
9549 (setq s (replace-match "%40" t t s)))
9552 (defun org-link-prettify (link)
9553 "Return a human-readable representation of LINK.
9554 The car of LINK must be a raw link.
9555 The cdr of LINK must be either a link description or nil."
9556 (let ((desc (or (cadr link) "<no description>")))
9557 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9558 "<" (car link) ">")))
9560 ;;;###autoload
9561 (defun org-insert-link-global ()
9562 "Insert a link like Org mode does.
9563 This command can be called in any mode to insert a link in Org syntax."
9564 (interactive)
9565 (org-load-modules-maybe)
9566 (org-run-like-in-org-mode 'org-insert-link))
9568 (defun org-insert-all-links (arg &optional pre post)
9569 "Insert all links in `org-stored-links'.
9570 When a universal prefix, do not delete the links from `org-stored-links'.
9571 When `ARG' is a number, insert the last N link(s).
9572 `PRE' and `POST' are optional arguments to define a string to
9573 prepend or to append."
9574 (interactive "P")
9575 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9576 (links (copy-sequence org-stored-links))
9577 (pr (or pre "- "))
9578 (po (or post "\n"))
9579 (cnt 1) l)
9580 (if (null org-stored-links)
9581 (message "No link to insert")
9582 (while (and (or (listp arg) (>= arg cnt))
9583 (setq l (if (listp arg)
9584 (pop links)
9585 (pop org-stored-links))))
9586 (setq cnt (1+ cnt))
9587 (insert pr)
9588 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9589 (insert po)))))
9591 (defun org-insert-last-stored-link (arg)
9592 "Insert the last link stored in `org-stored-links'."
9593 (interactive "p")
9594 (org-insert-all-links arg "" "\n"))
9596 (defun org-link-fontify-links-to-this-file ()
9597 "Fontify links to the current file in `org-stored-links'."
9598 (let ((f (buffer-file-name)) a b)
9599 (setq a (mapcar (lambda(l)
9600 (let ((ll (car l)))
9601 (when (and (string-match "^file:\\(.+\\)::" ll)
9602 (equal f (expand-file-name (match-string 1 ll))))
9603 ll)))
9604 org-stored-links))
9605 (when (featurep 'org-id)
9606 (setq b (mapcar (lambda(l)
9607 (let ((ll (car l)))
9608 (when (and (string-match "^id:\\(.+\\)$" ll)
9609 (equal f (expand-file-name
9610 (or (org-id-find-id-file
9611 (match-string 1 ll)) ""))))
9612 ll)))
9613 org-stored-links)))
9614 (mapcar (lambda(l)
9615 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9616 (delq nil (append a b)))))
9618 (defvar org--links-history nil)
9619 (defun org-insert-link (&optional complete-file link-location default-description)
9620 "Insert a link. At the prompt, enter the link.
9622 Completion can be used to insert any of the link protocol prefixes in use.
9624 The history can be used to select a link previously stored with
9625 `org-store-link'. When the empty string is entered (i.e. if you just
9626 press `RET' at the prompt), the link defaults to the most recently
9627 stored link. As `SPC' triggers completion in the minibuffer, you need to
9628 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9630 You will also be prompted for a description, and if one is given, it will
9631 be displayed in the buffer instead of the link.
9633 If there is already a link at point, this command will allow you to edit
9634 link and description parts.
9636 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9637 file name can be
9638 selected using completion. The path to the file will be relative to the
9639 current directory if the file is in the current directory or a subdirectory.
9640 Otherwise, the link will be the absolute path as completed in the minibuffer
9641 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9642 option `org-link-file-path-type'.
9644 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9645 absolute path even if the file is in
9646 the current directory or below.
9648 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9649 prefix negates `org-keep-stored-link-after-insertion'.
9651 If the LINK-LOCATION parameter is non-nil, this value will be used as
9652 the link location instead of reading one interactively.
9654 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9655 be used as the default description. Otherwise, if
9656 `org-make-link-description-function' is non-nil, this function
9657 will be called with the link target, and the result will be the
9658 default link description. When called non-interactivily, don't
9659 allow to edit the default description."
9660 (interactive "P")
9661 (let* ((wcf (current-window-configuration))
9662 (origbuf (current-buffer))
9663 (region (when (org-region-active-p)
9664 (buffer-substring (region-beginning) (region-end))))
9665 (remove (and region (list (region-beginning) (region-end))))
9666 (desc region)
9667 (link link-location)
9668 (abbrevs org-link-abbrev-alist-local)
9669 entry all-prefixes auto-desc)
9670 (cond
9671 (link-location) ; specified by arg, just use it.
9672 ((org-in-regexp org-bracket-link-regexp 1)
9673 ;; We do have a link at point, and we are going to edit it.
9674 (setq remove (list (match-beginning 0) (match-end 0)))
9675 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9676 (setq link (read-string "Link: "
9677 (org-link-unescape
9678 (match-string-no-properties 1)))))
9679 ((or (org-in-regexp org-angle-link-re)
9680 (org-in-regexp org-plain-link-re))
9681 ;; Convert to bracket link
9682 (setq remove (list (match-beginning 0) (match-end 0))
9683 link (read-string "Link: "
9684 (org-unbracket-string "<" ">" (match-string 0)))))
9685 ((member complete-file '((4) (16)))
9686 ;; Completing read for file names.
9687 (setq link (org-file-complete-link complete-file)))
9689 ;; Read link, with completion for stored links.
9690 (org-link-fontify-links-to-this-file)
9691 (org-switch-to-buffer-other-window "*Org Links*")
9692 (with-current-buffer "*Org Links*"
9693 (erase-buffer)
9694 (insert "Insert a link.
9695 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9696 (when org-stored-links
9697 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9698 (insert (mapconcat 'org-link-prettify
9699 (reverse org-stored-links) "\n")))
9700 (goto-char (point-min)))
9701 (let ((cw (selected-window)))
9702 (select-window (get-buffer-window "*Org Links*" 'visible))
9703 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9704 (unless (pos-visible-in-window-p (point-max))
9705 (org-fit-window-to-buffer))
9706 (and (window-live-p cw) (select-window cw)))
9707 (setq all-prefixes (append (mapcar 'car abbrevs)
9708 (mapcar 'car org-link-abbrev-alist)
9709 (org-link-types)))
9710 (unwind-protect
9711 ;; Fake a link history, containing the stored links.
9712 (let ((org--links-history
9713 (append (mapcar #'car org-stored-links)
9714 org-insert-link-history)))
9715 (setq link
9716 (org-completing-read
9717 "Link: "
9718 (append
9719 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9720 (mapcar #'car org-stored-links))
9721 nil nil nil
9722 'org--links-history
9723 (caar org-stored-links)))
9724 (unless (org-string-nw-p link) (user-error "No link selected"))
9725 (dolist (l org-stored-links)
9726 (when (equal link (cadr l))
9727 (setq link (car l))
9728 (setq auto-desc t)))
9729 (when (or (member link all-prefixes)
9730 (and (equal ":" (substring link -1))
9731 (member (substring link 0 -1) all-prefixes)
9732 (setq link (substring link 0 -1))))
9733 (setq link (with-current-buffer origbuf
9734 (org-link-try-special-completion link)))))
9735 (set-window-configuration wcf)
9736 (kill-buffer "*Org Links*"))
9737 (setq entry (assoc link org-stored-links))
9738 (or entry (push link org-insert-link-history))
9739 (setq desc (or desc (nth 1 entry)))))
9741 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9742 (not org-keep-stored-link-after-insertion))
9743 (setq org-stored-links (delq (assoc link org-stored-links)
9744 org-stored-links)))
9746 (when (and (string-match org-plain-link-re link)
9747 (not (string-match org-ts-regexp link)))
9748 ;; URL-like link, normalize the use of angular brackets.
9749 (setq link (org-unbracket-string "<" ">" link)))
9751 ;; Check if we are linking to the current file with a search
9752 ;; option If yes, simplify the link by using only the search
9753 ;; option.
9754 (when (and buffer-file-name
9755 (let ((case-fold-search nil))
9756 (string-match "\\`file:\\(.+?\\)::" link)))
9757 (let ((path (match-string-no-properties 1 link))
9758 (search (substring-no-properties link (match-end 0))))
9759 (save-match-data
9760 (when (equal (file-truename buffer-file-name) (file-truename path))
9761 ;; We are linking to this same file, with a search option
9762 (setq link search)))))
9764 ;; Check if we can/should use a relative path. If yes, simplify
9765 ;; the link.
9766 (let ((case-fold-search nil))
9767 (when (string-match "\\`\\(file\\|docview\\):" link)
9768 (let* ((type (match-string-no-properties 0 link))
9769 (path-start (match-end 0))
9770 (search (and (string-match "::\\(.*\\)\\'" link)
9771 (match-string 1 link)))
9772 (path
9773 (if search
9774 (substring-no-properties
9775 link path-start (match-beginning 0))
9776 (substring-no-properties link (match-end 0))))
9777 (origpath path))
9778 (cond
9779 ((or (eq org-link-file-path-type 'absolute)
9780 (equal complete-file '(16)))
9781 (setq path (abbreviate-file-name (expand-file-name path))))
9782 ((eq org-link-file-path-type 'noabbrev)
9783 (setq path (expand-file-name path)))
9784 ((eq org-link-file-path-type 'relative)
9785 (setq path (file-relative-name path)))
9787 (save-match-data
9788 (if (string-match (concat "^" (regexp-quote
9789 (expand-file-name
9790 (file-name-as-directory
9791 default-directory))))
9792 (expand-file-name path))
9793 ;; We are linking a file with relative path name.
9794 (setq path (substring (expand-file-name path)
9795 (match-end 0)))
9796 (setq path (abbreviate-file-name (expand-file-name path)))))))
9797 (setq link (concat type path (and search (concat "::" search))))
9798 (when (equal desc origpath)
9799 (setq desc path)))))
9801 (unless auto-desc
9802 (let ((initial-input
9803 (cond
9804 (default-description)
9805 ((not org-make-link-description-function) desc)
9806 (t (condition-case nil
9807 (funcall org-make-link-description-function link desc)
9808 (error
9809 (message "Can't get link description from `%s'"
9810 (symbol-name org-make-link-description-function))
9811 (sit-for 2)
9812 nil))))))
9813 (setq desc (if (called-interactively-p 'any)
9814 (read-string "Description: " initial-input)
9815 initial-input))))
9817 (unless (string-match "\\S-" desc) (setq desc nil))
9818 (when remove (apply 'delete-region remove))
9819 (insert (org-make-link-string link desc))
9820 ;; Redisplay so as the new link has proper invisible characters.
9821 (sit-for 0)))
9823 (defun org-link-try-special-completion (type)
9824 "If there is completion support for link type TYPE, offer it."
9825 (let ((fun (org-link-get-parameter type :complete)))
9826 (if (functionp fun)
9827 (funcall fun)
9828 (read-string "Link (no completion support): " (concat type ":")))))
9830 (defun org-file-complete-link (&optional arg)
9831 "Create a file link using completion."
9832 (let ((file (read-file-name "File: "))
9833 (pwd (file-name-as-directory (expand-file-name ".")))
9834 (pwd1 (file-name-as-directory (abbreviate-file-name
9835 (expand-file-name ".")))))
9836 (cond ((equal arg '(16))
9837 (concat "file:"
9838 (abbreviate-file-name (expand-file-name file))))
9839 ((string-match
9840 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9841 (concat "file:" (match-string 1 file)))
9842 ((string-match
9843 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9844 (expand-file-name file))
9845 (concat "file:"
9846 (match-string 1 (expand-file-name file))))
9847 (t (concat "file:" file)))))
9850 ;;; Opening/following a link
9852 (defvar org-link-search-failed nil)
9854 (defvar org-open-link-functions nil
9855 "Hook for functions finding a plain text link.
9856 These functions must take a single argument, the link content.
9857 They will be called for links that look like [[link text][description]]
9858 when LINK TEXT does not have a protocol like \"http:\" and does not look
9859 like a filename (e.g. \"./blue.png\").
9861 These functions will be called *before* Org attempts to resolve the
9862 link by doing text searches in the current buffer - so if you want a
9863 link \"[[target]]\" to still find \"<<target>>\", your function should
9864 handle this as a special case.
9866 When the function does handle the link, it must return a non-nil value.
9867 If it decides that it is not responsible for this link, it must return
9868 nil to indicate that that Org can continue with other options like
9869 exact and fuzzy text search.")
9871 (defun org-next-link (&optional search-backward)
9872 "Move forward to the next link.
9873 If the link is in hidden text, expose it."
9874 (interactive "P")
9875 (when (and org-link-search-failed (eq this-command last-command))
9876 (goto-char (point-min))
9877 (message "Link search wrapped back to beginning of buffer"))
9878 (setq org-link-search-failed nil)
9879 (let* ((pos (point))
9880 (ct (org-context))
9881 (a (assq :link ct))
9882 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9883 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9884 ((looking-at org-any-link-re)
9885 ;; Don't stay stuck at link without an org-link face
9886 (forward-char (if search-backward -1 1))))
9887 (if (funcall srch-fun org-any-link-re nil t)
9888 (progn
9889 (goto-char (match-beginning 0))
9890 (when (org-invisible-p) (org-show-context)))
9891 (goto-char pos)
9892 (setq org-link-search-failed t)
9893 (message "No further link found"))))
9895 (defun org-previous-link ()
9896 "Move backward to the previous link.
9897 If the link is in hidden text, expose it."
9898 (interactive)
9899 (funcall 'org-next-link t))
9901 (defun org-translate-link (s)
9902 "Translate a link string if a translation function has been defined."
9903 (with-temp-buffer
9904 (insert (org-trim s))
9905 (org-trim (org-element-interpret-data (org-element-context)))))
9907 (defun org-translate-link-from-planner (type path)
9908 "Translate a link from Emacs Planner syntax so that Org can follow it.
9909 This is still an experimental function, your mileage may vary."
9910 (cond
9911 ((member type '("http" "https" "news" "ftp"))
9912 ;; standard Internet links are the same.
9913 nil)
9914 ((and (equal type "irc") (string-match "^//" path))
9915 ;; Planner has two / at the beginning of an irc link, we have 1.
9916 ;; We should have zero, actually....
9917 (setq path (substring path 1)))
9918 ((and (equal type "lisp") (string-match "^/" path))
9919 ;; Planner has a slash, we do not.
9920 (setq type "elisp" path (substring path 1)))
9921 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9922 ;; A typical message link. Planner has the id after the final slash,
9923 ;; we separate it with a hash mark
9924 (setq path (concat (match-string 1 path) "#"
9925 (org-unbracket-string "<" ">" (match-string 2 path))))))
9926 (cons type path))
9928 (defun org-find-file-at-mouse (ev)
9929 "Open file link or URL at mouse."
9930 (interactive "e")
9931 (mouse-set-point ev)
9932 (org-open-at-point 'in-emacs))
9934 (defun org-open-at-mouse (ev)
9935 "Open file link or URL at mouse.
9936 See the docstring of `org-open-file' for details."
9937 (interactive "e")
9938 (mouse-set-point ev)
9939 (when (eq major-mode 'org-agenda-mode)
9940 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9941 (org-open-at-point))
9943 (defvar org-window-config-before-follow-link nil
9944 "The window configuration before following a link.
9945 This is saved in case the need arises to restore it.")
9947 ;;;###autoload
9948 (defun org-open-at-point-global ()
9949 "Follow a link or time-stamp like Org mode does.
9950 This command can be called in any mode to follow an external link
9951 or a time-stamp that has Org mode syntax. Its behavior is
9952 undefined when called on internal links (e.g., fuzzy links).
9953 Raise an error when there is nothing to follow. "
9954 (interactive)
9955 (cond ((org-in-regexp org-any-link-re)
9956 (org-open-link-from-string (match-string-no-properties 0)))
9957 ((or (org-in-regexp org-ts-regexp-both nil t)
9958 (org-in-regexp org-tsr-regexp-both nil t))
9959 (org-follow-timestamp-link))
9960 (t (user-error "No link found"))))
9962 ;;;###autoload
9963 (defun org-open-link-from-string (s &optional arg reference-buffer)
9964 "Open a link in the string S, as if it was in Org mode."
9965 (interactive "sLink: \nP")
9966 (let ((reference-buffer (or reference-buffer (current-buffer))))
9967 (with-temp-buffer
9968 (let ((org-inhibit-startup (not reference-buffer)))
9969 (org-mode)
9970 (insert s)
9971 (goto-char (point-min))
9972 (when reference-buffer
9973 (setq org-link-abbrev-alist-local
9974 (with-current-buffer reference-buffer
9975 org-link-abbrev-alist-local)))
9976 (org-open-at-point arg reference-buffer)))))
9978 (defvar org-open-at-point-functions nil
9979 "Hook that is run when following a link at point.
9981 Functions in this hook must return t if they identify and follow
9982 a link at point. If they don't find anything interesting at point,
9983 they must return nil.")
9985 (defvar org-link-search-inhibit-query nil)
9986 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9987 (defun org--open-doi-link (path)
9988 "Open a \"doi\" type link.
9989 PATH is a the path to search for, as a string."
9990 (browse-url (url-encode-url (concat org-doi-server-url path))))
9992 (defun org--open-elisp-link (path)
9993 "Open a \"elisp\" type link.
9994 PATH is the sexp to evaluate, as a string."
9995 (let ((cmd path))
9996 (if (or (and (org-string-nw-p
9997 org-confirm-elisp-link-not-regexp)
9998 (string-match-p org-confirm-elisp-link-not-regexp cmd))
9999 (not org-confirm-elisp-link-function)
10000 (funcall org-confirm-elisp-link-function
10001 (format "Execute \"%s\" as elisp? "
10002 (org-add-props cmd nil 'face 'org-warning))))
10003 (message "%s => %s" cmd
10004 (if (eq (string-to-char cmd) ?\()
10005 (eval (read cmd))
10006 (call-interactively (read cmd))))
10007 (user-error "Abort"))))
10009 (defun org--open-help-link (path)
10010 "Open a \"help\" type link.
10011 PATH is a symbol name, as a string."
10012 (pcase (intern path)
10013 ((and (pred fboundp) variable) (describe-function variable))
10014 ((and (pred boundp) function) (describe-variable function))
10015 (name (user-error "Unknown function or variable: %s" name))))
10017 (defun org--open-shell-link (path)
10018 "Open a \"shell\" type link.
10019 PATH is the command to execute, as a string."
10020 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10021 (cmd path))
10022 (if (or (and (org-string-nw-p
10023 org-confirm-shell-link-not-regexp)
10024 (string-match
10025 org-confirm-shell-link-not-regexp cmd))
10026 (not org-confirm-shell-link-function)
10027 (funcall org-confirm-shell-link-function
10028 (format "Execute \"%s\" in shell? "
10029 (org-add-props cmd nil
10030 'face 'org-warning))))
10031 (progn
10032 (message "Executing %s" cmd)
10033 (shell-command cmd buf)
10034 (when (featurep 'midnight)
10035 (setq clean-buffer-list-kill-buffer-names
10036 (cons (buffer-name buf)
10037 clean-buffer-list-kill-buffer-names))))
10038 (user-error "Abort"))))
10040 (defun org-open-at-point (&optional arg reference-buffer)
10041 "Open link, timestamp, footnote or tags at point.
10043 When point is on a link, follow it. Normally, files will be
10044 opened by an appropriate application. If the optional prefix
10045 argument ARG is non-nil, Emacs will visit the file. With
10046 a double prefix argument, try to open outside of Emacs, in the
10047 application the system uses for this file type.
10049 When point is on a timestamp, open the agenda at the day
10050 specified.
10052 When point is a footnote definition, move to the first reference
10053 found. If it is on a reference, move to the associated
10054 definition.
10056 When point is on a headline, display a list of every link in the
10057 entry, so it is possible to pick one, or all, of them. If point
10058 is on a tag, call `org-tags-view' instead.
10060 When optional argument REFERENCE-BUFFER is non-nil, it should
10061 specify a buffer from where the link search should happen. This
10062 is used internally by `org-open-link-from-string'.
10064 On top of syntactically correct links, this function will also
10065 try to open links and time-stamps in comments, example
10066 blocks... i.e., whenever point is on something looking like
10067 a timestamp or a link."
10068 (interactive "P")
10069 ;; On a code block, open block's results.
10070 (unless (call-interactively 'org-babel-open-src-block-result)
10071 (org-load-modules-maybe)
10072 (setq org-window-config-before-follow-link (current-window-configuration))
10073 (org-remove-occur-highlights nil nil t)
10074 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10075 (let* ((context
10076 ;; Only consider supported types, even if they are not
10077 ;; the closest one.
10078 (org-element-lineage
10079 (org-element-context)
10080 '(clock footnote-definition footnote-reference headline
10081 inlinetask link timestamp)
10083 (type (org-element-type context))
10084 (value (org-element-property :value context)))
10085 (cond
10086 ;; On a headline or an inlinetask, but not on a timestamp,
10087 ;; a link, a footnote reference.
10088 ((memq type '(headline inlinetask))
10089 (org-match-line org-complex-heading-regexp)
10090 (if (and (match-beginning 5)
10091 (>= (point) (match-beginning 5))
10092 (< (point) (match-end 5)))
10093 ;; On tags.
10094 (org-tags-view arg (substring (match-string 5) 0 -1))
10095 ;; Not on tags.
10096 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10097 (`(nil . ,_)
10098 (require 'org-attach)
10099 (org-attach-reveal 'if-exists))
10100 (`(,links . ,links-end)
10101 (dolist (link (if (stringp links) (list links) links))
10102 (search-forward link nil links-end)
10103 (goto-char (match-beginning 0))
10104 (org-open-at-point))))))
10105 ;; On a footnote reference or at definition's label.
10106 ((or (eq type 'footnote-reference)
10107 (and (eq type 'footnote-definition)
10108 (save-excursion
10109 ;; Do not validate action when point is on the
10110 ;; spaces right after the footnote label, in
10111 ;; order to be on par with behavior on links.
10112 (skip-chars-forward " \t")
10113 (let ((begin
10114 (org-element-property :contents-begin context)))
10115 (if begin (< (point) begin)
10116 (= (org-element-property :post-affiliated context)
10117 (line-beginning-position)))))))
10118 (org-footnote-action))
10119 ;; No valid context. Ignore catch-all types like `headline'.
10120 ;; If point is on something looking like a link or
10121 ;; a time-stamp, try opening it. It may be useful in
10122 ;; comments, example blocks...
10123 ((memq type '(footnote-definition headline inlinetask nil))
10124 (call-interactively #'org-open-at-point-global))
10125 ;; On a clock line, make sure point is on the timestamp
10126 ;; before opening it.
10127 ((and (eq type 'clock)
10128 value
10129 (>= (point) (org-element-property :begin value))
10130 (<= (point) (org-element-property :end value)))
10131 (org-follow-timestamp-link))
10132 ;; Do nothing on white spaces after an object.
10133 ((>= (point)
10134 (save-excursion
10135 (goto-char (org-element-property :end context))
10136 (skip-chars-backward " \t")
10137 (point)))
10138 (user-error "No link found"))
10139 ((eq type 'timestamp) (org-follow-timestamp-link))
10140 ((eq type 'link)
10141 (let ((type (org-element-property :type context))
10142 (path (org-link-unescape (org-element-property :path context))))
10143 ;; Switch back to REFERENCE-BUFFER needed when called in
10144 ;; a temporary buffer through `org-open-link-from-string'.
10145 (with-current-buffer (or reference-buffer (current-buffer))
10146 (cond
10147 ((equal type "file")
10148 (if (string-match "[*?{]" (file-name-nondirectory path))
10149 (dired path)
10150 ;; Look into `org-link-parameters' in order to find
10151 ;; a DEDICATED-FUNCTION to open file. The function
10152 ;; will be applied on raw link instead of parsed
10153 ;; link due to the limitation in `org-add-link-type'
10154 ;; ("open" function called with a single argument).
10155 ;; If no such function is found, fallback to
10156 ;; `org-open-file'.
10157 (let* ((option (org-element-property :search-option context))
10158 (app (org-element-property :application context))
10159 (dedicated-function
10160 (org-link-get-parameter
10161 (if app (concat type "+" app) type)
10162 :follow)))
10163 (if dedicated-function
10164 (funcall dedicated-function
10165 (concat path
10166 (and option (concat "::" option))))
10167 (apply #'org-open-file
10168 path
10169 (cond (arg)
10170 ((equal app "emacs") 'emacs)
10171 ((equal app "sys") 'system))
10172 (cond ((not option) nil)
10173 ((string-match-p "\\`[0-9]+\\'" option)
10174 (list (string-to-number option)))
10175 (t (list nil
10176 (org-link-unescape option)))))))))
10177 ((functionp (org-link-get-parameter type :follow))
10178 (funcall (org-link-get-parameter type :follow) path))
10179 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10180 (unless (run-hook-with-args-until-success
10181 'org-open-link-functions path)
10182 (if (not arg) (org-mark-ring-push)
10183 (switch-to-buffer-other-window
10184 (org-get-buffer-for-internal-link (current-buffer))))
10185 (let ((destination
10186 (org-with-wide-buffer
10187 (if (equal type "radio")
10188 (org-search-radio-target
10189 (org-element-property :path context))
10190 (org-link-search
10191 (if (member type '("custom-id" "coderef"))
10192 (org-element-property :raw-link context)
10193 path)
10194 ;; Prevent fuzzy links from matching
10195 ;; themselves.
10196 (and (equal type "fuzzy")
10197 (+ 2 (org-element-property :begin context)))))
10198 (point))))
10199 (unless (and (<= (point-min) destination)
10200 (>= (point-max) destination))
10201 (widen))
10202 (goto-char destination))))
10203 (t (browse-url-at-point))))))
10204 (t (user-error "No link found")))))
10205 (run-hook-with-args 'org-follow-link-hook)))
10207 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10208 "Offer links in the current entry and return the selected link.
10209 If there is only one link, return it.
10210 If NTH is an integer, return the NTH link found.
10211 If ZERO is a string, check also this string for a link, and if
10212 there is one, return it."
10213 (with-current-buffer buffer
10214 (org-with-wide-buffer
10215 (goto-char marker)
10216 (let ((cnt ?0)
10217 have-zero end links link c)
10218 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10219 (push (match-string 0 zero) links)
10220 (setq cnt (1- cnt) have-zero t))
10221 (save-excursion
10222 (org-back-to-heading t)
10223 (setq end (save-excursion (outline-next-heading) (point)))
10224 (while (re-search-forward org-any-link-re end t)
10225 (push (match-string 0) links))
10226 (setq links (org-uniquify (reverse links))))
10227 (cond
10228 ((null links)
10229 (message "No links"))
10230 ((equal (length links) 1)
10231 (setq link (car links)))
10232 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10233 (setq link (nth (if have-zero nth (1- nth)) links)))
10234 (t ; we have to select a link
10235 (save-excursion
10236 (save-window-excursion
10237 (delete-other-windows)
10238 (with-output-to-temp-buffer "*Select Link*"
10239 (dolist (l links)
10240 (cond
10241 ((not (string-match org-bracket-link-regexp l))
10242 (princ (format "[%c] %s\n" (cl-incf cnt)
10243 (org-unbracket-string "<" ">" l))))
10244 ((match-end 3)
10245 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10246 (match-string 3 l) (match-string 1 l))))
10247 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10248 (match-string 1 l)))))))
10249 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10250 (message "Select link to open, RET to open all:")
10251 (setq c (read-char-exclusive))
10252 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10253 (when (equal c ?q) (user-error "Abort"))
10254 (if (equal c ?\C-m)
10255 (setq link links)
10256 (setq nth (- c ?0))
10257 (when have-zero (setq nth (1+ nth)))
10258 (unless (and (integerp nth) (>= (length links) nth))
10259 (user-error "Invalid link selection"))
10260 (setq link (nth (1- nth) links)))))
10261 (cons link end)))))
10263 ;; TODO: These functions are deprecated since `org-open-at-point'
10264 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10265 (defun org-open-file-with-system (path)
10266 "Open file at PATH using the system way of opening it."
10267 (org-open-file path 'system))
10268 (defun org-open-file-with-emacs (path)
10269 "Open file at PATH in Emacs."
10270 (org-open-file path 'emacs))
10273 ;;; File search
10275 (defvar org-create-file-search-functions nil
10276 "List of functions to construct the right search string for a file link.
10277 These functions are called in turn with point at the location to
10278 which the link should point.
10280 A function in the hook should first test if it would like to
10281 handle this file type, for example by checking the `major-mode'
10282 or the file extension. If it decides not to handle this file, it
10283 should just return nil to give other functions a chance. If it
10284 does handle the file, it must return the search string to be used
10285 when following the link. The search string will be part of the
10286 file link, given after a double colon, and `org-open-at-point'
10287 will automatically search for it. If special measures must be
10288 taken to make the search successful, another function should be
10289 added to the companion hook `org-execute-file-search-functions',
10290 which see.
10292 A function in this hook may also use `setq' to set the variable
10293 `description' to provide a suggestion for the descriptive text to
10294 be used for this link when it gets inserted into an Org buffer
10295 with \\[org-insert-link].")
10297 (defvar org-execute-file-search-functions nil
10298 "List of functions to execute a file search triggered by a link.
10300 Functions added to this hook must accept a single argument, the
10301 search string that was part of the file link, the part after the
10302 double colon. The function must first check if it would like to
10303 handle this search, for example by checking the `major-mode' or
10304 the file extension. If it decides not to handle this search, it
10305 should just return nil to give other functions a chance. If it
10306 does handle the search, it must return a non-nil value to keep
10307 other functions from trying.
10309 Each function can access the current prefix argument through the
10310 variable `current-prefix-arg'. Note that a single prefix is used
10311 to force opening a link in Emacs, so it may be good to only use a
10312 numeric or double prefix to guide the search function.
10314 In case this is needed, a function in this hook can also restore
10315 the window configuration before `org-open-at-point' was called using:
10317 (set-window-configuration org-window-config-before-follow-link)")
10319 (defun org-search-radio-target (target)
10320 "Search a radio target matching TARGET in current buffer.
10321 White spaces are not significant."
10322 (let ((re (format "<<<%s>>>"
10323 (mapconcat #'regexp-quote
10324 (split-string target)
10325 "[ \t]+\\(?:\n[ \t]*\\)?")))
10326 (origin (point)))
10327 (goto-char (point-min))
10328 (catch :radio-match
10329 (while (re-search-forward re nil t)
10330 (backward-char)
10331 (let ((object (org-element-context)))
10332 (when (eq (org-element-type object) 'radio-target)
10333 (goto-char (org-element-property :begin object))
10334 (org-show-context 'link-search)
10335 (throw :radio-match nil))))
10336 (goto-char origin)
10337 (user-error "No match for radio target: %s" target))))
10339 (defun org-link-search (s &optional avoid-pos stealth)
10340 "Search for a search string S.
10342 If S starts with \"#\", it triggers a custom ID search.
10344 If S is enclosed within parenthesis, it initiates a coderef
10345 search.
10347 If S is surrounded by forward slashes, it is interpreted as
10348 a regular expression. In Org mode files, this will create an
10349 `org-occur' sparse tree. In ordinary files, `occur' will be used
10350 to list matches. If the current buffer is in `dired-mode', grep
10351 will be used to search in all files.
10353 When AVOID-POS is given, ignore matches near that position.
10355 When optional argument STEALTH is non-nil, do not modify
10356 visibility around point, thus ignoring `org-show-context-detail'
10357 variable.
10359 Search is case-insensitive and ignores white spaces. Return type
10360 of matched result, which is either `dedicated' or `fuzzy'."
10361 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10362 (let* ((case-fold-search t)
10363 (origin (point))
10364 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10365 (starred (eq (string-to-char normalized) ?*))
10366 (words (split-string (if starred (substring s 1) s)))
10367 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10368 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10369 type)
10370 (cond
10371 ;; Check if there are any special search functions.
10372 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10373 ((eq (string-to-char s) ?#)
10374 ;; Look for a custom ID S if S starts with "#".
10375 (let* ((id (substring normalized 1))
10376 (match (org-find-property "CUSTOM_ID" id)))
10377 (if match (progn (goto-char match) (setf type 'dedicated))
10378 (error "No match for custom ID: %s" id))))
10379 ((string-match "\\`(\\(.*\\))\\'" normalized)
10380 ;; Look for coderef targets if S is enclosed within parenthesis.
10381 (let ((coderef (match-string-no-properties 1 normalized))
10382 (re (substring s-single-re 1 -1)))
10383 (goto-char (point-min))
10384 (catch :coderef-match
10385 (while (re-search-forward re nil t)
10386 (let ((element (org-element-at-point)))
10387 (when (and (memq (org-element-type element)
10388 '(example-block src-block))
10389 ;; Build proper regexp according to current
10390 ;; block's label format.
10391 (let ((label-fmt
10392 (regexp-quote
10393 (or (org-element-property :label-fmt element)
10394 org-coderef-label-format))))
10395 (save-excursion
10396 (beginning-of-line)
10397 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10398 (format label-fmt coderef))))))
10399 (setq type 'dedicated)
10400 (goto-char (match-beginning 1))
10401 (throw :coderef-match nil))))
10402 (goto-char origin)
10403 (error "No match for coderef: %s" coderef))))
10404 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10405 ;; Look for a regular expression.
10406 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10407 (match-string 1 s)))
10408 ;; From here, we handle fuzzy links.
10410 ;; Look for targets, only if not in a headline search.
10411 ((and (not starred)
10412 (let ((target (format "<<%s>>" s-multi-re)))
10413 (catch :target-match
10414 (goto-char (point-min))
10415 (while (re-search-forward target nil t)
10416 (backward-char)
10417 (let ((context (org-element-context)))
10418 (when (eq (org-element-type context) 'target)
10419 (setq type 'dedicated)
10420 (goto-char (org-element-property :begin context))
10421 (throw :target-match t))))
10422 nil))))
10423 ;; Look for elements named after S, only if not in a headline
10424 ;; search.
10425 ((and (not starred)
10426 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10427 (catch :name-match
10428 (goto-char (point-min))
10429 (while (re-search-forward name nil t)
10430 (let ((element (org-element-at-point)))
10431 (when (equal words
10432 (split-string
10433 (org-element-property :name element)))
10434 (setq type 'dedicated)
10435 (beginning-of-line)
10436 (throw :name-match t))))
10437 nil))))
10438 ;; Regular text search. Prefer headlines in Org mode buffers.
10439 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10440 ;; statistics cookies and tags.
10441 ((and (derived-mode-p 'org-mode)
10442 (let ((title-re
10443 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10444 org-outline-regexp-bol
10445 org-comment-string
10446 (mapconcat #'regexp-quote words ".+")))
10447 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10448 (comment-re (eval-when-compile
10449 (format "\\`%s[ \t]+" org-comment-string))))
10450 (goto-char (point-min))
10451 (catch :found
10452 (while (re-search-forward title-re nil t)
10453 (when (equal words
10454 (split-string
10455 (replace-regexp-in-string
10456 cookie-re ""
10457 (replace-regexp-in-string
10458 comment-re "" (org-get-heading t t t)))))
10459 (throw :found t)))
10460 nil)))
10461 (beginning-of-line)
10462 (setq type 'dedicated))
10463 ;; Offer to create non-existent headline depending on
10464 ;; `org-link-search-must-match-exact-headline'.
10465 ((and (derived-mode-p 'org-mode)
10466 (not org-link-search-inhibit-query)
10467 (eq org-link-search-must-match-exact-headline 'query-to-create)
10468 (yes-or-no-p "No match - create this as a new heading? "))
10469 (goto-char (point-max))
10470 (unless (bolp) (newline))
10471 (org-insert-heading nil t t)
10472 (insert s "\n")
10473 (beginning-of-line 0))
10474 ;; Only headlines are looked after. No need to process
10475 ;; further: throw an error.
10476 ((and (derived-mode-p 'org-mode)
10477 (or starred org-link-search-must-match-exact-headline))
10478 (goto-char origin)
10479 (error "No match for fuzzy expression: %s" normalized))
10480 ;; Regular text search.
10481 ((catch :fuzzy-match
10482 (goto-char (point-min))
10483 (while (re-search-forward s-multi-re nil t)
10484 ;; Skip match if it contains AVOID-POS or it is included in
10485 ;; a link with a description but outside the description.
10486 (unless (or (and avoid-pos
10487 (<= (match-beginning 0) avoid-pos)
10488 (> (match-end 0) avoid-pos))
10489 (and (save-match-data
10490 (org-in-regexp org-bracket-link-regexp))
10491 (match-beginning 3)
10492 (or (> (match-beginning 3) (point))
10493 (<= (match-end 3) (point)))
10494 (org-element-lineage
10495 (save-match-data (org-element-context))
10496 '(link) t)))
10497 (goto-char (match-beginning 0))
10498 (setq type 'fuzzy)
10499 (throw :fuzzy-match t)))
10500 nil))
10501 ;; All failed. Throw an error.
10502 (t (goto-char origin)
10503 (error "No match for fuzzy expression: %s" normalized)))
10504 ;; Disclose surroundings of match, if appropriate.
10505 (when (and (derived-mode-p 'org-mode) (not stealth))
10506 (org-show-context 'link-search))
10507 type))
10509 (defun org-get-buffer-for-internal-link (buffer)
10510 "Return a buffer to be used for displaying the link target of internal links."
10511 (cond
10512 ((not org-display-internal-link-with-indirect-buffer)
10513 buffer)
10514 ((string-suffix-p "(Clone)" (buffer-name buffer))
10515 (message "Buffer is already a clone, not making another one")
10516 ;; we also do not modify visibility in this case
10517 buffer)
10518 (t ; make a new indirect buffer for displaying the link
10519 (let* ((bn (buffer-name buffer))
10520 (ibn (concat bn "(Clone)"))
10521 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10522 (with-current-buffer ib (org-overview))
10523 ib))))
10525 (defun org-do-occur (regexp &optional cleanup)
10526 "Call the Emacs command `occur'.
10527 If CLEANUP is non-nil, remove the printout of the regular expression
10528 in the *Occur* buffer. This is useful if the regex is long and not useful
10529 to read."
10530 (occur regexp)
10531 (when cleanup
10532 (let ((cwin (selected-window)) win beg end)
10533 (when (setq win (get-buffer-window "*Occur*"))
10534 (select-window win))
10535 (goto-char (point-min))
10536 (when (re-search-forward "match[a-z]+" nil t)
10537 (setq beg (match-end 0))
10538 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10539 (setq end (1- (match-beginning 0)))))
10540 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10541 (goto-char (point-min))
10542 (select-window cwin))))
10545 ;;; The Mark Ring
10547 (defvar org-mark-ring nil
10548 "Mark ring for positions before jumps in Org mode.")
10550 (defvar org-mark-ring-last-goto nil
10551 "Last position in the mark ring used to go back.")
10553 ;; Fill and close the ring
10554 (setq org-mark-ring nil)
10555 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10557 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10558 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10559 org-mark-ring)
10561 (defun org-mark-ring-push (&optional pos buffer)
10562 "Put the current position into the mark ring and rotate it.
10563 Also push position into the Emacs mark ring. If optional
10564 argument POS and BUFFER are not nil, mark this location instead."
10565 (interactive)
10566 (let ((pos (or pos (point)))
10567 (buffer (or buffer (current-buffer))))
10568 (with-current-buffer buffer
10569 (org-with-point-at pos (push-mark nil t)))
10570 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10571 (move-marker (car org-mark-ring) pos buffer))
10572 (message
10573 (substitute-command-keys
10574 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10576 (defun org-mark-ring-goto (&optional n)
10577 "Jump to the previous position in the mark ring.
10578 With prefix arg N, jump back that many stored positions. When
10579 called several times in succession, walk through the entire ring.
10580 Org mode commands jumping to a different position in the current file,
10581 or to another Org file, automatically push the old position onto the ring."
10582 (interactive "p")
10583 (let (p m)
10584 (if (eq last-command this-command)
10585 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10586 (setq p org-mark-ring))
10587 (setq org-mark-ring-last-goto p)
10588 (setq m (car p))
10589 (pop-to-buffer-same-window (marker-buffer m))
10590 (goto-char m)
10591 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10593 (defun org-add-angle-brackets (s)
10594 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10595 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10598 ;;; Following specific links
10600 (defvar org-agenda-buffer-tmp-name)
10601 (defvar org-agenda-start-on-weekday)
10602 (defun org-follow-timestamp-link ()
10603 "Open an agenda view for the time-stamp date/range at point."
10604 (cond
10605 ((org-at-date-range-p t)
10606 (let ((org-agenda-start-on-weekday)
10607 (t1 (match-string 1))
10608 (t2 (match-string 2)) tt1 tt2)
10609 (setq tt1 (time-to-days (org-time-string-to-time t1))
10610 tt2 (time-to-days (org-time-string-to-time t2)))
10611 (let ((org-agenda-buffer-tmp-name
10612 (format "*Org Agenda(a:%s)"
10613 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10614 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10615 ((org-at-timestamp-p 'lax)
10616 (let ((org-agenda-buffer-tmp-name
10617 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10618 (org-agenda-list nil (time-to-days (org-time-string-to-time
10619 (substring (match-string 1) 0 10)))
10620 1)))
10621 (t (error "This should not happen"))))
10624 ;;; Following file links
10625 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10626 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10627 (declare-function mailcap-mime-info
10628 "mailcap" (string &optional request no-decode))
10629 (defvar org-wait nil)
10630 (defun org-open-file (path &optional in-emacs line search)
10631 "Open the file at PATH.
10632 First, this expands any special file name abbreviations. Then the
10633 configuration variable `org-file-apps' is checked if it contains an
10634 entry for this file type, and if yes, the corresponding command is launched.
10636 If no application is found, Emacs simply visits the file.
10638 With optional prefix argument IN-EMACS, Emacs will visit the file.
10639 With a double \\[universal-argument] \\[universal-argument] \
10640 prefix arg, Org tries to avoid opening in Emacs
10641 and to use an external application to visit the file.
10643 Optional LINE specifies a line to go to, optional SEARCH a string
10644 to search for. If LINE or SEARCH is given, the file will be
10645 opened in Emacs, unless an entry from org-file-apps that makes
10646 use of groups in a regexp matches.
10648 If you want to change the way frames are used when following a
10649 link, please customize `org-link-frame-setup'.
10651 If the file does not exist, an error is thrown."
10652 (let* ((file (if (equal path "")
10653 buffer-file-name
10654 (substitute-in-file-name (expand-file-name path))))
10655 (file-apps (append org-file-apps (org-default-apps)))
10656 (apps (cl-remove-if
10657 'org-file-apps-entry-match-against-dlink-p file-apps))
10658 (apps-dlink (cl-remove-if-not
10659 'org-file-apps-entry-match-against-dlink-p file-apps))
10660 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10661 (dirp (unless remp (file-directory-p file)))
10662 (file (if (and dirp org-open-directory-means-index-dot-org)
10663 (concat (file-name-as-directory file) "index.org")
10664 file))
10665 (a-m-a-p (assq 'auto-mode apps))
10666 (dfile (downcase file))
10667 ;; Reconstruct the original link from the PATH, LINE and
10668 ;; SEARCH args.
10669 (link (cond (line (concat file "::" (number-to-string line)))
10670 (search (concat file "::" search))
10671 (t file)))
10672 (dlink (downcase link))
10673 (ext
10674 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10675 (match-string 1 dfile)))
10676 (save-position-maybe
10677 (let ((old-buffer (current-buffer))
10678 (old-pos (point))
10679 (old-mode major-mode))
10680 (lambda ()
10681 (and (derived-mode-p 'org-mode)
10682 (eq old-mode 'org-mode)
10683 (or (not (eq old-buffer (current-buffer)))
10684 (not (eq old-pos (point))))
10685 (org-mark-ring-push old-pos old-buffer)))))
10686 cmd link-match-data)
10687 (cond
10688 ((member in-emacs '((16) system))
10689 (setq cmd (cdr (assq 'system apps))))
10690 (in-emacs (setq cmd 'emacs))
10692 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10693 (and dirp (cdr (assq 'directory apps)))
10694 ;; First, try matching against apps-dlink if we
10695 ;; get a match here, store the match data for
10696 ;; later.
10697 (let ((match (assoc-default dlink apps-dlink
10698 'string-match)))
10699 (if match
10700 (progn (setq link-match-data (match-data))
10701 match)
10702 (progn (setq in-emacs (or in-emacs line search))
10703 nil))) ; if we have no match in apps-dlink,
10704 ; always open the file in emacs if line or search
10705 ; is given (for backwards compatibility)
10706 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10707 'string-match)
10708 (cdr (assoc ext apps))
10709 (cdr (assq t apps))))))
10710 (when (eq cmd 'system)
10711 (setq cmd (cdr (assq 'system apps))))
10712 (when (eq cmd 'default)
10713 (setq cmd (cdr (assoc t apps))))
10714 (when (eq cmd 'mailcap)
10715 (require 'mailcap)
10716 (mailcap-parse-mailcaps)
10717 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10718 (command (mailcap-mime-info mime-type)))
10719 (if (stringp command)
10720 (setq cmd command)
10721 (setq cmd 'emacs))))
10722 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10723 (not (file-exists-p file))
10724 (not org-open-non-existing-files))
10725 (user-error "No such file: %s" file))
10726 (cond
10727 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10728 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10729 (while (string-match "['\"]%s['\"]" cmd)
10730 (setq cmd (replace-match "%s" t t cmd)))
10731 (setq cmd (replace-regexp-in-string
10732 "%s"
10733 (shell-quote-argument (convert-standard-filename file))
10735 nil t))
10737 ;; Replace "%1", "%2" etc. in command with group matches from regex
10738 (save-match-data
10739 (let ((match-index 1)
10740 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10741 (set-match-data link-match-data)
10742 (while (<= match-index number-of-groups)
10743 (let ((regex (concat "%" (number-to-string match-index)))
10744 (replace-with (match-string match-index dlink)))
10745 (while (string-match regex cmd)
10746 (setq cmd (replace-match replace-with t t cmd))))
10747 (setq match-index (+ match-index 1)))))
10749 (save-window-excursion
10750 (message "Running %s...done" cmd)
10751 (start-process-shell-command cmd nil cmd)
10752 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10753 ((or (stringp cmd)
10754 (eq cmd 'emacs))
10755 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10756 (widen)
10757 (cond (line (org-goto-line line)
10758 (when (derived-mode-p 'org-mode) (org-reveal)))
10759 (search (condition-case err
10760 (org-link-search search)
10761 ;; Save position before error-ing out so user
10762 ;; can easily move back to the original buffer.
10763 (error (funcall save-position-maybe)
10764 (error (nth 1 err)))))))
10765 ((functionp cmd)
10766 (save-match-data
10767 (set-match-data link-match-data)
10768 (condition-case nil
10769 (funcall cmd file link)
10770 ;; FIXME: Remove this check when most default installations
10771 ;; of Emacs have at least Org 9.0.
10772 ((debug wrong-number-of-arguments wrong-type-argument
10773 invalid-function)
10774 (user-error "Please see Org News for version 9.0 about \
10775 `org-file-apps'--Lisp error: %S" cmd)))))
10776 ((consp cmd)
10777 ;; FIXME: Remove this check when most default installations of
10778 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10779 ;; fall back to `org-link-frame-setup' for an old usage of
10780 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10781 (user-error "Please see Org News for version 9.0 about \
10782 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10783 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10784 (funcall save-position-maybe)))
10786 (defun org-file-apps-entry-match-against-dlink-p (entry)
10787 "This function returns non-nil if `entry' uses a regular
10788 expression which should be matched against the whole link by
10789 org-open-file.
10791 It assumes that is the case when the entry uses a regular
10792 expression which has at least one grouping construct and the
10793 action is either a lisp form or a command string containing
10794 `%1', i.e. using at least one subexpression match as a
10795 parameter."
10796 (let ((selector (car entry))
10797 (action (cdr entry)))
10798 (if (stringp selector)
10799 (and (> (regexp-opt-depth selector) 0)
10800 (or (and (stringp action)
10801 (string-match "%[0-9]" action))
10802 (consp action)))
10803 nil)))
10805 (defun org-default-apps ()
10806 "Return the default applications for this operating system."
10807 (cond
10808 ((eq system-type 'darwin)
10809 org-file-apps-defaults-macosx)
10810 ((eq system-type 'windows-nt)
10811 org-file-apps-defaults-windowsnt)
10812 (t org-file-apps-defaults-gnu)))
10814 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10815 "Convert extensions to regular expressions in the cars of LIST.
10816 Also, weed out any non-string entries, because the return value is used
10817 only for regexp matching.
10818 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10819 point to the symbol `emacs', indicating that the file should
10820 be opened in Emacs."
10821 (append
10822 (delq nil
10823 (mapcar (lambda (x)
10824 (unless (not (stringp (car x)))
10825 (if (string-match "\\W" (car x))
10827 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10828 list))
10829 (when add-auto-mode
10830 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10832 (defvar ange-ftp-name-format)
10833 (defun org-file-remote-p (file)
10834 "Test whether FILE specifies a location on a remote system.
10835 Return non-nil if the location is indeed remote.
10837 For example, the filename \"/user@host:/foo\" specifies a location
10838 on the system \"/user@host:\"."
10839 (cond ((fboundp 'file-remote-p)
10840 (file-remote-p file))
10841 ((fboundp 'tramp-handle-file-remote-p)
10842 (tramp-handle-file-remote-p file))
10843 ((and (boundp 'ange-ftp-name-format)
10844 (string-match (car ange-ftp-name-format) file))
10845 t)))
10848 ;;;; Refiling
10850 (defun org-get-org-file ()
10851 "Read a filename, with default directory `org-directory'."
10852 (let ((default (or org-default-notes-file remember-data-file)))
10853 (read-file-name (format "File name [%s]: " default)
10854 (file-name-as-directory org-directory)
10855 default)))
10857 (defun org-notes-order-reversed-p ()
10858 "Check if the current file should receive notes in reversed order."
10859 (cond
10860 ((not org-reverse-note-order) nil)
10861 ((eq t org-reverse-note-order) t)
10862 ((not (listp org-reverse-note-order)) nil)
10863 (t (catch 'exit
10864 (dolist (entry org-reverse-note-order)
10865 (when (string-match (car entry) buffer-file-name)
10866 (throw 'exit (cdr entry))))))))
10868 (defvar org-refile-target-table nil
10869 "The list of refile targets, created by `org-refile'.")
10871 (defvar org-agenda-new-buffers nil
10872 "Buffers created to visit agenda files.")
10874 (defvar org-refile-cache nil
10875 "Cache for refile targets.")
10877 (defvar org-refile-markers nil
10878 "All the markers used for caching refile locations.")
10880 (defun org-refile-marker (pos)
10881 "Get a new refile marker, but only if caching is in use."
10882 (if (not org-refile-use-cache)
10884 (let ((m (make-marker)))
10885 (move-marker m pos)
10886 (push m org-refile-markers)
10887 m)))
10889 (defun org-refile-cache-clear ()
10890 "Clear the refile cache and disable all the markers."
10891 (dolist (m org-refile-markers) (move-marker m nil))
10892 (setq org-refile-markers nil)
10893 (setq org-refile-cache nil)
10894 (message "Refile cache has been cleared"))
10896 (defun org-refile-cache-check-set (set)
10897 "Check if all the markers in the cache still have live buffers."
10898 (let (marker)
10899 (catch 'exit
10900 (while (and set (setq marker (nth 3 (pop set))))
10901 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10902 (when (and marker (null (marker-buffer marker)))
10903 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10904 (sit-for 3)
10905 (throw 'exit nil)))
10906 t)))
10908 (defun org-refile-cache-put (set &rest identifiers)
10909 "Push the refile targets SET into the cache, under IDENTIFIERS."
10910 (let* ((key (sha1 (prin1-to-string identifiers)))
10911 (entry (assoc key org-refile-cache)))
10912 (if entry
10913 (setcdr entry set)
10914 (push (cons key set) org-refile-cache))))
10916 (defun org-refile-cache-get (&rest identifiers)
10917 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10918 (cond
10919 ((not org-refile-cache) nil)
10920 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10922 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10923 org-refile-cache))))
10924 (and set (org-refile-cache-check-set set) set)))))
10926 (defvar org-outline-path-cache nil
10927 "Alist between buffer positions and outline paths.
10928 It value is an alist (POSITION . PATH) where POSITION is the
10929 buffer position at the beginning of an entry and PATH is a list
10930 of strings describing the outline path for that entry, in reverse
10931 order.")
10933 (defun org-refile-get-targets (&optional default-buffer)
10934 "Produce a table with refile targets."
10935 (let ((case-fold-search nil)
10936 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10937 (entries (or org-refile-targets '((nil . (:level . 1)))))
10938 targets tgs files desc descre)
10939 (message "Getting targets...")
10940 (with-current-buffer (or default-buffer (current-buffer))
10941 (dolist (entry entries)
10942 (setq files (car entry) desc (cdr entry))
10943 (cond
10944 ((null files) (setq files (list (current-buffer))))
10945 ((eq files 'org-agenda-files)
10946 (setq files (org-agenda-files 'unrestricted)))
10947 ((and (symbolp files) (fboundp files))
10948 (setq files (funcall files)))
10949 ((and (symbolp files) (boundp files))
10950 (setq files (symbol-value files))))
10951 (when (stringp files) (setq files (list files)))
10952 (cond
10953 ((eq (car desc) :tag)
10954 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10955 ((eq (car desc) :todo)
10956 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10957 ((eq (car desc) :regexp)
10958 (setq descre (cdr desc)))
10959 ((eq (car desc) :level)
10960 (setq descre (concat "^\\*\\{" (number-to-string
10961 (if org-odd-levels-only
10962 (1- (* 2 (cdr desc)))
10963 (cdr desc)))
10964 "\\}[ \t]")))
10965 ((eq (car desc) :maxlevel)
10966 (setq descre (concat "^\\*\\{1," (number-to-string
10967 (if org-odd-levels-only
10968 (1- (* 2 (cdr desc)))
10969 (cdr desc)))
10970 "\\}[ \t]")))
10971 (t (error "Bad refiling target description %s" desc)))
10972 (dolist (f files)
10973 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10975 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10976 (progn
10977 (when (bufferp f)
10978 (setq f (buffer-file-name (buffer-base-buffer f))))
10979 (setq f (and f (expand-file-name f)))
10980 (when (eq org-refile-use-outline-path 'file)
10981 (push (list (file-name-nondirectory f) f nil nil) tgs))
10982 (when (eq org-refile-use-outline-path 'buffer-name)
10983 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10984 (when (eq org-refile-use-outline-path 'full-file-path)
10985 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10986 (org-with-wide-buffer
10987 (goto-char (point-min))
10988 (setq org-outline-path-cache nil)
10989 (while (re-search-forward descre nil t)
10990 (beginning-of-line)
10991 (let ((case-fold-search nil))
10992 (looking-at org-complex-heading-regexp))
10993 (let ((begin (point))
10994 (heading (match-string-no-properties 4)))
10995 (unless (or (and
10996 org-refile-target-verify-function
10997 (not
10998 (funcall org-refile-target-verify-function)))
10999 (not heading))
11000 (let ((re (format org-complex-heading-regexp-format
11001 (regexp-quote heading)))
11002 (target
11003 (if (not org-refile-use-outline-path) heading
11004 (mapconcat
11005 #'identity
11006 (append
11007 (pcase org-refile-use-outline-path
11008 (`file (list (file-name-nondirectory
11009 (buffer-file-name
11010 (buffer-base-buffer)))))
11011 (`full-file-path
11012 (list (buffer-file-name
11013 (buffer-base-buffer))))
11014 (`buffer-name
11015 (list (buffer-name
11016 (buffer-base-buffer))))
11017 (_ nil))
11018 (mapcar (lambda (s) (replace-regexp-in-string
11019 "/" "\\/" s nil t))
11020 (org-get-outline-path t t)))
11021 "/"))))
11022 (push (list target f re (org-refile-marker (point)))
11023 tgs)))
11024 (when (= (point) begin)
11025 ;; Verification function has not moved point.
11026 (end-of-line)))))))
11027 (when org-refile-use-cache
11028 (org-refile-cache-put tgs (buffer-file-name) descre))
11029 (setq targets (append tgs targets))))))
11030 (message "Getting targets...done")
11031 (delete-dups (nreverse targets))))
11033 (defun org--get-outline-path-1 (&optional use-cache)
11034 "Return outline path to current headline.
11036 Outline path is a list of strings, in reverse order. When
11037 optional argument USE-CACHE is non-nil, make use of a cache. See
11038 `org-get-outline-path' for details.
11040 Assume buffer is widened and point is on a headline."
11041 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11042 (let ((p (point))
11043 (heading (let ((case-fold-search nil))
11044 (looking-at org-complex-heading-regexp)
11045 (if (not (match-end 4)) ""
11046 ;; Remove statistics cookies.
11047 (org-trim
11048 (org-link-display-format
11049 (replace-regexp-in-string
11050 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11051 (match-string-no-properties 4))))))))
11052 (if (org-up-heading-safe)
11053 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11054 (when use-cache
11055 (push (cons p path) org-outline-path-cache))
11056 path)
11057 ;; This is a new root node. Since we assume we are moving
11058 ;; forward, we can drop previous cache so as to limit number
11059 ;; of associations there.
11060 (let ((path (list heading)))
11061 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11062 path)))))
11064 (defun org-get-outline-path (&optional with-self use-cache)
11065 "Return the outline path to the current entry.
11067 An outline path is a list of ancestors for current headline, as
11068 a list of strings. Statistics cookies are removed and links are
11069 replaced with their description, if any, or their path otherwise.
11071 When optional argument WITH-SELF is non-nil, the path also
11072 includes the current headline.
11074 When optional argument USE-CACHE is non-nil, cache outline paths
11075 between calls to this function so as to avoid backtracking. This
11076 argument is useful when planning to find more than one outline
11077 path in the same document. In that case, there are two
11078 conditions to satisfy:
11079 - `org-outline-path-cache' is set to nil before starting the
11080 process;
11081 - outline paths are computed by increasing buffer positions."
11082 (org-with-wide-buffer
11083 (and (or (and with-self (org-back-to-heading t))
11084 (org-up-heading-safe))
11085 (reverse (org--get-outline-path-1 use-cache)))))
11087 (defun org-format-outline-path (path &optional width prefix separator)
11088 "Format the outline path PATH for display.
11089 WIDTH is the maximum number of characters that is available.
11090 PREFIX is a prefix to be included in the returned string,
11091 such as the file name.
11092 SEPARATOR is inserted between the different parts of the path,
11093 the default is \"/\"."
11094 (setq width (or width 79))
11095 (setq path (delq nil path))
11096 (unless (> width 0)
11097 (user-error "Argument `width' must be positive"))
11098 (setq separator (or separator "/"))
11099 (let* ((org-odd-levels-only nil)
11100 (fpath (concat
11101 prefix (and prefix path separator)
11102 (mapconcat
11103 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11104 (cl-loop for head in path
11105 for n from 0
11106 collect (org-add-props
11107 head nil 'face
11108 (nth (% n org-n-level-faces) org-level-faces)))
11109 separator))))
11110 (when (> (length fpath) width)
11111 (if (< width 7)
11112 ;; It's unlikely that `width' will be this small, but don't
11113 ;; waste characters by adding ".." if it is.
11114 (setq fpath (substring fpath 0 width))
11115 (setf (substring fpath (- width 2)) "..")))
11116 fpath))
11118 (defun org-display-outline-path (&optional file current separator just-return-string)
11119 "Display the current outline path in the echo area.
11121 If FILE is non-nil, prepend the output with the file name.
11122 If CURRENT is non-nil, append the current heading to the output.
11123 SEPARATOR is passed through to `org-format-outline-path'. It separates
11124 the different parts of the path and defaults to \"/\".
11125 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11126 (interactive "P")
11127 (let* (case-fold-search
11128 (bfn (buffer-file-name (buffer-base-buffer)))
11129 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11130 res)
11131 (when current (setq path (append path
11132 (save-excursion
11133 (org-back-to-heading t)
11134 (when (looking-at org-complex-heading-regexp)
11135 (list (match-string 4)))))))
11136 (setq res
11137 (org-format-outline-path
11138 path
11139 (1- (frame-width))
11140 (and file bfn (concat (file-name-nondirectory bfn) separator))
11141 separator))
11142 (if just-return-string
11143 (org-no-properties res)
11144 (org-unlogged-message "%s" res))))
11146 (defvar org-refile-history nil
11147 "History for refiling operations.")
11149 (defvar org-after-refile-insert-hook nil
11150 "Hook run after `org-refile' has inserted its stuff at the new location.
11151 Note that this is still *before* the stuff will be removed from
11152 the *old* location.")
11154 (defvar org-capture-last-stored-marker)
11155 (defvar org-refile-keep nil
11156 "Non-nil means `org-refile' will copy instead of refile.")
11158 (defun org-copy ()
11159 "Like `org-refile', but copy."
11160 (interactive)
11161 (let ((org-refile-keep t))
11162 (funcall 'org-refile nil nil nil "Copy")))
11164 (defun org-refile (&optional arg default-buffer rfloc msg)
11165 "Move the entry or entries at point to another heading.
11167 The list of target headings is compiled using the information in
11168 `org-refile-targets', which see.
11170 At the target location, the entry is filed as a subitem of the
11171 target heading. Depending on `org-reverse-note-order', the new
11172 subitem will either be the first or the last subitem.
11174 If there is an active region, all entries in that region will be
11175 refiled. However, the region must fulfill the requirement that
11176 the first heading sets the top-level of the moved text.
11178 With a `\\[universal-argument]' ARG, the command will only visit the target \
11179 location
11180 and not actually move anything.
11182 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11183 location where the last
11184 refiling operation has put the subtree.
11186 With a numeric prefix argument of `2', refile to the running clock.
11188 With a numeric prefix argument of `3', emulate `org-refile-keep'
11189 being set to t and copy to the target location, don't move it.
11190 Beware that keeping refiled entries may result in duplicated ID
11191 properties.
11193 RFLOC can be a refile location obtained in a different way.
11195 MSG is a string to replace \"Refile\" in the default prompt with
11196 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11198 See also `org-refile-use-outline-path'.
11200 If you are using target caching (see `org-refile-use-cache'), you
11201 have to clear the target cache in order to find new targets.
11202 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11203 prefix argument (`C-u C-u C-u C-c C-w')."
11204 (interactive "P")
11205 (if (member arg '(0 (64)))
11206 (org-refile-cache-clear)
11207 (let* ((actionmsg (cond (msg msg)
11208 ((equal arg 3) "Refile (and keep)")
11209 (t "Refile")))
11210 (regionp (org-region-active-p))
11211 (region-start (and regionp (region-beginning)))
11212 (region-end (and regionp (region-end)))
11213 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11214 pos it nbuf file level reversed)
11215 (setq last-command nil)
11216 (when regionp
11217 (goto-char region-start)
11218 (or (bolp) (goto-char (point-at-bol)))
11219 (setq region-start (point))
11220 (unless (or (org-kill-is-subtree-p
11221 (buffer-substring region-start region-end))
11222 (prog1 org-refile-active-region-within-subtree
11223 (let ((s (point-at-eol)))
11224 (org-toggle-heading)
11225 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11226 (user-error "The region is not a (sequence of) subtree(s)")))
11227 (if (equal arg '(16))
11228 (org-refile-goto-last-stored)
11229 (when (or
11230 (and (equal arg 2)
11231 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11232 (prog1
11233 (setq it (list (or org-clock-heading "running clock")
11234 (buffer-file-name
11235 (marker-buffer org-clock-hd-marker))
11237 (marker-position org-clock-hd-marker)))
11238 (setq arg nil)))
11239 (setq it
11240 (or rfloc
11241 (let (heading-text)
11242 (save-excursion
11243 (unless (and arg (listp arg))
11244 (org-back-to-heading t)
11245 (setq heading-text
11246 (replace-regexp-in-string
11247 org-bracket-link-regexp
11248 "\\3"
11249 (or (nth 4 (org-heading-components))
11250 ""))))
11251 (org-refile-get-location
11252 (cond ((and arg (listp arg)) "Goto")
11253 (regionp (concat actionmsg " region to"))
11254 (t (concat actionmsg " subtree \""
11255 heading-text "\" to")))
11256 default-buffer
11257 (and (not (equal '(4) arg))
11258 org-refile-allow-creating-parent-nodes)))))))
11259 (setq file (nth 1 it)
11260 pos (nth 3 it))
11261 (when (and (not arg)
11263 (equal (buffer-file-name) file)
11264 (if regionp
11265 (and (>= pos region-start)
11266 (<= pos region-end))
11267 (and (>= pos (point))
11268 (< pos (save-excursion
11269 (org-end-of-subtree t t))))))
11270 (error "Cannot refile to position inside the tree or region"))
11271 (setq nbuf (or (find-buffer-visiting file)
11272 (find-file-noselect file)))
11273 (if (and arg (not (equal arg 3)))
11274 (progn
11275 (pop-to-buffer-same-window nbuf)
11276 (goto-char (cond (pos)
11277 ((org-notes-order-reversed-p) (point-min))
11278 (t (point-max))))
11279 (org-show-context 'org-goto))
11280 (if regionp
11281 (progn
11282 (org-kill-new (buffer-substring region-start region-end))
11283 (org-save-markers-in-region region-start region-end))
11284 (org-copy-subtree 1 nil t))
11285 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11286 (find-file-noselect file)))
11287 (setq reversed (org-notes-order-reversed-p))
11288 (org-with-wide-buffer
11289 (if pos
11290 (progn
11291 (goto-char pos)
11292 (setq level (org-get-valid-level (funcall outline-level) 1))
11293 (goto-char
11294 (if reversed
11295 (or (outline-next-heading) (point-max))
11296 (or (save-excursion (org-get-next-sibling))
11297 (org-end-of-subtree t t)
11298 (point-max)))))
11299 (setq level 1)
11300 (if (not reversed)
11301 (goto-char (point-max))
11302 (goto-char (point-min))
11303 (or (outline-next-heading) (goto-char (point-max)))))
11304 (unless (bolp) (newline))
11305 (org-paste-subtree level nil nil t)
11306 (when org-log-refile
11307 (org-add-log-setup 'refile nil nil org-log-refile)
11308 (unless (eq org-log-refile 'note)
11309 (save-excursion (org-add-log-note))))
11310 (and org-auto-align-tags
11311 (let ((org-loop-over-headlines-in-active-region nil))
11312 (org-set-tags nil t)))
11313 (let ((bookmark-name (plist-get org-bookmark-names-plist
11314 :last-refile)))
11315 (when bookmark-name
11316 (with-demoted-errors
11317 (bookmark-set bookmark-name))))
11318 ;; If we are refiling for capture, make sure that the
11319 ;; last-capture pointers point here
11320 (when (bound-and-true-p org-capture-is-refiling)
11321 (let ((bookmark-name (plist-get org-bookmark-names-plist
11322 :last-capture-marker)))
11323 (when bookmark-name
11324 (with-demoted-errors
11325 (bookmark-set bookmark-name))))
11326 (move-marker org-capture-last-stored-marker (point)))
11327 (when (fboundp 'deactivate-mark) (deactivate-mark))
11328 (run-hooks 'org-after-refile-insert-hook)))
11329 (unless org-refile-keep
11330 (if regionp
11331 (delete-region (point) (+ (point) (- region-end region-start)))
11332 (org-preserve-local-variables
11333 (delete-region
11334 (and (org-back-to-heading t) (point))
11335 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11336 (when (featurep 'org-inlinetask)
11337 (org-inlinetask-remove-END-maybe))
11338 (setq org-markers-to-move nil)
11339 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11341 (defun org-refile-goto-last-stored ()
11342 "Go to the location where the last refile was stored."
11343 (interactive)
11344 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11345 (message "This is the location of the last refile"))
11347 (defun org-refile--get-location (refloc tbl)
11348 "When user refile to REFLOC, find the associated target in TBL.
11349 Also check `org-refile-target-table'."
11350 (car (delq
11352 (mapcar
11353 (lambda (r) (or (assoc r tbl)
11354 (assoc r org-refile-target-table)))
11355 (list (replace-regexp-in-string "/$" "" refloc)
11356 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11358 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11359 "Prompt the user for a refile location, using PROMPT.
11360 PROMPT should not be suffixed with a colon and a space, because
11361 this function appends the default value from
11362 `org-refile-history' automatically, if that is not empty."
11363 (let ((org-refile-targets org-refile-targets)
11364 (org-refile-use-outline-path org-refile-use-outline-path))
11365 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11366 (unless org-refile-target-table
11367 (user-error "No refile targets"))
11368 (let* ((cbuf (current-buffer))
11369 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11370 (cfunc (if (and org-refile-use-outline-path
11371 org-outline-path-complete-in-steps)
11372 #'org-olpath-completing-read
11373 #'completing-read))
11374 (extra (if org-refile-use-outline-path "/" ""))
11375 (cbnex (concat (buffer-name) extra))
11376 (filename (and cfn (expand-file-name cfn)))
11377 (tbl (mapcar
11378 (lambda (x)
11379 (if (and (not (member org-refile-use-outline-path
11380 '(file full-file-path)))
11381 (not (equal filename (nth 1 x))))
11382 (cons (concat (car x) extra " ("
11383 (file-name-nondirectory (nth 1 x)) ")")
11384 (cdr x))
11385 (cons (concat (car x) extra) (cdr x))))
11386 org-refile-target-table))
11387 (completion-ignore-case t)
11388 cdef
11389 (prompt (concat prompt
11390 (or (and (car org-refile-history)
11391 (concat " (default " (car org-refile-history) ")"))
11392 (and (assoc cbnex tbl) (setq cdef cbnex)
11393 (concat " (default " cbnex ")"))) ": "))
11394 pa answ parent-target child parent old-hist)
11395 (setq old-hist org-refile-history)
11396 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11397 nil 'org-refile-history (or cdef (car org-refile-history))))
11398 (if (setq pa (org-refile--get-location answ tbl))
11399 (progn
11400 (org-refile-check-position pa)
11401 (when (or (not org-refile-history)
11402 (not (eq old-hist org-refile-history))
11403 (not (equal (car pa) (car org-refile-history))))
11404 (setq org-refile-history
11405 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11406 org-refile-history
11407 (cdr org-refile-history))))
11408 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11409 (pop org-refile-history)))
11411 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11412 (progn
11413 (setq parent (match-string 1 answ)
11414 child (match-string 2 answ))
11415 (setq parent-target (org-refile--get-location parent tbl))
11416 (when (and parent-target
11417 (or (eq new-nodes t)
11418 (and (eq new-nodes 'confirm)
11419 (y-or-n-p (format "Create new node \"%s\"? "
11420 child)))))
11421 (org-refile-new-child parent-target child)))
11422 (user-error "Invalid target location")))))
11424 (declare-function org-string-nw-p "org-macs" (s))
11425 (defun org-refile-check-position (refile-pointer)
11426 "Check if the refile pointer matches the headline to which it points."
11427 (let* ((file (nth 1 refile-pointer))
11428 (re (nth 2 refile-pointer))
11429 (pos (nth 3 refile-pointer))
11430 buffer)
11431 (if (and (not (markerp pos)) (not file))
11432 (user-error "Please indicate a target file in the refile path")
11433 (when (org-string-nw-p re)
11434 (setq buffer (if (markerp pos)
11435 (marker-buffer pos)
11436 (or (find-buffer-visiting file)
11437 (find-file-noselect file))))
11438 (with-current-buffer buffer
11439 (org-with-wide-buffer
11440 (goto-char pos)
11441 (beginning-of-line 1)
11442 (unless (looking-at-p re)
11443 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11445 (defun org-refile-new-child (parent-target child)
11446 "Use refile target PARENT-TARGET to add new CHILD below it."
11447 (unless parent-target
11448 (error "Cannot find parent for new node"))
11449 (let ((file (nth 1 parent-target))
11450 (pos (nth 3 parent-target))
11451 level)
11452 (with-current-buffer (or (find-buffer-visiting file)
11453 (find-file-noselect file))
11454 (org-with-wide-buffer
11455 (if pos
11456 (goto-char pos)
11457 (goto-char (point-max))
11458 (unless (bolp) (newline)))
11459 (when (looking-at org-outline-regexp)
11460 (setq level (funcall outline-level))
11461 (org-end-of-subtree t t))
11462 (org-back-over-empty-lines)
11463 (insert "\n" (make-string
11464 (if pos (org-get-valid-level level 1) 1) ?*)
11465 " " child "\n")
11466 (beginning-of-line 0)
11467 (list (concat (car parent-target) "/" child) file "" (point))))))
11469 (defun org-olpath-completing-read (prompt collection &rest args)
11470 "Read an outline path like a file name."
11471 (let ((thetable collection))
11472 (apply #'completing-read
11473 prompt
11474 (lambda (string predicate &optional flag)
11475 (cond
11476 ((eq flag nil) (try-completion string thetable))
11477 ((eq flag t)
11478 (let ((l (length string)))
11479 (mapcar (lambda (x)
11480 (let ((r (substring x l))
11481 (f (if (string-match " ([^)]*)$" x)
11482 (match-string 0 x)
11483 "")))
11484 (if (string-match "/" r)
11485 (concat string (substring r 0 (match-end 0)) f)
11486 x)))
11487 (all-completions string thetable predicate))))
11488 ;; Exact match?
11489 ((eq flag 'lambda) (assoc string thetable))))
11490 args)))
11492 ;;;; Dynamic blocks
11494 (defun org-find-dblock (name)
11495 "Find the first dynamic block with name NAME in the buffer.
11496 If not found, stay at current position and return nil."
11497 (let ((case-fold-search t) pos)
11498 (save-excursion
11499 (goto-char (point-min))
11500 (setq pos (and (re-search-forward
11501 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11502 (match-beginning 0))))
11503 (when pos (goto-char pos))
11504 pos))
11506 (defun org-create-dblock (plist)
11507 "Create a dynamic block section, with parameters taken from PLIST.
11508 PLIST must contain a :name entry which is used as the name of the block."
11509 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11510 (end-of-line 1)
11511 (newline))
11512 (let ((col (current-column))
11513 (name (plist-get plist :name)))
11514 (insert "#+BEGIN: " name)
11515 (while plist
11516 (if (eq (car plist) :name)
11517 (setq plist (cddr plist))
11518 (insert " " (prin1-to-string (pop plist)))))
11519 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11520 (beginning-of-line -2)))
11522 (defun org-prepare-dblock ()
11523 "Prepare dynamic block for refresh.
11524 This empties the block, puts the cursor at the insert position and returns
11525 the property list including an extra property :name with the block name."
11526 (unless (looking-at org-dblock-start-re)
11527 (user-error "Not at a dynamic block"))
11528 (let* ((begdel (1+ (match-end 0)))
11529 (name (org-no-properties (match-string 1)))
11530 (params (append (list :name name)
11531 (read (concat "(" (match-string 3) ")")))))
11532 (save-excursion
11533 (beginning-of-line 1)
11534 (skip-chars-forward " \t")
11535 (setq params (plist-put params :indentation-column (current-column))))
11536 (unless (re-search-forward org-dblock-end-re nil t)
11537 (error "Dynamic block not terminated"))
11538 (setq params
11539 (append params
11540 (list :content (buffer-substring
11541 begdel (match-beginning 0)))))
11542 (delete-region begdel (match-beginning 0))
11543 (goto-char begdel)
11544 (open-line 1)
11545 params))
11547 (defun org-map-dblocks (&optional command)
11548 "Apply COMMAND to all dynamic blocks in the current buffer.
11549 If COMMAND is not given, use `org-update-dblock'."
11550 (let ((cmd (or command 'org-update-dblock)))
11551 (save-excursion
11552 (goto-char (point-min))
11553 (while (re-search-forward org-dblock-start-re nil t)
11554 (goto-char (match-beginning 0))
11555 (save-excursion
11556 (condition-case nil
11557 (funcall cmd)
11558 (error (message "Error during update of dynamic block"))))
11559 (unless (re-search-forward org-dblock-end-re nil t)
11560 (error "Dynamic block not terminated"))))))
11562 (defun org-dblock-update (&optional arg)
11563 "User command for updating dynamic blocks.
11564 Update the dynamic block at point. With prefix ARG, update all dynamic
11565 blocks in the buffer."
11566 (interactive "P")
11567 (if arg
11568 (org-update-all-dblocks)
11569 (or (looking-at org-dblock-start-re)
11570 (org-beginning-of-dblock))
11571 (org-update-dblock)))
11573 (defun org-update-dblock ()
11574 "Update the dynamic block at point.
11575 This means to empty the block, parse for parameters and then call
11576 the correct writing function."
11577 (interactive)
11578 (save-excursion
11579 (let* ((win (selected-window))
11580 (pos (point))
11581 (line (org-current-line))
11582 (params (org-prepare-dblock))
11583 (name (plist-get params :name))
11584 (indent (plist-get params :indentation-column))
11585 (cmd (intern (concat "org-dblock-write:" name))))
11586 (message "Updating dynamic block `%s' at line %d..." name line)
11587 (funcall cmd params)
11588 (message "Updating dynamic block `%s' at line %d...done" name line)
11589 (goto-char pos)
11590 (when (and indent (> indent 0))
11591 (setq indent (make-string indent ?\ ))
11592 (save-excursion
11593 (select-window win)
11594 (org-beginning-of-dblock)
11595 (forward-line 1)
11596 (while (not (looking-at org-dblock-end-re))
11597 (insert indent)
11598 (beginning-of-line 2))
11599 (when (looking-at org-dblock-end-re)
11600 (and (looking-at "[ \t]+")
11601 (replace-match ""))
11602 (insert indent)))))))
11604 (defun org-beginning-of-dblock ()
11605 "Find the beginning of the dynamic block at point.
11606 Error if there is no such block at point."
11607 (let ((pos (point))
11608 beg)
11609 (end-of-line 1)
11610 (if (and (re-search-backward org-dblock-start-re nil t)
11611 (setq beg (match-beginning 0))
11612 (re-search-forward org-dblock-end-re nil t)
11613 (> (match-end 0) pos))
11614 (goto-char beg)
11615 (goto-char pos)
11616 (error "Not in a dynamic block"))))
11618 (defun org-update-all-dblocks ()
11619 "Update all dynamic blocks in the buffer.
11620 This function can be used in a hook."
11621 (interactive)
11622 (when (derived-mode-p 'org-mode)
11623 (org-map-dblocks 'org-update-dblock)))
11626 ;;;; Completion
11628 (declare-function org-export-backend-options "ox" (cl-x) t)
11629 (defun org-get-export-keywords ()
11630 "Return a list of all currently understood export keywords.
11631 Export keywords include options, block names, attributes and
11632 keywords relative to each registered export back-end."
11633 (let (keywords)
11634 (dolist (backend
11635 (bound-and-true-p org-export-registered-backends)
11636 (delq nil keywords))
11637 ;; Back-end name (for keywords, like #+LATEX:)
11638 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11639 (dolist (option-entry (org-export-backend-options backend))
11640 ;; Back-end options.
11641 (push (nth 1 option-entry) keywords)))))
11643 (defconst org-options-keywords
11644 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11645 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11646 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11647 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11648 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11650 (defcustom org-structure-template-alist
11651 '(("a" . "export ascii")
11652 ("c" . "center")
11653 ("C" . "comment")
11654 ("e" . "example")
11655 ("E" . "export")
11656 ("h" . "export html")
11657 ("l" . "export latex")
11658 ("q" . "quote")
11659 ("s" . "src")
11660 ("v" . "verse"))
11661 "Structure completion elements.
11662 This is an alist of keys and block types. With
11663 `org-insert-structure-template' a block can be inserted through a
11664 menu. The block type is inserted, with \"#+BEGIN_\" and
11665 \"#+END_\" added automatically. The menukeys are determined
11666 based on the key elements in the `org-structure-template-alist'.
11667 If two entries have the keys \"a\" and \"aa\" respectively, the
11668 former will be inserted by typing \"a TAB/RET/SPC\" and the
11669 latter will be inserted by typing \"aa\". If an entry with the
11670 key \"aab\" is later added it would be inserted by typing \"ab\".
11672 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11673 block can be inserted by pressing TAB after the string \"<KEY\".
11675 :group 'org-edit-structure
11676 :type '(repeat
11677 (cons (string :tag "Key")
11678 (string :tag "Template")))
11679 :package-version '(Org . "9.2"))
11681 (defun org--insert-structure-template-mks ()
11682 "Present `org-structure-template-alist' with `org-mks'.
11684 Menus are added if keys require more than one keystroke.
11685 Tabs are added to single key entires when needing more than one stroke.
11686 Keys longer than two characters are reduced to two characters."
11687 (let* (case-fold-search
11688 (templates (append org-structure-template-alist
11689 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11690 (keys (mapcar #'car templates))
11691 (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11692 ;; Sort each element of `org-structure-template-alist' into
11693 ;; sublists according to the first letter.
11694 (superlist (mapcar (lambda (letter)
11695 (list letter
11696 (cl-remove-if-not
11697 (apply-partially #'string-match-p (concat "^" letter))
11698 templates :key #'car)))
11699 start-letters)))
11700 (org-mks
11701 (apply #'append
11702 ;; Make an `org-mks' table. If only one element is
11703 ;; present in a sublist, make it part of the top-menu,
11704 ;; otherwise make a submenu according to the starting
11705 ;; letter and populate it.
11706 (mapcar (lambda (sublist)
11707 (if (eq 1 (length (cadr sublist)))
11708 (mapcar (lambda (elm)
11709 (list (substring (car elm) 0 1)
11710 (cdr elm) ""))
11711 (cadr sublist))
11712 ;; Create submenu.
11713 (let* ((topkey (car sublist))
11714 (elms (cadr sublist))
11715 (keys (mapcar #'car elms))
11716 (long (> (length elms) 3)))
11717 (append
11718 (list
11719 ;; Make a description of the submenu.
11720 (list topkey
11721 (concat
11722 (mapconcat #'cdr
11723 (cl-subseq elms 0 (if long 3 (length elms)))
11724 ", ")
11725 (when long ", ..."))))
11726 ;; List of entries in submenu.
11727 (cl-mapcar #'list
11728 (org--insert-structure-template-unique-keys keys)
11729 (mapcar #'cdr elms)
11730 (make-list (length elms) ""))))))
11731 superlist))
11732 "Select a key\n============"
11733 "Key: ")))
11735 (defun org--insert-structure-template-unique-keys (keys)
11736 "Make list of unique, two character long elements from KEYS.
11738 Elements of length one have a tab appended. Elements of length
11739 two are kept as is. Longer elements are truncated to length two.
11741 If an element cannot be made unique an error is raised."
11742 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11743 menu-keys)
11744 (dolist (key orderd-keys)
11745 (let ((potential-key
11746 (cl-case (length key)
11747 (1 (concat key "\t"))
11748 (2 key)
11749 (otherwise
11750 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11751 (mapcar (apply-partially #'concat (substring key 0 1))
11752 (split-string (substring key 1) "" t)))))))
11753 (if (or (not potential-key) (assoc potential-key menu-keys))
11754 (user-error "Could not make unique key for %s." key)
11755 (push (cons potential-key key) menu-keys))))
11756 (mapcar #'car
11757 (cl-sort menu-keys #'<
11758 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11760 (defun org-insert-structure-template (type)
11761 "Insert a block structure of the type #+begin_foo/#+end_foo.
11762 First choose a block based on `org-structure-template-alist'.
11763 Alternatively, type RET, TAB or SPC to write the block type.
11764 With an active region, wrap the region in the block. Otherwise,
11765 insert an empty block."
11766 (interactive
11767 (list (pcase (org--insert-structure-template-mks)
11768 (`("\t" . ,_) (read-string "Structure type: "))
11769 (`(,_ ,choice . ,_) choice))))
11770 (let* ((region? (use-region-p))
11771 (col (current-indentation))
11772 (indent (make-string col ?\s))
11773 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11774 (region-string (and region?
11775 (buffer-substring (region-beginning)
11776 (region-end))))
11777 (region-end-blank (and region?
11778 (save-excursion
11779 (goto-char (region-end))
11780 (when (looking-at "[ \t]*$")
11781 (replace-match "")
11782 t))))
11784 (when region? (delete-region (region-beginning) (region-end)))
11785 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11786 (insert "\n"))
11787 (beginning-of-line)
11788 (save-excursion
11789 (insert
11790 (with-temp-buffer
11791 (when region?
11792 (insert region-string "\n")
11793 (when (string-match-p
11794 (concat "\\`" (regexp-opt '("example" "export" "src")))
11795 type)
11796 (org-escape-code-in-region (point-min) (point-max))))
11797 (goto-char (point-min))
11798 ;; Delete trailing white-lines.
11799 (when region?
11800 (while (looking-at-p "^[ \t]*$")
11801 (delete-region (line-beginning-position)
11802 (line-beginning-position 2))))
11803 (save-excursion
11804 (while (not (eobp))
11805 (unless (looking-at-p indent)
11806 (insert indent))
11807 (forward-line)))
11808 (insert
11809 indent
11810 (format "#+begin_%s%s\n" type (if special? " " "")))
11811 (unless region? (indent-to col))
11812 (setq s (point))
11813 (goto-char (point-max))
11814 (skip-chars-backward "[ \t\n]" s)
11815 (delete-region (line-end-position) (point-max))
11816 (insert "\n" indent
11817 (format "#+end_%s" (car (split-string type)))
11818 (if region-end-blank "" "\n"))
11819 (buffer-substring (point-min) (point))))
11820 (when (and (eobp) (not (bolp))) (insert "\n")))
11821 (cond (special?
11822 (end-of-line))
11824 (forward-line)
11825 (skip-chars-forward "[ \t]*")))))
11828 ;;;; TODO, DEADLINE, Comments
11830 (defun org-toggle-comment ()
11831 "Change the COMMENT state of an entry."
11832 (interactive)
11833 (save-excursion
11834 (org-back-to-heading)
11835 (let ((case-fold-search nil))
11836 (looking-at org-complex-heading-regexp))
11837 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11838 (skip-chars-forward " \t")
11839 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11840 (if (org-in-commented-heading-p t)
11841 (delete-region (point)
11842 (progn (search-forward " " (line-end-position) 'move)
11843 (skip-chars-forward " \t")
11844 (point)))
11845 (insert org-comment-string)
11846 (unless (eolp) (insert " ")))))
11848 (defvar org-last-todo-state-is-todo nil
11849 "This is non-nil when the last TODO state change led to a TODO state.
11850 If the last change removed the TODO tag or switched to DONE, then
11851 this is nil.")
11853 (defvar org-setting-tags nil) ; dynamically scoped
11855 (defvar org-todo-setup-filter-hook nil
11856 "Hook for functions that pre-filter todo specs.
11857 Each function takes a todo spec and returns either nil or the spec
11858 transformed into canonical form." )
11860 (defvar org-todo-get-default-hook nil
11861 "Hook for functions that get a default item for todo.
11862 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11863 nil or a string to be used for the todo mark." )
11865 (defvar org-agenda-headline-snapshot-before-repeat)
11867 (defun org-current-effective-time ()
11868 "Return current time adjusted for `org-extend-today-until' variable."
11869 (let* ((ct (org-current-time))
11870 (dct (decode-time ct))
11871 (ct1
11872 (cond
11873 (org-use-last-clock-out-time-as-effective-time
11874 (or (org-clock-get-last-clock-out-time) ct))
11875 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11876 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11877 (t ct))))
11878 ct1))
11880 (defun org-todo-yesterday (&optional arg)
11881 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11882 (interactive "P")
11883 (if (eq major-mode 'org-agenda-mode)
11884 (apply 'org-agenda-todo-yesterday arg)
11885 (let* ((org-use-effective-time t)
11886 (hour (nth 2 (decode-time (org-current-time))))
11887 (org-extend-today-until (1+ hour)))
11888 (org-todo arg))))
11890 (defvar org-block-entry-blocking ""
11891 "First entry preventing the TODO state change.")
11893 (defun org-cancel-repeater ()
11894 "Cancel a repeater by setting its numeric value to zero."
11895 (interactive)
11896 (save-excursion
11897 (org-back-to-heading t)
11898 (let ((bound1 (point))
11899 (bound0 (save-excursion (outline-next-heading) (point))))
11900 (when (and (re-search-forward
11901 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11902 org-deadline-time-regexp "\\)\\|\\("
11903 org-ts-regexp "\\)")
11904 bound0 t)
11905 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11906 bound1 t))
11907 (replace-match "0" t nil nil 1)))))
11909 (defvar org-state)
11910 (defvar org-blocked-by-checkboxes)
11911 (defun org-todo (&optional arg)
11912 "Change the TODO state of an item.
11914 The state of an item is given by a keyword at the start of the heading,
11915 like
11916 *** TODO Write paper
11917 *** DONE Call mom
11919 The different keywords are specified in the variable `org-todo-keywords'.
11920 By default the available states are \"TODO\" and \"DONE\". So, for this
11921 example: when the item starts with TODO, it is changed to DONE.
11922 When it starts with DONE, the DONE is removed. And when neither TODO nor
11923 DONE are present, add TODO at the beginning of the heading.
11925 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11926 state.
11927 With numeric prefix ARG, switch to that state.
11928 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11929 next set of TODO \
11930 keywords (nextset).
11931 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11932 prefix, circumvent any state blocking.
11933 With a numeric prefix arg of 0, inhibit note taking for the change.
11934 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11936 When called through ELisp, arg is also interpreted in the following way:
11937 `none' -> empty state
11938 \"\" -> switch to empty state
11939 `done' -> switch to DONE
11940 `nextset' -> switch to the next set of keywords
11941 `previousset' -> switch to the previous set of keywords
11942 \"WAITING\" -> switch to the specified keyword, but only if it
11943 really is a member of `org-todo-keywords'."
11944 (interactive "P")
11945 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11946 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11947 'region-start-level 'region))
11948 org-loop-over-headlines-in-active-region)
11949 (org-map-entries
11950 `(org-todo ,arg)
11951 org-loop-over-headlines-in-active-region
11952 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11953 (when (equal arg '(16)) (setq arg 'nextset))
11954 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11955 (let ((org-blocker-hook org-blocker-hook)
11956 commentp
11957 case-fold-search)
11958 (when (equal arg '(64))
11959 (setq arg nil org-blocker-hook nil))
11960 (when (and org-blocker-hook
11961 (or org-inhibit-blocking
11962 (org-entry-get nil "NOBLOCKING")))
11963 (setq org-blocker-hook nil))
11964 (save-excursion
11965 (catch 'exit
11966 (org-back-to-heading t)
11967 (when (org-in-commented-heading-p t)
11968 (org-toggle-comment)
11969 (setq commentp t))
11970 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11971 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11972 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11973 (let* ((match-data (match-data))
11974 (startpos (copy-marker (line-beginning-position)))
11975 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11976 (org-log-done org-log-done)
11977 (org-log-repeat org-log-repeat)
11978 (org-todo-log-states org-todo-log-states)
11979 (org-inhibit-logging
11980 (if (equal arg 0)
11981 (progn (setq arg nil) 'note) org-inhibit-logging))
11982 (this (match-string 1))
11983 (hl-pos (match-beginning 0))
11984 (head (org-get-todo-sequence-head this))
11985 (ass (assoc head org-todo-kwd-alist))
11986 (interpret (nth 1 ass))
11987 (done-word (nth 3 ass))
11988 (final-done-word (nth 4 ass))
11989 (org-last-state (or this ""))
11990 (completion-ignore-case t)
11991 (member (member this org-todo-keywords-1))
11992 (tail (cdr member))
11993 (org-state (cond
11994 ((and org-todo-key-trigger
11995 (or (and (equal arg '(4))
11996 (eq org-use-fast-todo-selection 'prefix))
11997 (and (not arg) org-use-fast-todo-selection
11998 (not (eq org-use-fast-todo-selection
11999 'prefix)))))
12000 ;; Use fast selection.
12001 (org-fast-todo-selection))
12002 ((and (equal arg '(4))
12003 (or (not org-use-fast-todo-selection)
12004 (not org-todo-key-trigger)))
12005 ;; Read a state with completion.
12006 (completing-read
12007 "State: " (mapcar #'list org-todo-keywords-1)
12008 nil t))
12009 ((eq arg 'right)
12010 (if this
12011 (if tail (car tail) nil)
12012 (car org-todo-keywords-1)))
12013 ((eq arg 'left)
12014 (unless (equal member org-todo-keywords-1)
12015 (if this
12016 (nth (- (length org-todo-keywords-1)
12017 (length tail) 2)
12018 org-todo-keywords-1)
12019 (org-last org-todo-keywords-1))))
12020 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12021 (setq arg nil))) ;hack to fall back to cycling
12022 (arg
12023 ;; User or caller requests a specific state.
12024 (cond
12025 ((equal arg "") nil)
12026 ((eq arg 'none) nil)
12027 ((eq arg 'done) (or done-word (car org-done-keywords)))
12028 ((eq arg 'nextset)
12029 (or (car (cdr (member head org-todo-heads)))
12030 (car org-todo-heads)))
12031 ((eq arg 'previousset)
12032 (let ((org-todo-heads (reverse org-todo-heads)))
12033 (or (car (cdr (member head org-todo-heads)))
12034 (car org-todo-heads))))
12035 ((car (member arg org-todo-keywords-1)))
12036 ((stringp arg)
12037 (user-error "State `%s' not valid in this file" arg))
12038 ((nth (1- (prefix-numeric-value arg))
12039 org-todo-keywords-1))))
12040 ((null member) (or head (car org-todo-keywords-1)))
12041 ((equal this final-done-word) nil) ;-> make empty
12042 ((null tail) nil) ;-> first entry
12043 ((memq interpret '(type priority))
12044 (if (eq this-command last-command)
12045 (car tail)
12046 (if (> (length tail) 0)
12047 (or done-word (car org-done-keywords))
12048 nil)))
12050 (car tail))))
12051 (org-state (or
12052 (run-hook-with-args-until-success
12053 'org-todo-get-default-hook org-state org-last-state)
12054 org-state))
12055 (next (if org-state (concat " " org-state " ") " "))
12056 (change-plist (list :type 'todo-state-change :from this :to org-state
12057 :position startpos))
12058 dolog now-done-p)
12059 (when org-blocker-hook
12060 (let (org-blocked-by-checkboxes block-reason)
12061 (setq org-last-todo-state-is-todo
12062 (not (member this org-done-keywords)))
12063 (unless (save-excursion
12064 (save-match-data
12065 (org-with-wide-buffer
12066 (run-hook-with-args-until-failure
12067 'org-blocker-hook change-plist))))
12068 (setq block-reason (if org-blocked-by-checkboxes
12069 "contained checkboxes"
12070 (format "\"%s\"" org-block-entry-blocking)))
12071 (if (called-interactively-p 'interactive)
12072 (user-error "TODO state change from %s to %s blocked (by %s)"
12073 this org-state block-reason)
12074 ;; Fail silently.
12075 (message "TODO state change from %s to %s blocked (by %s)"
12076 this org-state block-reason)
12077 (throw 'exit nil)))))
12078 (store-match-data match-data)
12079 (replace-match next t t)
12080 (cond ((equal this org-state)
12081 (message "TODO state was already %s" (org-trim next)))
12082 ((not (pos-visible-in-window-p hl-pos))
12083 (message "TODO state changed to %s" (org-trim next))))
12084 (unless head
12085 (setq head (org-get-todo-sequence-head org-state)
12086 ass (assoc head org-todo-kwd-alist)
12087 interpret (nth 1 ass)
12088 done-word (nth 3 ass)
12089 final-done-word (nth 4 ass)))
12090 (when (memq arg '(nextset previousset))
12091 (message "Keyword-Set %d/%d: %s"
12092 (- (length org-todo-sets) -1
12093 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12094 (length org-todo-sets)
12095 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12096 (setq org-last-todo-state-is-todo
12097 (not (member org-state org-done-keywords)))
12098 (setq now-done-p (and (member org-state org-done-keywords)
12099 (not (member this org-done-keywords))))
12100 (and logging (org-local-logging logging))
12101 (when (and (or org-todo-log-states org-log-done)
12102 (not (eq org-inhibit-logging t))
12103 (not (memq arg '(nextset previousset))))
12104 ;; We need to look at recording a time and note.
12105 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12106 (nth 2 (assoc this org-todo-log-states))))
12107 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12108 (setq dolog 'time))
12109 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12110 (and org-state
12111 (member org-state org-not-done-keywords)
12112 (not (member this org-not-done-keywords))))
12113 ;; This is now a todo state and was not one before
12114 ;; If there was a CLOSED time stamp, get rid of it.
12115 (org-add-planning-info nil nil 'closed))
12116 (when (and now-done-p org-log-done)
12117 ;; It is now done, and it was not done before.
12118 (org-add-planning-info 'closed (org-current-effective-time))
12119 (when (and (not dolog) (eq 'note org-log-done))
12120 (org-add-log-setup 'done org-state this 'note)))
12121 (when (and org-state dolog)
12122 ;; This is a non-nil state, and we need to log it.
12123 (org-add-log-setup 'state org-state this dolog)))
12124 ;; Fixup tag positioning.
12125 (org-todo-trigger-tag-changes org-state)
12126 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12127 (when org-provide-todo-statistics
12128 (org-update-parent-todo-statistics))
12129 (run-hooks 'org-after-todo-state-change-hook)
12130 (when (and arg (not (member org-state org-done-keywords)))
12131 (setq head (org-get-todo-sequence-head org-state)))
12132 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12133 ;; Do we need to trigger a repeat?
12134 (when now-done-p
12135 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12136 ;; This is for the agenda, take a snapshot of the headline.
12137 (save-match-data
12138 (setq org-agenda-headline-snapshot-before-repeat
12139 (org-get-heading))))
12140 (org-auto-repeat-maybe org-state))
12141 ;; Fixup cursor location if close to the keyword.
12142 (when (and (outline-on-heading-p)
12143 (not (bolp))
12144 (save-excursion (beginning-of-line 1)
12145 (looking-at org-todo-line-regexp))
12146 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12147 (goto-char (or (match-end 2) (match-end 1)))
12148 (and (looking-at " ") (just-one-space)))
12149 (when org-trigger-hook
12150 (save-excursion
12151 (run-hook-with-args 'org-trigger-hook change-plist)))
12152 (when commentp (org-toggle-comment))))))))
12154 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12155 "Block turning an entry into a TODO, using the hierarchy.
12156 This checks whether the current task should be blocked from state
12157 changes. Such blocking occurs when:
12159 1. The task has children which are not all in a completed state.
12161 2. A task has a parent with the property :ORDERED:, and there
12162 are siblings prior to the current task with incomplete
12163 status.
12165 3. The parent of the task is blocked because it has siblings that should
12166 be done first, or is child of a block grandparent TODO entry."
12168 (if (not org-enforce-todo-dependencies)
12169 t ; if locally turned off don't block
12170 (catch 'dont-block
12171 ;; If this is not a todo state change, or if this entry is already DONE,
12172 ;; do not block
12173 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12174 (member (plist-get change-plist :from)
12175 (cons 'done org-done-keywords))
12176 (member (plist-get change-plist :to)
12177 (cons 'todo org-not-done-keywords))
12178 (not (plist-get change-plist :to)))
12179 (throw 'dont-block t))
12180 ;; If this task has children, and any are undone, it's blocked
12181 (save-excursion
12182 (org-back-to-heading t)
12183 (let ((this-level (funcall outline-level)))
12184 (outline-next-heading)
12185 (let ((child-level (funcall outline-level)))
12186 (while (and (not (eobp))
12187 (> child-level this-level))
12188 ;; this todo has children, check whether they are all
12189 ;; completed
12190 (when (and (not (org-entry-is-done-p))
12191 (org-entry-is-todo-p))
12192 (setq org-block-entry-blocking (org-get-heading))
12193 (throw 'dont-block nil))
12194 (outline-next-heading)
12195 (setq child-level (funcall outline-level))))))
12196 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12197 ;; any previous siblings are undone, it's blocked
12198 (save-excursion
12199 (org-back-to-heading t)
12200 (let* ((pos (point))
12201 (parent-pos (and (org-up-heading-safe) (point)))
12202 (case-fold-search nil))
12203 (unless parent-pos (throw 'dont-block t)) ; no parent
12204 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12205 (forward-line 1)
12206 (re-search-forward org-not-done-heading-regexp pos t))
12207 (setq org-block-entry-blocking (match-string 0))
12208 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12209 ;; Search further up the hierarchy, to see if an ancestor is blocked
12210 (while t
12211 (goto-char parent-pos)
12212 (unless (looking-at org-not-done-heading-regexp)
12213 (throw 'dont-block t)) ; do not block, parent is not a TODO
12214 (setq pos (point))
12215 (setq parent-pos (and (org-up-heading-safe) (point)))
12216 (unless parent-pos (throw 'dont-block t)) ; no parent
12217 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12218 (forward-line 1)
12219 (re-search-forward org-not-done-heading-regexp pos t)
12220 (setq org-block-entry-blocking (org-get-heading)))
12221 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12223 (defcustom org-track-ordered-property-with-tag nil
12224 "Should the ORDERED property also be shown as a tag?
12225 The ORDERED property decides if an entry should require subtasks to be
12226 completed in sequence. Since a property is not very visible, setting
12227 this option means that toggling the ORDERED property with the command
12228 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12229 not relevant for the behavior, but it makes things more visible.
12231 Note that toggling the tag with tags commands will not change the property
12232 and therefore not influence behavior!
12234 This can be t, meaning the tag ORDERED should be used, It can also be a
12235 string to select a different tag for this task."
12236 :group 'org-todo
12237 :type '(choice
12238 (const :tag "No tracking" nil)
12239 (const :tag "Track with ORDERED tag" t)
12240 (string :tag "Use other tag")))
12242 (defun org-toggle-ordered-property ()
12243 "Toggle the ORDERED property of the current entry.
12244 For better visibility, you can track the value of this property with a tag.
12245 See variable `org-track-ordered-property-with-tag'."
12246 (interactive)
12247 (let* ((t1 org-track-ordered-property-with-tag)
12248 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12249 (save-excursion
12250 (org-back-to-heading)
12251 (if (org-entry-get nil "ORDERED")
12252 (progn
12253 (org-delete-property "ORDERED")
12254 (and tag (org-toggle-tag tag 'off))
12255 (message "Subtasks can be completed in arbitrary order"))
12256 (org-entry-put nil "ORDERED" "t")
12257 (and tag (org-toggle-tag tag 'on))
12258 (message "Subtasks must be completed in sequence")))))
12260 (defun org-block-todo-from-checkboxes (change-plist)
12261 "Block turning an entry into a TODO, using checkboxes.
12262 This checks whether the current task should be blocked from state
12263 changes because there are unchecked boxes in this entry."
12264 (if (not org-enforce-todo-checkbox-dependencies)
12265 t ; if locally turned off don't block
12266 (catch 'dont-block
12267 ;; If this is not a todo state change, or if this entry is already DONE,
12268 ;; do not block
12269 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12270 (member (plist-get change-plist :from)
12271 (cons 'done org-done-keywords))
12272 (member (plist-get change-plist :to)
12273 (cons 'todo org-not-done-keywords))
12274 (not (plist-get change-plist :to)))
12275 (throw 'dont-block t))
12276 ;; If this task has checkboxes that are not checked, it's blocked
12277 (save-excursion
12278 (org-back-to-heading t)
12279 (let ((beg (point)) end)
12280 (outline-next-heading)
12281 (setq end (point))
12282 (goto-char beg)
12283 (when (org-list-search-forward
12284 (concat (org-item-beginning-re)
12285 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12286 "\\[[- ]\\]")
12287 end t)
12288 (when (boundp 'org-blocked-by-checkboxes)
12289 (setq org-blocked-by-checkboxes t))
12290 (throw 'dont-block nil))))
12291 t))) ; do not block
12293 (defun org-entry-blocked-p ()
12294 "Non-nil if entry at point is blocked."
12295 (and (not (org-entry-get nil "NOBLOCKING"))
12296 (member (org-entry-get nil "TODO") org-not-done-keywords)
12297 (not (run-hook-with-args-until-failure
12298 'org-blocker-hook
12299 (list :type 'todo-state-change
12300 :position (point)
12301 :from 'todo
12302 :to 'done)))))
12304 (defun org-update-statistics-cookies (all)
12305 "Update the statistics cookie, either from TODO or from checkboxes.
12306 This should be called with the cursor in a line with a statistics
12307 cookie. When called with a \\[universal-argument] prefix, update
12308 all statistics cookies in the buffer."
12309 (interactive "P")
12310 (if all
12311 (progn
12312 (org-update-checkbox-count 'all)
12313 (org-map-entries 'org-update-parent-todo-statistics))
12314 (if (not (org-at-heading-p))
12315 (org-update-checkbox-count)
12316 (let ((pos (point-marker))
12317 end l1 l2)
12318 (ignore-errors (org-back-to-heading t))
12319 (if (not (org-at-heading-p))
12320 (org-update-checkbox-count)
12321 (setq l1 (org-outline-level))
12322 (setq end (save-excursion
12323 (outline-next-heading)
12324 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12325 (point)))
12326 (if (and (save-excursion
12327 (re-search-forward
12328 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12329 (not (save-excursion (re-search-forward
12330 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12331 (org-update-checkbox-count)
12332 (if (and l2 (> l2 l1))
12333 (progn
12334 (goto-char end)
12335 (org-update-parent-todo-statistics))
12336 (goto-char pos)
12337 (beginning-of-line 1)
12338 (while (re-search-forward
12339 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12340 (point-at-eol) t)
12341 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12342 (goto-char pos)
12343 (move-marker pos nil)))))
12345 (defvar org-entry-property-inherited-from) ;; defined below
12346 (defun org-update-parent-todo-statistics ()
12347 "Update any statistics cookie in the parent of the current headline.
12348 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12349 the entire subtree and this will travel up the hierarchy and update
12350 statistics everywhere."
12351 (let* ((prop (save-excursion (org-up-heading-safe)
12352 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12353 (recursive (or (not org-hierarchical-todo-statistics)
12354 (and prop (string-match "\\<recursive\\>" prop))))
12355 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12357 (first t)
12358 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12359 level ltoggle l1 new ndel
12360 (cnt-all 0) (cnt-done 0) is-percent kwd
12361 checkbox-beg cookie-present)
12362 (catch 'exit
12363 (save-excursion
12364 (beginning-of-line 1)
12365 (setq ltoggle (funcall outline-level))
12366 ;; Three situations are to consider:
12368 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12369 ;; to the top-level ancestor on the headline;
12371 ;; 2. If parent has "recursive" property, repeat up to the
12372 ;; headline setting that property, taking inheritance into
12373 ;; account;
12375 ;; 3. Else, move up to direct parent and proceed only once.
12376 (while (and (setq level (org-up-heading-safe))
12377 (or recursive first)
12378 (>= (point) lim))
12379 (setq first nil cookie-present nil)
12380 (unless (and level
12381 (not (string-match
12382 "\\<checkbox\\>"
12383 (downcase (or (org-entry-get nil "COOKIE_DATA")
12384 "")))))
12385 (throw 'exit nil))
12386 (while (re-search-forward box-re (point-at-eol) t)
12387 (setq cnt-all 0 cnt-done 0 cookie-present t)
12388 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12389 (save-match-data
12390 (unless (outline-next-heading) (throw 'exit nil))
12391 (while (and (looking-at org-complex-heading-regexp)
12392 (> (setq l1 (length (match-string 1))) level))
12393 (setq kwd (and (or recursive (= l1 ltoggle))
12394 (match-string 2)))
12395 (if (or (eq org-provide-todo-statistics 'all-headlines)
12396 (and (eq org-provide-todo-statistics t)
12397 (or (member kwd org-done-keywords)))
12398 (and (listp org-provide-todo-statistics)
12399 (stringp (car org-provide-todo-statistics))
12400 (or (member kwd org-provide-todo-statistics)
12401 (member kwd org-done-keywords)))
12402 (and (listp org-provide-todo-statistics)
12403 (listp (car org-provide-todo-statistics))
12404 (or (member kwd (car org-provide-todo-statistics))
12405 (and (member kwd org-done-keywords)
12406 (member kwd (cadr org-provide-todo-statistics))))))
12407 (setq cnt-all (1+ cnt-all))
12408 (and (eq org-provide-todo-statistics t)
12410 (setq cnt-all (1+ cnt-all))))
12411 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12412 (member kwd org-done-keywords))
12413 (and (listp org-provide-todo-statistics)
12414 (listp (car org-provide-todo-statistics))
12415 (member kwd org-done-keywords)
12416 (member kwd (cadr org-provide-todo-statistics)))
12417 (and (listp org-provide-todo-statistics)
12418 (stringp (car org-provide-todo-statistics))
12419 (member kwd org-done-keywords)))
12420 (setq cnt-done (1+ cnt-done)))
12421 (outline-next-heading)))
12422 (setq new
12423 (if is-percent
12424 (format "[%d%%]" (floor (* 100.0 cnt-done)
12425 (max 1 cnt-all)))
12426 (format "[%d/%d]" cnt-done cnt-all))
12427 ndel (- (match-end 0) checkbox-beg))
12428 (goto-char checkbox-beg)
12429 (insert new)
12430 (delete-region (point) (+ (point) ndel))
12431 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12432 (when cookie-present
12433 (run-hook-with-args 'org-after-todo-statistics-hook
12434 cnt-done (- cnt-all cnt-done))))))
12435 (run-hooks 'org-todo-statistics-hook)))
12437 (defvar org-after-todo-statistics-hook nil
12438 "Hook that is called after a TODO statistics cookie has been updated.
12439 Each function is called with two arguments: the number of not-done entries
12440 and the number of done entries.
12442 For example, the following function, when added to this hook, will switch
12443 an entry to DONE when all children are done, and back to TODO when new
12444 entries are set to a TODO status. Note that this hook is only called
12445 when there is a statistics cookie in the headline!
12447 (defun org-summary-todo (n-done n-not-done)
12448 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12449 (let (org-log-done org-log-states) ; turn off logging
12450 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12453 (defvar org-todo-statistics-hook nil
12454 "Hook that is run whenever Org thinks TODO statistics should be updated.
12455 This hook runs even if there is no statistics cookie present, in which case
12456 `org-after-todo-statistics-hook' would not run.")
12458 (defun org-todo-trigger-tag-changes (state)
12459 "Apply the changes defined in `org-todo-state-tags-triggers'."
12460 (let ((l org-todo-state-tags-triggers)
12461 changes)
12462 (when (or (not state) (equal state ""))
12463 (setq changes (append changes (cdr (assoc "" l)))))
12464 (when (and (stringp state) (> (length state) 0))
12465 (setq changes (append changes (cdr (assoc state l)))))
12466 (when (member state org-not-done-keywords)
12467 (setq changes (append changes (cdr (assq 'todo l)))))
12468 (when (member state org-done-keywords)
12469 (setq changes (append changes (cdr (assq 'done l)))))
12470 (dolist (c changes)
12471 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12473 (defun org-local-logging (value)
12474 "Get logging settings from a property VALUE."
12475 ;; Directly set the variables, they are already local.
12476 (setq org-log-done nil
12477 org-log-repeat nil
12478 org-todo-log-states nil)
12479 (dolist (w (split-string value))
12480 (let (a)
12481 (cond
12482 ((setq a (assoc w org-startup-options))
12483 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12484 (set (nth 1 a) (nth 2 a))))
12485 ((setq a (org-extract-log-state-settings w))
12486 (and (member (car a) org-todo-keywords-1)
12487 (push a org-todo-log-states)))))))
12489 (defun org-get-todo-sequence-head (kwd)
12490 "Return the head of the TODO sequence to which KWD belongs.
12491 If KWD is not set, check if there is a text property remembering the
12492 right sequence."
12493 (let (p)
12494 (cond
12495 ((not kwd)
12496 (or (get-text-property (point-at-bol) 'org-todo-head)
12497 (progn
12498 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12499 nil (point-at-eol)))
12500 (get-text-property p 'org-todo-head))))
12501 ((not (member kwd org-todo-keywords-1))
12502 (car org-todo-keywords-1))
12503 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12505 (defun org-fast-todo-selection ()
12506 "Fast TODO keyword selection with single keys.
12507 Returns the new TODO keyword, or nil if no state change should occur."
12508 (let* ((fulltable org-todo-key-alist)
12509 (done-keywords org-done-keywords) ;; needed for the faces.
12510 (maxlen (apply 'max (mapcar
12511 (lambda (x)
12512 (if (stringp (car x)) (string-width (car x)) 0))
12513 fulltable)))
12514 (expert nil)
12515 (fwidth (+ maxlen 3 1 3))
12516 (ncol (/ (- (window-width) 4) fwidth))
12517 tg cnt e c tbl
12518 groups ingroup)
12519 (save-excursion
12520 (save-window-excursion
12521 (if expert
12522 (set-buffer (get-buffer-create " *Org todo*"))
12523 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12524 (erase-buffer)
12525 (setq-local org-done-keywords done-keywords)
12526 (setq tbl fulltable cnt 0)
12527 (while (setq e (pop tbl))
12528 (cond
12529 ((equal e '(:startgroup))
12530 (push '() groups) (setq ingroup t)
12531 (unless (= cnt 0)
12532 (setq cnt 0)
12533 (insert "\n"))
12534 (insert "{ "))
12535 ((equal e '(:endgroup))
12536 (setq ingroup nil cnt 0)
12537 (insert "}\n"))
12538 ((equal e '(:newline))
12539 (unless (= cnt 0)
12540 (setq cnt 0)
12541 (insert "\n")
12542 (setq e (car tbl))
12543 (while (equal (car tbl) '(:newline))
12544 (insert "\n")
12545 (setq tbl (cdr tbl)))))
12547 (setq tg (car e) c (cdr e))
12548 (when ingroup (push tg (car groups)))
12549 (setq tg (org-add-props tg nil 'face
12550 (org-get-todo-face tg)))
12551 (when (and (= cnt 0) (not ingroup)) (insert " "))
12552 (insert "[" c "] " tg (make-string
12553 (- fwidth 4 (length tg)) ?\ ))
12554 (when (= (setq cnt (1+ cnt)) ncol)
12555 (insert "\n")
12556 (when ingroup (insert " "))
12557 (setq cnt 0)))))
12558 (insert "\n")
12559 (goto-char (point-min))
12560 (unless expert (org-fit-window-to-buffer))
12561 (message "[a-z..]:Set [SPC]:clear")
12562 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12563 (cond
12564 ((or (= c ?\C-g)
12565 (and (= c ?q) (not (rassoc c fulltable))))
12566 (setq quit-flag t))
12567 ((= c ?\ ) nil)
12568 ((setq e (rassoc c fulltable) tg (car e))
12570 (t (setq quit-flag t)))))))
12572 (defun org-entry-is-todo-p ()
12573 (member (org-get-todo-state) org-not-done-keywords))
12575 (defun org-entry-is-done-p ()
12576 (member (org-get-todo-state) org-done-keywords))
12578 (defun org-get-todo-state ()
12579 "Return the TODO keyword of the current subtree."
12580 (save-excursion
12581 (org-back-to-heading t)
12582 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12583 (match-end 2)
12584 (match-string 2))))
12586 (defun org-at-date-range-p (&optional inactive-ok)
12587 "Non-nil if point is inside a date range.
12589 When optional argument INACTIVE-OK is non-nil, also consider
12590 inactive time ranges.
12592 When this function returns a non-nil value, match data is set
12593 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12594 on INACTIVE-OK."
12595 (interactive)
12596 (save-excursion
12597 (catch 'exit
12598 (let ((pos (point)))
12599 (skip-chars-backward "^[<\r\n")
12600 (skip-chars-backward "<[")
12601 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12602 (>= (match-end 0) pos)
12603 (throw 'exit t))
12604 (skip-chars-backward "^<[\r\n")
12605 (skip-chars-backward "<[")
12606 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12607 (>= (match-end 0) pos)
12608 (throw 'exit t)))
12609 nil)))
12611 (defun org-get-repeat (&optional timestamp)
12612 "Check if there is a time-stamp with repeater in this entry.
12614 Return the repeater, as a string, or nil. Also return nil when
12615 this function is called before first heading.
12617 When optional argument TIMESTAMP is a string, extract the
12618 repeater from there instead."
12619 (save-match-data
12620 (cond (timestamp
12621 (and (string-match org-repeat-re timestamp)
12622 (match-string-no-properties 1 timestamp)))
12623 ((org-before-first-heading-p) nil)
12625 (save-excursion
12626 (org-back-to-heading t)
12627 (let ((end (org-entry-end-position)))
12628 (catch :repeat
12629 (while (re-search-forward org-repeat-re end t)
12630 (when (save-match-data (org-at-timestamp-p 'agenda))
12631 (throw :repeat (match-string-no-properties 1)))))))))))
12633 (defvar org-last-changed-timestamp)
12634 (defvar org-last-inserted-timestamp)
12635 (defvar org-log-post-message)
12636 (defvar org-log-note-purpose)
12637 (defvar org-log-note-how nil)
12638 (defvar org-log-note-extra)
12639 (defun org-auto-repeat-maybe (done-word)
12640 "Check if the current headline contains a repeated time-stamp.
12642 If yes, set TODO state back to what it was and change the base date
12643 of repeating deadline/scheduled time stamps to new date.
12645 This function is run automatically after each state change to a DONE state."
12646 (let* ((repeat (org-get-repeat))
12647 (aa (assoc org-last-state org-todo-kwd-alist))
12648 (interpret (nth 1 aa))
12649 (head (nth 2 aa))
12650 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12651 (msg "Entry repeats: ")
12652 (org-log-done nil)
12653 (org-todo-log-states nil)
12654 (end (copy-marker (org-entry-end-position))))
12655 (unwind-protect
12656 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12657 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12658 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12659 (and (stringp org-todo-repeat-to-state)
12660 org-todo-repeat-to-state)
12661 (and org-todo-repeat-to-state org-last-state))))
12662 (org-todo (cond
12663 ((and to-state (member to-state org-todo-keywords-1))
12664 to-state)
12665 ((eq interpret 'type) org-last-state)
12666 (head)
12667 (t 'none))))
12668 (org-back-to-heading t)
12669 (org-add-planning-info nil nil 'closed)
12670 ;; When `org-log-repeat' is non-nil or entry contains
12671 ;; a clock, set LAST_REPEAT property.
12672 (when (or org-log-repeat
12673 (catch :clock
12674 (save-excursion
12675 (while (re-search-forward org-clock-line-re end t)
12676 (when (org-at-clock-log-p) (throw :clock t))))))
12677 (org-entry-put nil "LAST_REPEAT" (format-time-string
12678 (org-time-stamp-format t t)
12679 (current-time))))
12680 (when org-log-repeat
12681 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12682 (memq 'org-add-log-note post-command-hook))
12683 ;; We are already setup for some record.
12684 (when (eq org-log-repeat 'note)
12685 ;; Make sure we take a note, not only a time stamp.
12686 (setq org-log-note-how 'note))
12687 ;; Set up for taking a record.
12688 (org-add-log-setup 'state
12689 (or done-word (car org-done-keywords))
12690 org-last-state
12691 org-log-repeat)))
12692 (let ((planning-re (regexp-opt
12693 (list org-scheduled-string org-deadline-string))))
12694 (while (re-search-forward org-ts-regexp end t)
12695 (let* ((ts (match-string 0))
12696 (planning? (org-at-planning-p))
12697 (type (if (not planning?) "Plain:"
12698 (save-excursion
12699 (re-search-backward
12700 planning-re (line-beginning-position) t)
12701 (match-string 0)))))
12702 (cond
12703 ;; Ignore fake time-stamps (e.g., within comments).
12704 ((not (org-at-timestamp-p 'agenda)))
12705 ;; Time-stamps without a repeater are usually
12706 ;; skipped. However, a SCHEDULED time-stamp without
12707 ;; one is removed, as they are no longer relevant.
12708 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12709 ts))
12710 (when (equal type org-scheduled-string)
12711 (org-remove-timestamp-with-keyword type)))
12713 (let ((n (string-to-number (match-string 2 ts)))
12714 (what (match-string 3 ts)))
12715 (when (equal what "w") (setq n (* n 7) what "d"))
12716 (when (and (equal what "h")
12717 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12718 ts)))
12719 (user-error
12720 "Cannot repeat in Repeat in %d hour(s) because no hour \
12721 has been set"
12723 ;; Preparation, see if we need to modify the start
12724 ;; date for the change.
12725 (when (match-end 1)
12726 (let ((time (save-match-data
12727 (org-time-string-to-time ts))))
12728 (cond
12729 ((equal (match-string 1 ts) ".")
12730 ;; Shift starting date to today
12731 (org-timestamp-change
12732 (- (org-today) (time-to-days time))
12733 'day))
12734 ((equal (match-string 1 ts) "+")
12735 (let ((nshiftmax 10)
12736 (nshift 0))
12737 (while (or (= nshift 0)
12738 (not (time-less-p (current-time) time)))
12739 (when (= (cl-incf nshift) nshiftmax)
12740 (or (y-or-n-p
12741 (format "%d repeater intervals were not \
12742 enough to shift date past today. Continue? "
12743 nshift))
12744 (user-error "Abort")))
12745 (org-timestamp-change n (cdr (assoc what whata)))
12746 (org-in-regexp org-ts-regexp3)
12747 (setq ts (match-string 1))
12748 (setq time
12749 (save-match-data
12750 (org-time-string-to-time ts)))))
12751 (org-timestamp-change (- n) (cdr (assoc what whata)))
12752 ;; Rematch, so that we have everything in place
12753 ;; for the real shift.
12754 (org-in-regexp org-ts-regexp3)
12755 (setq ts (match-string 1))
12756 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12757 ts)))))
12758 (save-excursion
12759 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12760 (setq msg
12761 (concat
12762 msg type " " org-last-changed-timestamp " "))))))))
12763 (setq org-log-post-message msg)
12764 (message "%s" msg))
12765 (set-marker end nil))))
12767 (defun org-show-todo-tree (arg)
12768 "Make a compact tree which shows all headlines marked with TODO.
12769 The tree will show the lines where the regexp matches, and all higher
12770 headlines above the match.
12771 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12772 With a numeric prefix N, construct a sparse tree for the Nth element
12773 of `org-todo-keywords-1'."
12774 (interactive "P")
12775 (let ((case-fold-search nil)
12776 (kwd-re
12777 (cond ((null arg) org-not-done-regexp)
12778 ((equal arg '(4))
12779 (let ((kwd
12780 (completing-read "Keyword (or KWD1|KWD2|...): "
12781 (mapcar #'list org-todo-keywords-1))))
12782 (concat "\\("
12783 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12784 "\\)\\>")))
12785 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12786 (regexp-quote (nth (1- (prefix-numeric-value arg))
12787 org-todo-keywords-1)))
12788 (t (user-error "Invalid prefix argument: %s" arg)))))
12789 (message "%d TODO entries found"
12790 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12792 (defun org--deadline-or-schedule (arg type time)
12793 "Insert DEADLINE or SCHEDULE information in current entry.
12794 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12795 `org-schedule' for information about ARG and TIME arguments."
12796 (let* ((deadline? (eq type 'deadline))
12797 (keyword (if deadline? org-deadline-string org-scheduled-string))
12798 (log (if deadline? org-log-redeadline org-log-reschedule))
12799 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12800 (old-date-time (and old-date (org-time-string-to-time old-date)))
12801 ;; Save repeater cookie from either TIME or current scheduled
12802 ;; time stamp. We are going to insert it back at the end of
12803 ;; the process.
12804 (repeater (or (and (org-string-nw-p time)
12805 ;; We use `org-repeat-re' because we need
12806 ;; to tell the difference between a real
12807 ;; repeater and a time delta, e.g. "+2d".
12808 (string-match org-repeat-re time)
12809 (match-string 1 time))
12810 (and (org-string-nw-p old-date)
12811 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12812 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12813 old-date)
12814 (match-string 1 old-date)))))
12815 (pcase arg
12816 (`(4)
12817 (when (and old-date log)
12818 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12819 nil old-date log))
12820 (org-remove-timestamp-with-keyword keyword)
12821 (message (if deadline? "Item no longer has a deadline."
12822 "Item is no longer scheduled.")))
12823 (`(16)
12824 (save-excursion
12825 (org-back-to-heading t)
12826 (let ((regexp (if deadline? org-deadline-time-regexp
12827 org-scheduled-time-regexp)))
12828 (if (not (re-search-forward regexp (line-end-position 2) t))
12829 (user-error (if deadline? "No deadline information to update"
12830 "No scheduled information to update"))
12831 (let* ((rpl0 (match-string 1))
12832 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12833 (msg (if deadline? "Warn starting from" "Delay until")))
12834 (replace-match
12835 (concat keyword
12836 " <" rpl
12837 (format " -%dd"
12838 (abs (- (time-to-days
12839 (save-match-data
12840 (org-read-date
12841 nil t nil msg old-date-time)))
12842 (time-to-days old-date-time))))
12843 ">") t t))))))
12845 (org-add-planning-info type time 'closed)
12846 (when (and old-date
12848 (not (equal old-date org-last-inserted-timestamp)))
12849 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12850 org-last-inserted-timestamp
12851 old-date
12852 log))
12853 (when repeater
12854 (save-excursion
12855 (org-back-to-heading t)
12856 (when (re-search-forward
12857 (concat keyword " " org-last-inserted-timestamp)
12858 (line-end-position 2)
12860 (goto-char (1- (match-end 0)))
12861 (insert " " repeater)
12862 (setq org-last-inserted-timestamp
12863 (concat (substring org-last-inserted-timestamp 0 -1)
12864 " " repeater
12865 (substring org-last-inserted-timestamp -1))))))
12866 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12867 org-last-inserted-timestamp)))))
12869 (defun org-deadline (arg &optional time)
12870 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12871 With one universal prefix argument, remove any deadline from the item.
12872 With two universal prefix arguments, prompt for a warning delay.
12873 With argument TIME, set the deadline at the corresponding date. TIME
12874 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12875 (interactive "P")
12876 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12877 (org-map-entries
12878 (lambda () (org--deadline-or-schedule arg 'deadline time))
12880 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12881 'region-start-level
12882 'region)
12883 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12884 (org--deadline-or-schedule arg 'deadline time)))
12886 (defun org-schedule (arg &optional time)
12887 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12888 With one universal prefix argument, remove any scheduling date from the item.
12889 With two universal prefix arguments, prompt for a delay cookie.
12890 With argument TIME, scheduled at the corresponding date. TIME can
12891 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12892 (interactive "P")
12893 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12894 (org-map-entries
12895 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12897 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12898 'region-start-level
12899 'region)
12900 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12901 (org--deadline-or-schedule arg 'scheduled time)))
12903 (defun org-get-scheduled-time (pom &optional inherit)
12904 "Get the scheduled time as a time tuple, of a format suitable
12905 for calling org-schedule with, or if there is no scheduling,
12906 returns nil."
12907 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12908 (when time
12909 (apply 'encode-time (org-parse-time-string time)))))
12911 (defun org-get-deadline-time (pom &optional inherit)
12912 "Get the deadline as a time tuple, of a format suitable for
12913 calling org-deadline with, or if there is no scheduling, returns
12914 nil."
12915 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12916 (when time
12917 (apply 'encode-time (org-parse-time-string time)))))
12919 (defun org-remove-timestamp-with-keyword (keyword)
12920 "Remove all time stamps with KEYWORD in the current entry."
12921 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12922 beg)
12923 (save-excursion
12924 (org-back-to-heading t)
12925 (setq beg (point))
12926 (outline-next-heading)
12927 (while (re-search-backward re beg t)
12928 (replace-match "")
12929 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12930 (equal (char-before) ?\ ))
12931 (backward-delete-char 1)
12932 (when (string-match "^[ \t]*$" (buffer-substring
12933 (point-at-bol) (point-at-eol)))
12934 (delete-region (point-at-bol)
12935 (min (point-max) (1+ (point-at-eol))))))))))
12937 (defvar org-time-was-given) ; dynamically scoped parameter
12938 (defvar org-end-time-was-given) ; dynamically scoped parameter
12940 (defun org-at-planning-p ()
12941 "Non-nil when point is on a planning info line."
12942 ;; This is as accurate and faster than `org-element-at-point' since
12943 ;; planning info location is fixed in the section.
12944 (org-with-wide-buffer
12945 (beginning-of-line)
12946 (and (looking-at-p org-planning-line-re)
12947 (eq (point)
12948 (ignore-errors
12949 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12950 (org-back-to-heading t)
12951 (org-with-limited-levels (org-back-to-heading t)))
12952 (line-beginning-position 2))))))
12954 (defun org-add-planning-info (what &optional time &rest remove)
12955 "Insert new timestamp with keyword in the planning line.
12956 WHAT indicates what kind of time stamp to add. It is a symbol
12957 among `closed', `deadline', `scheduled' and nil. TIME indicates
12958 the time to use. If none is given, the user is prompted for
12959 a date. REMOVE indicates what kind of entries to remove. An old
12960 WHAT entry will also be removed."
12961 (let (org-time-was-given org-end-time-was-given default-time default-input)
12962 (catch 'exit
12963 (when (and (memq what '(scheduled deadline))
12964 (or (not time)
12965 (and (stringp time)
12966 (string-match "^[-+]+[0-9]" time))))
12967 ;; Try to get a default date/time from existing timestamp
12968 (save-excursion
12969 (org-back-to-heading t)
12970 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12971 (when (re-search-forward (if (eq what 'scheduled)
12972 org-scheduled-time-regexp
12973 org-deadline-time-regexp)
12974 end t)
12975 (setq ts (match-string 1)
12976 default-time (apply 'encode-time (org-parse-time-string ts))
12977 default-input (and ts (org-get-compact-tod ts)))))))
12978 (when what
12979 (setq time
12980 (if (stringp time)
12981 ;; This is a string (relative or absolute), set
12982 ;; proper date.
12983 (apply #'encode-time
12984 (org-read-date-analyze
12985 time default-time (decode-time default-time)))
12986 ;; If necessary, get the time from the user
12987 (or time (org-read-date nil 'to-time nil nil
12988 default-time default-input)))))
12990 (org-with-wide-buffer
12991 (org-back-to-heading t)
12992 (forward-line)
12993 (unless (bolp) (insert "\n"))
12994 (cond ((looking-at-p org-planning-line-re)
12995 ;; Move to current indentation.
12996 (skip-chars-forward " \t")
12997 ;; Check if we have to remove something.
12998 (dolist (type (if what (cons what remove) remove))
12999 (save-excursion
13000 (when (re-search-forward
13001 (cl-case type
13002 (closed org-closed-time-regexp)
13003 (deadline org-deadline-time-regexp)
13004 (scheduled org-scheduled-time-regexp)
13005 (otherwise
13006 (error "Invalid planning type: %s" type)))
13007 (line-end-position) t)
13008 ;; Delete until next keyword or end of line.
13009 (delete-region
13010 (match-beginning 0)
13011 (if (re-search-forward org-keyword-time-not-clock-regexp
13012 (line-end-position)
13014 (match-beginning 0)
13015 (line-end-position))))))
13016 ;; If there is nothing more to add and no more keyword
13017 ;; is left, remove the line completely.
13018 (if (and (looking-at-p "[ \t]*$") (not what))
13019 (delete-region (line-beginning-position)
13020 (line-beginning-position 2))
13021 ;; If we removed last keyword, do not leave trailing
13022 ;; white space at the end of line.
13023 (let ((p (point)))
13024 (save-excursion
13025 (end-of-line)
13026 (unless (= (skip-chars-backward " \t" p) 0)
13027 (delete-region (point) (line-end-position)))))))
13028 ((not what) (throw 'exit nil)) ; Nothing to do.
13029 (t (insert-before-markers "\n")
13030 (backward-char 1)
13031 (when org-adapt-indentation
13032 (indent-to-column (1+ (org-outline-level))))))
13033 (when what
13034 ;; Insert planning keyword.
13035 (insert (cl-case what
13036 (closed org-closed-string)
13037 (deadline org-deadline-string)
13038 (scheduled org-scheduled-string)
13039 (otherwise (error "Invalid planning type: %s" what)))
13040 " ")
13041 ;; Insert associated timestamp.
13042 (let ((ts (org-insert-time-stamp
13043 time
13044 (or org-time-was-given
13045 (and (eq what 'closed) org-log-done-with-time))
13046 (eq what 'closed)
13047 nil nil (list org-end-time-was-given))))
13048 (unless (eolp) (insert " "))
13049 ts))))))
13051 (defvar org-log-note-marker (make-marker)
13052 "Marker pointing at the entry where the note is to be inserted.")
13053 (defvar org-log-note-purpose nil)
13054 (defvar org-log-note-state nil)
13055 (defvar org-log-note-previous-state nil)
13056 (defvar org-log-note-extra nil)
13057 (defvar org-log-note-window-configuration nil)
13058 (defvar org-log-note-return-to (make-marker))
13059 (defvar org-log-note-effective-time nil
13060 "Remembered current time so that dynamically scoped
13061 `org-extend-today-until' affects timestamps in state change log")
13063 (defvar org-log-post-message nil
13064 "Message to be displayed after a log note has been stored.
13065 The auto-repeater uses this.")
13067 (defun org-add-note ()
13068 "Add a note to the current entry.
13069 This is done in the same way as adding a state change note."
13070 (interactive)
13071 (org-add-log-setup 'note))
13073 (defun org-log-beginning (&optional create)
13074 "Return expected start of log notes in current entry.
13075 When optional argument CREATE is non-nil, the function creates
13076 a drawer to store notes, if necessary. Returned position ignores
13077 narrowing."
13078 (org-with-wide-buffer
13079 (let ((drawer (org-log-into-drawer)))
13080 (cond
13081 (drawer
13082 (org-end-of-meta-data)
13083 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13084 (end (if (org-at-heading-p) (point)
13085 (save-excursion (outline-next-heading) (point))))
13086 (case-fold-search t))
13087 (catch 'exit
13088 ;; Try to find existing drawer.
13089 (while (re-search-forward regexp end t)
13090 (let ((element (org-element-at-point)))
13091 (when (eq (org-element-type element) 'drawer)
13092 (let ((cend (org-element-property :contents-end element)))
13093 (when (and (not org-log-states-order-reversed) cend)
13094 (goto-char cend)))
13095 (throw 'exit nil))))
13096 ;; No drawer found. Create one, if permitted.
13097 (when create
13098 (unless (bolp) (insert "\n"))
13099 (let ((beg (point)))
13100 (insert ":" drawer ":\n:END:\n")
13101 (org-indent-region beg (point))
13102 (org-flag-region
13103 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13104 (end-of-line -1)))))
13106 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13107 (skip-chars-forward " \t\n")
13108 (beginning-of-line)
13109 (unless org-log-states-order-reversed
13110 (org-skip-over-state-notes)
13111 (skip-chars-backward " \t\n")
13112 (forward-line)))))
13113 (if (bolp) (point) (line-beginning-position 2))))
13115 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13116 "Set up the post command hook to take a note.
13117 If this is about to TODO state change, the new state is expected in STATE.
13118 HOW is an indicator what kind of note should be created.
13119 EXTRA is additional text that will be inserted into the notes buffer."
13120 (move-marker org-log-note-marker (point))
13121 (setq org-log-note-purpose purpose
13122 org-log-note-state state
13123 org-log-note-previous-state prev-state
13124 org-log-note-how how
13125 org-log-note-extra extra
13126 org-log-note-effective-time (org-current-effective-time))
13127 (add-hook 'post-command-hook 'org-add-log-note 'append))
13129 (defun org-skip-over-state-notes ()
13130 "Skip past the list of State notes in an entry."
13131 (when (ignore-errors (goto-char (org-in-item-p)))
13132 (let* ((struct (org-list-struct))
13133 (prevs (org-list-prevs-alist struct))
13134 (regexp
13135 (concat "[ \t]*- +"
13136 (replace-regexp-in-string
13137 " +" " +"
13138 (org-replace-escapes
13139 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13140 `(("%d" . ,org-ts-regexp-inactive)
13141 ("%D" . ,org-ts-regexp)
13142 ("%s" . "\"\\S-+\"")
13143 ("%S" . "\"\\S-+\"")
13144 ("%t" . ,org-ts-regexp-inactive)
13145 ("%T" . ,org-ts-regexp)
13146 ("%u" . ".*?")
13147 ("%U" . ".*?")))))))
13148 (while (looking-at-p regexp)
13149 (goto-char (or (org-list-get-next-item (point) struct prevs)
13150 (org-list-get-item-end (point) struct)))))))
13152 (defun org-add-log-note (&optional _purpose)
13153 "Pop up a window for taking a note, and add this note later."
13154 (remove-hook 'post-command-hook 'org-add-log-note)
13155 (setq org-log-note-window-configuration (current-window-configuration))
13156 (delete-other-windows)
13157 (move-marker org-log-note-return-to (point))
13158 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13159 (goto-char org-log-note-marker)
13160 (org-switch-to-buffer-other-window "*Org Note*")
13161 (erase-buffer)
13162 (if (memq org-log-note-how '(time state))
13163 (org-store-log-note)
13164 (let ((org-inhibit-startup t)) (org-mode))
13165 (insert (format "# Insert note for %s.
13166 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13167 (cond
13168 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13169 ((eq org-log-note-purpose 'done) "closed todo item")
13170 ((eq org-log-note-purpose 'state)
13171 (format "state change from \"%s\" to \"%s\""
13172 (or org-log-note-previous-state "")
13173 (or org-log-note-state "")))
13174 ((eq org-log-note-purpose 'reschedule)
13175 "rescheduling")
13176 ((eq org-log-note-purpose 'delschedule)
13177 "no longer scheduled")
13178 ((eq org-log-note-purpose 'redeadline)
13179 "changing deadline")
13180 ((eq org-log-note-purpose 'deldeadline)
13181 "removing deadline")
13182 ((eq org-log-note-purpose 'refile)
13183 "refiling")
13184 ((eq org-log-note-purpose 'note)
13185 "this entry")
13186 (t (error "This should not happen")))))
13187 (when org-log-note-extra (insert org-log-note-extra))
13188 (setq-local org-finish-function 'org-store-log-note)
13189 (run-hooks 'org-log-buffer-setup-hook)))
13191 (defvar org-note-abort nil) ; dynamically scoped
13192 (defun org-store-log-note ()
13193 "Finish taking a log note, and insert it to where it belongs."
13194 (let ((txt (prog1 (buffer-string)
13195 (kill-buffer)))
13196 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13197 lines)
13198 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13199 (setq txt (replace-match "" t t txt)))
13200 (when (string-match "\\s-+\\'" txt)
13201 (setq txt (replace-match "" t t txt)))
13202 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13203 (when (org-string-nw-p note)
13204 (setq note
13205 (org-replace-escapes
13206 note
13207 (list (cons "%u" (user-login-name))
13208 (cons "%U" user-full-name)
13209 (cons "%t" (format-time-string
13210 (org-time-stamp-format 'long 'inactive)
13211 org-log-note-effective-time))
13212 (cons "%T" (format-time-string
13213 (org-time-stamp-format 'long nil)
13214 org-log-note-effective-time))
13215 (cons "%d" (format-time-string
13216 (org-time-stamp-format nil 'inactive)
13217 org-log-note-effective-time))
13218 (cons "%D" (format-time-string
13219 (org-time-stamp-format nil nil)
13220 org-log-note-effective-time))
13221 (cons "%s" (cond
13222 ((not org-log-note-state) "")
13223 ((string-match-p org-ts-regexp
13224 org-log-note-state)
13225 (format "\"[%s]\""
13226 (substring org-log-note-state 1 -1)))
13227 (t (format "\"%s\"" org-log-note-state))))
13228 (cons "%S"
13229 (cond
13230 ((not org-log-note-previous-state) "")
13231 ((string-match-p org-ts-regexp
13232 org-log-note-previous-state)
13233 (format "\"[%s]\""
13234 (substring
13235 org-log-note-previous-state 1 -1)))
13236 (t (format "\"%s\""
13237 org-log-note-previous-state)))))))
13238 (when lines (setq note (concat note " \\\\")))
13239 (push note lines))
13240 (when (and lines (not org-note-abort))
13241 (with-current-buffer (marker-buffer org-log-note-marker)
13242 (org-with-wide-buffer
13243 ;; Find location for the new note.
13244 (goto-char org-log-note-marker)
13245 (set-marker org-log-note-marker nil)
13246 ;; Note associated to a clock is to be located right after
13247 ;; the clock. Do not move point.
13248 (unless (eq org-log-note-purpose 'clock-out)
13249 (goto-char (org-log-beginning t)))
13250 ;; Make sure point is at the beginning of an empty line.
13251 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13252 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13253 ;; In an existing list, add a new item at the top level.
13254 ;; Otherwise, indent line like a regular one.
13255 (let ((itemp (org-in-item-p)))
13256 (if itemp
13257 (indent-line-to
13258 (let ((struct (save-excursion
13259 (goto-char itemp) (org-list-struct))))
13260 (org-list-get-ind (org-list-get-top-point struct) struct)))
13261 (org-indent-line)))
13262 (insert (org-list-bullet-string "-") (pop lines))
13263 (let ((ind (org-list-item-body-column (line-beginning-position))))
13264 (dolist (line lines)
13265 (insert "\n")
13266 (indent-line-to ind)
13267 (insert line)))
13268 (message "Note stored")
13269 (org-back-to-heading t))
13270 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13271 ;; from within `org-add-log-note' because `buffer-undo-list'
13272 ;; is then modified outside of `org-with-remote-undo'.
13273 (when (eq this-command 'org-agenda-todo)
13274 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13275 ;; Don't add undo information when called from `org-agenda-todo'.
13276 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13277 (set-window-configuration org-log-note-window-configuration)
13278 (with-current-buffer (marker-buffer org-log-note-return-to)
13279 (goto-char org-log-note-return-to))
13280 (move-marker org-log-note-return-to nil)
13281 (when org-log-post-message (message "%s" org-log-post-message))))
13283 (defun org-remove-empty-drawer-at (pos)
13284 "Remove an empty drawer at position POS.
13285 POS may also be a marker."
13286 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13287 (org-with-wide-buffer
13288 (goto-char pos)
13289 (let ((drawer (org-element-at-point)))
13290 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13291 (not (org-element-property :contents-begin drawer)))
13292 (delete-region (org-element-property :begin drawer)
13293 (progn (goto-char (org-element-property :end drawer))
13294 (skip-chars-backward " \r\t\n")
13295 (forward-line)
13296 (point))))))))
13298 (defvar org-ts-type nil)
13299 (defun org-sparse-tree (&optional arg type)
13300 "Create a sparse tree, prompt for the details.
13301 This command can create sparse trees. You first need to select the type
13302 of match used to create the tree:
13304 t Show all TODO entries.
13305 T Show entries with a specific TODO keyword.
13306 m Show entries selected by a tags/property match.
13307 p Enter a property name and its value (both with completion on existing
13308 names/values) and show entries with that property.
13309 r Show entries matching a regular expression (`/' can be used as well).
13310 b Show deadlines and scheduled items before a date.
13311 a Show deadlines and scheduled items after a date.
13312 d Show deadlines due within `org-deadline-warning-days'.
13313 D Show deadlines and scheduled items between a date range."
13314 (interactive "P")
13315 (setq type (or type org-sparse-tree-default-date-type))
13316 (setq org-ts-type type)
13317 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13318 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13319 \[c]ycle through date types: %s"
13320 (cl-case type
13321 (all "all timestamps")
13322 (scheduled "only scheduled")
13323 (deadline "only deadline")
13324 (active "only active timestamps")
13325 (inactive "only inactive timestamps")
13326 (closed "with a closed time-stamp")
13327 (otherwise "scheduled/deadline")))
13328 (let ((answer (read-char-exclusive)))
13329 (cl-case answer
13331 (org-sparse-tree
13333 (cadr
13334 (memq type '(nil all scheduled deadline active inactive closed)))))
13335 (?d (call-interactively 'org-check-deadlines))
13336 (?b (call-interactively 'org-check-before-date))
13337 (?a (call-interactively 'org-check-after-date))
13338 (?D (call-interactively 'org-check-dates-range))
13339 (?t (call-interactively 'org-show-todo-tree))
13340 (?T (org-show-todo-tree '(4)))
13341 (?m (call-interactively 'org-match-sparse-tree))
13342 ((?p ?P)
13343 (let* ((kwd (completing-read
13344 "Property: " (mapcar #'list (org-buffer-property-keys))))
13345 (value (completing-read
13346 "Value: " (mapcar #'list (org-property-values kwd)))))
13347 (unless (string-match "\\`{.*}\\'" value)
13348 (setq value (concat "\"" value "\"")))
13349 (org-match-sparse-tree arg (concat kwd "=" value))))
13350 ((?r ?R ?/) (call-interactively 'org-occur))
13351 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13353 (defvar-local org-occur-highlights nil
13354 "List of overlays used for occur matches.")
13355 (defvar-local org-occur-parameters nil
13356 "Parameters of the active org-occur calls.
13357 This is a list, each call to org-occur pushes as cons cell,
13358 containing the regular expression and the callback, onto the list.
13359 The list can contain several entries if `org-occur' has been called
13360 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13361 will only contain one set of parameters. When the highlights are
13362 removed (for example with `C-c C-c', or with the next edit (depending
13363 on `org-remove-highlights-with-change'), this variable is emptied
13364 as well.")
13366 (defun org-occur (regexp &optional keep-previous callback)
13367 "Make a compact tree which shows all matches of REGEXP.
13369 The tree will show the lines where the regexp matches, and any other context
13370 defined in `org-show-context-detail', which see.
13372 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13373 done by a previous call to `org-occur' will be kept, to allow stacking of
13374 calls to this command.
13376 Optional argument CALLBACK can be a function of no argument. In this case,
13377 it is called with point at the end of the match, match data being set
13378 accordingly. Current match is shown only if the return value is non-nil.
13379 The function must neither move point nor alter narrowing."
13380 (interactive "sRegexp: \nP")
13381 (when (equal regexp "")
13382 (user-error "Regexp cannot be empty"))
13383 (unless keep-previous
13384 (org-remove-occur-highlights nil nil t))
13385 (push (cons regexp callback) org-occur-parameters)
13386 (let ((cnt 0))
13387 (save-excursion
13388 (goto-char (point-min))
13389 (when (or (not keep-previous) ; do not want to keep
13390 (not org-occur-highlights)) ; no previous matches
13391 ;; hide everything
13392 (org-overview))
13393 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13394 (isearch-no-upper-case-p regexp t)
13395 org-occur-case-fold-search)))
13396 (while (re-search-forward regexp nil t)
13397 (when (or (not callback)
13398 (save-match-data (funcall callback)))
13399 (setq cnt (1+ cnt))
13400 (when org-highlight-sparse-tree-matches
13401 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13402 (org-show-context 'occur-tree)))))
13403 (when org-remove-highlights-with-change
13404 (add-hook 'before-change-functions 'org-remove-occur-highlights
13405 nil 'local))
13406 (unless org-sparse-tree-open-archived-trees
13407 (org-hide-archived-subtrees (point-min) (point-max)))
13408 (run-hooks 'org-occur-hook)
13409 (when (called-interactively-p 'interactive)
13410 (message "%d match(es) for regexp %s" cnt regexp))
13411 cnt))
13413 (defun org-occur-next-match (&optional n _reset)
13414 "Function for `next-error-function' to find sparse tree matches.
13415 N is the number of matches to move, when negative move backwards.
13416 This function always goes back to the starting point when no
13417 match is found."
13418 (let* ((limit (if (< n 0) (point-min) (point-max)))
13419 (search-func (if (< n 0)
13420 'previous-single-char-property-change
13421 'next-single-char-property-change))
13422 (n (abs n))
13423 (pos (point))
13425 (catch 'exit
13426 (while (setq p1 (funcall search-func (point) 'org-type))
13427 (when (equal p1 limit)
13428 (goto-char pos)
13429 (user-error "No more matches"))
13430 (when (equal (get-char-property p1 'org-type) 'org-occur)
13431 (setq n (1- n))
13432 (when (= n 0)
13433 (goto-char p1)
13434 (throw 'exit (point))))
13435 (goto-char p1))
13436 (goto-char p1)
13437 (user-error "No more matches"))))
13439 (defun org-highlight-new-match (beg end)
13440 "Highlight from BEG to END and mark the highlight is an occur headline."
13441 (let ((ov (make-overlay beg end)))
13442 (overlay-put ov 'face 'secondary-selection)
13443 (overlay-put ov 'org-type 'org-occur)
13444 (push ov org-occur-highlights)))
13446 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13447 "Remove the occur highlights from the buffer.
13448 BEG and END are ignored. If NOREMOVE is nil, remove this function
13449 from the `before-change-functions' in the current buffer."
13450 (interactive)
13451 (unless org-inhibit-highlight-removal
13452 (mapc #'delete-overlay org-occur-highlights)
13453 (setq org-occur-highlights nil)
13454 (setq org-occur-parameters nil)
13455 (unless noremove
13456 (remove-hook 'before-change-functions
13457 'org-remove-occur-highlights 'local))))
13459 ;;;; Priorities
13461 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13462 "Regular expression matching the priority indicator.")
13464 (defvar org-remove-priority-next-time nil)
13466 (defun org-priority-up ()
13467 "Increase the priority of the current item."
13468 (interactive)
13469 (org-priority 'up))
13471 (defun org-priority-down ()
13472 "Decrease the priority of the current item."
13473 (interactive)
13474 (org-priority 'down))
13476 (defun org-priority (&optional action _show)
13477 "Change the priority of an item.
13478 ACTION can be `set', `up', `down', or a character."
13479 (interactive "P")
13480 (if (equal action '(4))
13481 (org-show-priority)
13482 (unless org-enable-priority-commands
13483 (user-error "Priority commands are disabled"))
13484 (setq action (or action 'set))
13485 (let (current new news have remove)
13486 (save-excursion
13487 (org-back-to-heading t)
13488 (when (looking-at org-priority-regexp)
13489 (setq current (string-to-char (match-string 2))
13490 have t))
13491 (cond
13492 ((eq action 'remove)
13493 (setq remove t new ?\ ))
13494 ((or (eq action 'set)
13495 (integerp action))
13496 (if (not (eq action 'set))
13497 (setq new action)
13498 (message "Priority %c-%c, SPC to remove: "
13499 org-highest-priority org-lowest-priority)
13500 (save-match-data
13501 (setq new (read-char-exclusive))))
13502 (when (and (= (upcase org-highest-priority) org-highest-priority)
13503 (= (upcase org-lowest-priority) org-lowest-priority))
13504 (setq new (upcase new)))
13505 (cond ((equal new ?\ ) (setq remove t))
13506 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13507 (user-error "Priority must be between `%c' and `%c'"
13508 org-highest-priority org-lowest-priority))))
13509 ((eq action 'up)
13510 (setq new (if have
13511 (1- current) ; normal cycling
13512 ;; last priority was empty
13513 (if (eq last-command this-command)
13514 org-lowest-priority ; wrap around empty to lowest
13515 ;; default
13516 (if org-priority-start-cycle-with-default
13517 org-default-priority
13518 (1- org-default-priority))))))
13519 ((eq action 'down)
13520 (setq new (if have
13521 (1+ current) ; normal cycling
13522 ;; last priority was empty
13523 (if (eq last-command this-command)
13524 org-highest-priority ; wrap around empty to highest
13525 ;; default
13526 (if org-priority-start-cycle-with-default
13527 org-default-priority
13528 (1+ org-default-priority))))))
13529 (t (user-error "Invalid action")))
13530 (when (or (< (upcase new) org-highest-priority)
13531 (> (upcase new) org-lowest-priority))
13532 (if (and (memq action '(up down))
13533 (not have) (not (eq last-command this-command)))
13534 ;; `new' is from default priority
13535 (error
13536 "The default can not be set, see `org-default-priority' why")
13537 ;; normal cycling: `new' is beyond highest/lowest priority
13538 ;; and is wrapped around to the empty priority
13539 (setq remove t)))
13540 (setq news (format "%c" new))
13541 (if have
13542 (if remove
13543 (replace-match "" t t nil 1)
13544 (replace-match news t t nil 2))
13545 (if remove
13546 (user-error "No priority cookie found in line")
13547 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13548 (if (match-end 2)
13549 (progn
13550 (goto-char (match-end 2))
13551 (insert " [#" news "]"))
13552 (goto-char (match-beginning 3))
13553 (insert "[#" news "] "))))
13554 (org-set-tags nil 'align))
13555 (if remove
13556 (message "Priority removed")
13557 (message "Priority of current item set to %s" news)))))
13559 (defun org-show-priority ()
13560 "Show the priority of the current item.
13561 This priority is composed of the main priority given with the [#A] cookies,
13562 and by additional input from the age of a schedules or deadline entry."
13563 (interactive)
13564 (let ((pri (if (eq major-mode 'org-agenda-mode)
13565 (org-get-at-bol 'priority)
13566 (save-excursion
13567 (save-match-data
13568 (beginning-of-line)
13569 (and (looking-at org-heading-regexp)
13570 (org-get-priority (match-string 0))))))))
13571 (message "Priority is %d" (if pri pri -1000))))
13573 (defun org-get-priority (s)
13574 "Find priority cookie and return priority."
13575 (save-match-data
13576 (if (functionp org-get-priority-function)
13577 (funcall org-get-priority-function)
13578 (if (not (string-match org-priority-regexp s))
13579 (* 1000 (- org-lowest-priority org-default-priority))
13580 (* 1000 (- org-lowest-priority
13581 (string-to-char (match-string 2 s))))))))
13583 ;;;; Tags
13585 (defvar org-agenda-archives-mode)
13586 (defvar org-map-continue-from nil
13587 "Position from where mapping should continue.
13588 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13590 (defvar org-scanner-tags nil
13591 "The current tag list while the tags scanner is running.")
13593 (defvar org-trust-scanner-tags nil
13594 "Should `org-get-tags-at' use the tags for the scanner.
13595 This is for internal dynamical scoping only.
13596 When this is non-nil, the function `org-get-tags-at' will return the value
13597 of `org-scanner-tags' instead of building the list by itself. This
13598 can lead to large speed-ups when the tags scanner is used in a file with
13599 many entries, and when the list of tags is retrieved, for example to
13600 obtain a list of properties. Building the tags list for each entry in such
13601 a file becomes an N^2 operation - but with this variable set, it scales
13602 as N.")
13604 (defvar org--matcher-tags-todo-only nil)
13606 (defun org-scan-tags (action matcher todo-only &optional start-level)
13607 "Scan headline tags with inheritance and produce output ACTION.
13609 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13610 or `agenda' to produce an entry list for an agenda view. It can also be
13611 a Lisp form or a function that should be called at each matched headline, in
13612 this case the return value is a list of all return values from these calls.
13614 MATCHER is a function accepting three arguments, returning
13615 a non-nil value whenever a given set of tags qualifies a headline
13616 for inclusion. See `org-make-tags-matcher' for more information.
13617 As a special case, it can also be set to t (respectively nil) in
13618 order to match all (respectively none) headline.
13620 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13621 included in the output.
13623 START-LEVEL can be a string with asterisks, reducing the scope to
13624 headlines matching this string."
13625 (require 'org-agenda)
13626 (let* ((re (concat "^"
13627 (if start-level
13628 ;; Get the correct level to match
13629 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13630 org-outline-regexp)
13631 " *\\(\\<\\("
13632 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13633 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13634 (props (list 'face 'default
13635 'done-face 'org-agenda-done
13636 'undone-face 'default
13637 'mouse-face 'highlight
13638 'org-not-done-regexp org-not-done-regexp
13639 'org-todo-regexp org-todo-regexp
13640 'org-complex-heading-regexp org-complex-heading-regexp
13641 'help-echo
13642 (format "mouse-2 or RET jump to Org file %S"
13643 (abbreviate-file-name
13644 (or (buffer-file-name (buffer-base-buffer))
13645 (buffer-name (buffer-base-buffer)))))))
13646 (org-map-continue-from nil)
13647 lspos tags tags-list
13648 (tags-alist (list (cons 0 org-file-tags)))
13649 (llast 0) rtn rtn1 level category i txt
13650 todo marker entry priority
13651 ts-date ts-date-type ts-date-pair)
13652 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13653 (setq action (list 'lambda nil action)))
13654 (save-excursion
13655 (goto-char (point-min))
13656 (when (eq action 'sparse-tree)
13657 (org-overview)
13658 (org-remove-occur-highlights))
13659 (while (let (case-fold-search)
13660 (re-search-forward re nil t))
13661 (setq org-map-continue-from nil)
13662 (catch :skip
13663 ;; Ignore closing parts of inline tasks.
13664 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13665 (throw :skip t))
13666 (setq todo
13667 ;; TODO: is the 1-2 difference a bug?
13668 (when (match-end 1) (match-string-no-properties 2))
13669 tags (when (match-end 4) (match-string-no-properties 4)))
13670 (goto-char (setq lspos (match-beginning 0)))
13671 (setq level (org-reduced-level (org-outline-level))
13672 category (org-get-category))
13673 (when (eq action 'agenda)
13674 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13675 ts-date (car ts-date-pair)
13676 ts-date-type (cdr ts-date-pair)))
13677 (setq i llast llast level)
13678 ;; remove tag lists from same and sublevels
13679 (while (>= i level)
13680 (when (setq entry (assoc i tags-alist))
13681 (setq tags-alist (delete entry tags-alist)))
13682 (setq i (1- i)))
13683 ;; add the next tags
13684 (when tags
13685 (setq tags (org-split-string tags ":")
13686 tags-alist
13687 (cons (cons level tags) tags-alist)))
13688 ;; compile tags for current headline
13689 (setq tags-list
13690 (if org-use-tag-inheritance
13691 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13692 tags)
13693 org-scanner-tags tags-list)
13694 (when org-use-tag-inheritance
13695 (setcdr (car tags-alist)
13696 (mapcar (lambda (x)
13697 (setq x (copy-sequence x))
13698 (org-add-prop-inherited x))
13699 (cdar tags-alist))))
13700 (when (and tags org-use-tag-inheritance
13701 (or (not (eq t org-use-tag-inheritance))
13702 org-tags-exclude-from-inheritance))
13703 ;; Selective inheritance, remove uninherited ones.
13704 (setcdr (car tags-alist)
13705 (org-remove-uninherited-tags (cdar tags-alist))))
13706 (when (and
13708 ;; eval matcher only when the todo condition is OK
13709 (and (or (not todo-only) (member todo org-todo-keywords-1))
13710 (if (functionp matcher)
13711 (let ((case-fold-search t) (org-trust-scanner-tags t))
13712 (funcall matcher todo tags-list level))
13713 matcher))
13715 ;; Call the skipper, but return t if it does not
13716 ;; skip, so that the `and' form continues evaluating.
13717 (progn
13718 (unless (eq action 'sparse-tree) (org-agenda-skip))
13721 ;; Check if timestamps are deselecting this entry
13722 (or (not todo-only)
13723 (and (member todo org-todo-keywords-1)
13724 (or (not org-agenda-tags-todo-honor-ignore-options)
13725 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13727 ;; select this headline
13728 (cond
13729 ((eq action 'sparse-tree)
13730 (and org-highlight-sparse-tree-matches
13731 (org-get-heading) (match-end 0)
13732 (org-highlight-new-match
13733 (match-beginning 1) (match-end 1)))
13734 (org-show-context 'tags-tree))
13735 ((eq action 'agenda)
13736 (setq txt (org-agenda-format-item
13738 (concat
13739 (if (eq org-tags-match-list-sublevels 'indented)
13740 (make-string (1- level) ?.) "")
13741 (org-get-heading))
13742 (make-string level ?\s)
13743 category
13744 tags-list)
13745 priority (org-get-priority txt))
13746 (goto-char lspos)
13747 (setq marker (org-agenda-new-marker))
13748 (org-add-props txt props
13749 'org-marker marker 'org-hd-marker marker 'org-category category
13750 'todo-state todo
13751 'ts-date ts-date
13752 'priority priority
13753 'type (concat "tagsmatch" ts-date-type))
13754 (push txt rtn))
13755 ((functionp action)
13756 (setq org-map-continue-from nil)
13757 (save-excursion
13758 (setq rtn1 (funcall action))
13759 (push rtn1 rtn)))
13760 (t (user-error "Invalid action")))
13762 ;; if we are to skip sublevels, jump to end of subtree
13763 (unless org-tags-match-list-sublevels
13764 (org-end-of-subtree t)
13765 (backward-char 1))))
13766 ;; Get the correct position from where to continue
13767 (if org-map-continue-from
13768 (goto-char org-map-continue-from)
13769 (and (= (point) lspos) (end-of-line 1)))))
13770 (when (and (eq action 'sparse-tree)
13771 (not org-sparse-tree-open-archived-trees))
13772 (org-hide-archived-subtrees (point-min) (point-max)))
13773 (nreverse rtn)))
13775 (defun org-remove-uninherited-tags (tags)
13776 "Remove all tags that are not inherited from the list TAGS."
13777 (cond
13778 ((eq org-use-tag-inheritance t)
13779 (if org-tags-exclude-from-inheritance
13780 (org-delete-all org-tags-exclude-from-inheritance tags)
13781 tags))
13782 ((not org-use-tag-inheritance) nil)
13783 ((stringp org-use-tag-inheritance)
13784 (delq nil (mapcar
13785 (lambda (x)
13786 (if (and (string-match org-use-tag-inheritance x)
13787 (not (member x org-tags-exclude-from-inheritance)))
13788 x nil))
13789 tags)))
13790 ((listp org-use-tag-inheritance)
13791 (delq nil (mapcar
13792 (lambda (x)
13793 (if (member x org-use-tag-inheritance) x nil))
13794 tags)))))
13796 (defun org-match-sparse-tree (&optional todo-only match)
13797 "Create a sparse tree according to tags string MATCH.
13799 MATCH is a string with match syntax. It can contain a selection
13800 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13801 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13802 those. See the manual for details.
13804 If optional argument TODO-ONLY is non-nil, only select lines that
13805 are also TODO tasks."
13806 (interactive "P")
13807 (org-agenda-prepare-buffers (list (current-buffer)))
13808 (let ((org--matcher-tags-todo-only todo-only))
13809 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13810 org--matcher-tags-todo-only)))
13812 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13814 (defvar org-cached-props nil)
13815 (defun org-cached-entry-get (pom property)
13816 (if (or (eq t org-use-property-inheritance)
13817 (and (stringp org-use-property-inheritance)
13818 (let ((case-fold-search t))
13819 (string-match-p org-use-property-inheritance property)))
13820 (and (listp org-use-property-inheritance)
13821 (member-ignore-case property org-use-property-inheritance)))
13822 ;; Caching is not possible, check it directly.
13823 (org-entry-get pom property 'inherit)
13824 ;; Get all properties, so we can do complicated checks easily.
13825 (cdr (assoc-string property
13826 (or org-cached-props
13827 (setq org-cached-props (org-entry-properties pom)))
13828 t))))
13830 (defun org-global-tags-completion-table (&optional files)
13831 "Return the list of all tags in all agenda buffer/files.
13832 Optional FILES argument is a list of files which can be used
13833 instead of the agenda files."
13834 (save-excursion
13835 (org-uniquify
13836 (delq nil
13837 (apply #'append
13838 (mapcar
13839 (lambda (file)
13840 (set-buffer (find-file-noselect file))
13841 (org-tag-add-to-alist
13842 (org-get-buffer-tags)
13843 (mapcar (lambda (x)
13844 (and (stringp (car-safe x))
13845 (list (car-safe x))))
13846 org-current-tag-alist)))
13847 (if (car-safe files) files
13848 (org-agenda-files))))))))
13850 (defun org-make-tags-matcher (match)
13851 "Create the TAGS/TODO matcher form for the selection string MATCH.
13853 Returns a cons of the selection string MATCH and a function
13854 implementing the matcher.
13856 The matcher is to be called at an Org entry, with point on the
13857 headline, and returns non-nil if the entry matches the selection
13858 string MATCH. It must be called with three arguments: the TODO
13859 keyword at the entry (or nil if none), the list of all tags at
13860 the entry including inherited ones and the reduced level of the
13861 headline. Additionally, the category of the entry, if any, must
13862 be specified as the text property `org-category' on the headline.
13864 This function sets the variable `org--matcher-tags-todo-only' to
13865 a non-nil value if the matcher restricts matching to TODO
13866 entries, otherwise it is not touched.
13868 See also `org-scan-tags'."
13869 (unless match
13870 ;; Get a new match request, with completion against the global
13871 ;; tags table and the local tags in current buffer.
13872 (let ((org-last-tags-completion-table
13873 (org-tag-add-to-alist
13874 (org-get-buffer-tags)
13875 (org-global-tags-completion-table))))
13876 (setq match
13877 (completing-read
13878 "Match: "
13879 'org-tags-completion-function nil nil nil 'org-tags-history))))
13881 (let ((match0 match)
13882 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13883 (start 0)
13884 tagsmatch todomatch tagsmatcher todomatcher)
13886 ;; Expand group tags.
13887 (setq match (org-tags-expand match))
13889 ;; Check if there is a TODO part of this match, which would be the
13890 ;; part after a "/". To make sure that this slash is not part of
13891 ;; a property value to be matched against, we also check that
13892 ;; there is no / after that slash. First, find the last slash.
13893 (let ((s 0))
13894 (while (string-match "/+" match s)
13895 (setq start (match-beginning 0))
13896 (setq s (match-end 0))))
13897 (if (and (string-match "/+" match start)
13898 (not (string-match-p "\"" match start)))
13899 ;; Match contains also a TODO-matching request.
13900 (progn
13901 (setq tagsmatch (substring match 0 (match-beginning 0)))
13902 (setq todomatch (substring match (match-end 0)))
13903 (when (string-prefix-p "!" todomatch)
13904 (setq org--matcher-tags-todo-only t)
13905 (setq todomatch (substring todomatch 1)))
13906 (when (string-match "\\`\\s-*\\'" todomatch)
13907 (setq todomatch nil)))
13908 ;; Only matching tags.
13909 (setq tagsmatch match)
13910 (setq todomatch nil))
13912 ;; Make the tags matcher.
13913 (when (org-string-nw-p tagsmatch)
13914 (let ((orlist nil)
13915 (orterms (org-split-string tagsmatch "|"))
13916 term)
13917 (while (setq term (pop orterms))
13918 (while (and (equal (substring term -1) "\\") orterms)
13919 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13920 (while (string-match re term)
13921 (let* ((rest (substring term (match-end 0)))
13922 (minus (and (match-end 1)
13923 (equal (match-string 1 term) "-")))
13924 (tag (save-match-data
13925 (replace-regexp-in-string
13926 "\\\\-" "-" (match-string 2 term))))
13927 (regexp (eq (string-to-char tag) ?{))
13928 (levelp (match-end 4))
13929 (propp (match-end 5))
13931 (cond
13932 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13933 (levelp
13934 `(,(org-op-to-function (match-string 3 term))
13935 level
13936 ,(string-to-number (match-string 4 term))))
13937 (propp
13938 (let* ((gv (pcase (upcase (match-string 5 term))
13939 ("CATEGORY"
13940 '(get-text-property (point) 'org-category))
13941 ("TODO" 'todo)
13942 (p `(org-cached-entry-get nil ,p))))
13943 (pv (match-string 7 term))
13944 (regexp (eq (string-to-char pv) ?{))
13945 (strp (eq (string-to-char pv) ?\"))
13946 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13947 (po (org-op-to-function (match-string 6 term)
13948 (if timep 'time strp))))
13949 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13950 (when timep (setq pv (org-matcher-time pv)))
13951 (cond ((and regexp (eq po '/=))
13952 `(not (string-match ,pv (or ,gv ""))))
13953 (regexp `(string-match ,pv (or ,gv "")))
13954 (strp `(,po (or ,gv "") ,pv))
13956 `(,po
13957 (string-to-number (or ,gv ""))
13958 ,(string-to-number pv))))))
13959 (t `(member ,tag tags-list)))))
13960 (push (if minus `(not ,mm) mm) tagsmatcher)
13961 (setq term rest)))
13962 (push `(and ,@tagsmatcher) orlist)
13963 (setq tagsmatcher nil))
13964 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13966 ;; Make the TODO matcher.
13967 (when (org-string-nw-p todomatch)
13968 (let ((orlist nil))
13969 (dolist (term (org-split-string todomatch "|"))
13970 (while (string-match re term)
13971 (let* ((minus (and (match-end 1)
13972 (equal (match-string 1 term) "-")))
13973 (kwd (match-string 2 term))
13974 (regexp (eq (string-to-char kwd) ?{))
13975 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13976 `(equal todo ,kwd))))
13977 (push (if minus `(not ,mm) mm) todomatcher))
13978 (setq term (substring term (match-end 0))))
13979 (push (if (> (length todomatcher) 1)
13980 (cons 'and todomatcher)
13981 (car todomatcher))
13982 orlist)
13983 (setq todomatcher nil))
13984 (setq todomatcher (cons 'or orlist))))
13986 ;; Return the string and function of the matcher. If no
13987 ;; tags-specific or todo-specific matcher exists, match
13988 ;; everything.
13989 (let ((matcher (if (and tagsmatcher todomatcher)
13990 `(and ,tagsmatcher ,todomatcher)
13991 (or tagsmatcher todomatcher t))))
13992 (when org--matcher-tags-todo-only
13993 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13994 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13996 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13997 "Expand group tags in MATCH.
13999 This replaces every group tag in MATCH with a regexp tag search.
14000 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14001 will be replaced like this:
14003 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14004 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14005 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14007 Replacing by a regexp preserves the structure of the match.
14008 E.g., this expansion
14010 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14012 will match anything tagged with \"Lab\" and \"Home\", or tagged
14013 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14015 A group tag in MATCH can contain regular expressions of its own.
14016 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14017 will be replaced like this:
14019 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14021 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14022 assumed to be a single group tag, and the function will return
14023 the list of tags in this group.
14025 When DOWNCASE is non-nil, expand downcased TAGS."
14026 (if org-group-tags
14027 (let* ((case-fold-search t)
14028 (stable org-mode-syntax-table)
14029 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14030 (taggroups (if downcased
14031 (mapcar (lambda (tg) (mapcar #'downcase tg))
14032 taggroups)
14033 taggroups))
14034 (taggroups-keys (mapcar #'car taggroups))
14035 (return-match (if downcased (downcase match) match))
14036 (count 0)
14037 (work-already-expanded tags-already-expanded)
14038 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14039 ;; @ and _ are allowed as word-components in tags.
14040 (modify-syntax-entry ?@ "w" stable)
14041 (modify-syntax-entry ?_ "w" stable)
14042 ;; Temporarily replace regexp-expressions in the match-expression.
14043 (while (string-match "{.+?}" return-match)
14044 (cl-incf count)
14045 (push (match-string 0 return-match) regexps-in-match)
14046 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14047 (while (and taggroups-keys
14048 (with-syntax-table stable
14049 (string-match
14050 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14051 (regexp-opt taggroups-keys) "\\>\\)")
14052 return-match)))
14053 (let* ((dir (match-string 1 return-match))
14054 (tag (match-string 2 return-match))
14055 (tag (if downcased (downcase tag) tag)))
14056 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14057 (member tag tags-already-expanded))
14058 (setq tags-in-group (assoc tag taggroups))
14059 (push tag work-already-expanded)
14060 ;; Recursively expand each tag in the group, if the tag hasn't
14061 ;; already been expanded. Restore the match-data after all recursive calls.
14062 (save-match-data
14063 (let (tags-expanded)
14064 (dolist (x (cdr tags-in-group))
14065 (if (and (member x taggroups-keys)
14066 (not (member x work-already-expanded)))
14067 (setq tags-expanded
14068 (delete-dups
14069 (append
14070 (org-tags-expand x t downcased
14071 work-already-expanded)
14072 tags-expanded)))
14073 (setq tags-expanded
14074 (append (list x) tags-expanded)))
14075 (setq work-already-expanded
14076 (delete-dups
14077 (append tags-expanded
14078 work-already-expanded))))
14079 (setq tags-in-group
14080 (delete-dups (cons (car tags-in-group)
14081 tags-expanded)))))
14082 ;; Filter tag-regexps from tags.
14083 (setq regexp-in-group-escaped
14084 (delq nil (mapcar (lambda (x)
14085 (if (stringp x)
14086 (and (equal "{" (substring x 0 1))
14087 (equal "}" (substring x -1))
14090 tags-in-group))
14091 regexp-in-group
14092 (mapcar (lambda (x)
14093 (substring x 1 -1))
14094 regexp-in-group-escaped)
14095 tags-in-group
14096 (delq nil (mapcar (lambda (x)
14097 (if (stringp x)
14098 (and (not (equal "{" (substring x 0 1)))
14099 (not (equal "}" (substring x -1)))
14102 tags-in-group)))
14103 ;; If single-as-list, do no more in the while-loop.
14104 (if (not single-as-list)
14105 (progn
14106 (when regexp-in-group
14107 (setq regexp-in-group
14108 (concat "\\|"
14109 (mapconcat 'identity regexp-in-group
14110 "\\|"))))
14111 (setq tags-in-group
14112 (concat dir
14113 "{\\<"
14114 (regexp-opt tags-in-group)
14115 "\\>"
14116 regexp-in-group
14117 "}"))
14118 (when (stringp tags-in-group)
14119 (org-add-props tags-in-group '(grouptag t)))
14120 (setq return-match
14121 (replace-match tags-in-group t t return-match)))
14122 (setq tags-in-group
14123 (append regexp-in-group-escaped tags-in-group))))
14124 (setq taggroups-keys (delete tag taggroups-keys))))
14125 ;; Add the regular expressions back into the match-expression again.
14126 (while regexps-in-match
14127 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14128 (pop regexps-in-match)
14129 return-match t t))
14130 (cl-decf count))
14131 (if single-as-list
14132 (if tags-in-group tags-in-group (list return-match))
14133 return-match))
14134 (if single-as-list
14135 (list (if downcased (downcase match) match))
14136 match)))
14138 (defun org-op-to-function (op &optional stringp)
14139 "Turn an operator into the appropriate function."
14140 (setq op
14141 (cond
14142 ((equal op "<" ) '(< org-string< org-time<))
14143 ((equal op ">" ) '(> org-string> org-time>))
14144 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14145 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14146 ((member op '("=" "==")) '(= string= org-time=))
14147 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14148 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14150 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14151 (defvar org-tags-overlay (make-overlay 1 1))
14152 (delete-overlay org-tags-overlay)
14154 (defun org-get-local-tags-at (&optional pos)
14155 "Get a list of tags defined in the current headline."
14156 (org-get-tags-at pos 'local))
14158 (defun org-get-local-tags ()
14159 "Get a list of tags defined in the current headline."
14160 (org-get-tags-at nil 'local))
14162 (defun org-get-tags-at (&optional pos local)
14163 "Get a list of all headline tags applicable at POS.
14164 POS defaults to point. If tags are inherited, the list contains
14165 the targets in the same sequence as the headlines appear, i.e.
14166 the tags of the current headline come last.
14167 When LOCAL is non-nil, only return tags from the current headline,
14168 ignore inherited ones."
14169 (interactive)
14170 (if (and org-trust-scanner-tags
14171 (or (not pos) (equal pos (point)))
14172 (not local))
14173 org-scanner-tags
14174 (let (tags ltags lastpos parent)
14175 (save-excursion
14176 (save-restriction
14177 (widen)
14178 (goto-char (or pos (point)))
14179 (save-match-data
14180 (catch 'done
14181 (condition-case nil
14182 (progn
14183 (org-back-to-heading t)
14184 (while (not (equal lastpos (point)))
14185 (setq lastpos (point))
14186 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14187 (setq ltags (org-split-string
14188 (match-string-no-properties 1) ":"))
14189 (when parent
14190 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14191 (setq tags (append
14192 (if parent
14193 (org-remove-uninherited-tags ltags)
14194 ltags)
14195 tags)))
14196 (or org-use-tag-inheritance (throw 'done t))
14197 (when local (throw 'done t))
14198 (or (org-up-heading-safe) (error nil))
14199 (setq parent t)))
14200 (error nil)))))
14201 (if local
14202 tags
14203 (reverse (delete-dups
14204 (reverse (append
14205 (org-remove-uninherited-tags
14206 org-file-tags)
14207 tags)))))))))
14209 (defun org-add-prop-inherited (s)
14210 (add-text-properties 0 (length s) '(inherited t) s)
14213 (defun org-toggle-tag (tag &optional onoff)
14214 "Toggle the tag TAG for the current line.
14215 If ONOFF is `on' or `off', don't toggle but set to this state."
14216 (save-excursion
14217 (org-back-to-heading t)
14218 (let ((current
14219 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14220 (line-end-position) t)
14221 (let ((tags (match-string 1)))
14222 ;; Clear current tags.
14223 (replace-match "")
14224 ;; Reverse the tags list so any new tag is appended to
14225 ;; the current list of tags.
14226 (nreverse (org-split-string tags ":")))))
14227 res)
14228 (pcase onoff
14229 (`off (setq current (delete tag current)))
14230 ((or `on (guard (not (member tag current))))
14231 (setq res t)
14232 (cl-pushnew tag current :test #'equal))
14233 (_ (setq current (delete tag current))))
14234 (end-of-line)
14235 (if current
14236 (progn
14237 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14238 (org-set-tags nil t))
14239 (delete-horizontal-space))
14240 (run-hooks 'org-after-tags-change-hook)
14241 res)))
14243 (defun org--align-tags-here (to-col)
14244 "Align tags on the current headline to TO-COL.
14245 Assume point is on a headline."
14246 (let ((pos (point)))
14247 (beginning-of-line)
14248 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14249 (>= pos (match-beginning 2)))
14250 ;; No tags or point within tags: do not align.
14251 (goto-char pos)
14252 (goto-char (match-beginning 1))
14253 (let ((shift (max (- (if (>= to-col 0) to-col
14254 (- (abs to-col) (string-width (match-string 2))))
14255 (current-column))
14256 1)))
14257 (replace-match (make-string shift ?\s) nil nil nil 1)
14258 ;; Preserve initial position, if possible. In any case, stop
14259 ;; before tags.
14260 (when (< pos (point)) (goto-char pos))))))
14262 (defun org-set-tags-command (&optional arg just-align)
14263 "Call the set-tags command for the current entry."
14264 (interactive "P")
14265 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14266 (org-set-tags arg just-align)
14267 (save-excursion
14268 (unless (and (org-region-active-p)
14269 org-loop-over-headlines-in-active-region)
14270 (org-back-to-heading t))
14271 (org-set-tags arg just-align))))
14273 (defun org-set-tags-to (data)
14274 "Set the tags of the current entry to DATA, replacing current tags.
14275 DATA may be a tags string like \":aa:bb:cc:\", or a list of tags.
14276 If DATA is nil or the empty string, all tags are removed."
14277 (interactive "sTags: ")
14278 (let ((data
14279 (pcase (if (stringp data) (org-trim data) data)
14280 ((or `nil "") nil)
14281 ((pred listp) (format ":%s:" (mapconcat #'identity data ":")))
14282 ((pred stringp)
14283 (format ":%s:"
14284 (mapconcat #'identity (org-split-string data ":+") ":")))
14285 (_ (error "Invalid tag specification: %S" data)))))
14286 (org-with-wide-buffer
14287 (org-back-to-heading t)
14288 (let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
14289 (when (or (match-end 5) data)
14290 (goto-char (or (match-beginning 5) (line-end-position)))
14291 (skip-chars-backward " \t")
14292 (delete-region (point) (line-end-position))
14293 (when data
14294 (insert " " data)
14295 (org-set-tags nil 'align))))))
14297 (defun org-align-all-tags ()
14298 "Align the tags in all headings."
14299 (interactive)
14300 (save-excursion
14301 (or (ignore-errors (org-back-to-heading t))
14302 (outline-next-heading))
14303 (if (org-at-heading-p)
14304 (org-set-tags t)
14305 (message "No headings"))))
14307 (defvar org-indent-indentation-per-level)
14308 (defun org-set-tags (&optional arg just-align)
14309 "Set the tags for the current headline.
14310 With prefix ARG, realign all tags in headings in the current buffer.
14311 When JUST-ALIGN is non-nil, only align tags."
14312 (interactive "P")
14313 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14314 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14315 'region-start-level
14316 'region))
14317 org-loop-over-headlines-in-active-region)
14318 (org-map-entries
14319 ;; We don't use ARG and JUST-ALIGN here because these args
14320 ;; are not useful when looping over headlines.
14321 #'org-set-tags
14322 org-loop-over-headlines-in-active-region
14324 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14325 (let ((org-setting-tags t))
14326 (if arg
14327 (save-excursion
14328 (goto-char (point-min))
14329 (while (re-search-forward org-outline-regexp-bol nil t)
14330 (org-set-tags nil t)
14331 (end-of-line))
14332 (message "All tags realigned to column %d" org-tags-column))
14333 (let* ((current (org-get-tags-string))
14334 (tags
14335 (if just-align current
14336 ;; Get a new set of tags from the user.
14337 (save-excursion
14338 (let* ((table
14339 (setq
14340 org-last-tags-completion-table
14341 (org-tag-add-to-alist
14342 (and
14343 org-complete-tags-always-offer-all-agenda-tags
14344 (org-global-tags-completion-table
14345 (org-agenda-files)))
14346 (or org-current-tag-alist
14347 (org-get-buffer-tags)))))
14348 (current-tags (org-split-string current ":"))
14349 (inherited-tags
14350 (nreverse (nthcdr (length current-tags)
14351 (nreverse (org-get-tags-at))))))
14352 (replace-regexp-in-string
14353 "\\([-+&]+\\|,\\)"
14355 (if (or (eq t org-use-fast-tag-selection)
14356 (and org-use-fast-tag-selection
14357 (delq nil (mapcar #'cdr table))))
14358 (org-fast-tag-selection
14359 current-tags inherited-tags table
14360 (and org-fast-tag-selection-include-todo
14361 org-todo-key-alist))
14362 (let ((org-add-colon-after-tag-completion
14363 (< 1 (length table))))
14364 (org-trim
14365 (completing-read
14366 "Tags: "
14367 #'org-tags-completion-function
14368 nil nil current 'org-tags-history))))))))))
14370 (when org-tags-sort-function
14371 (setq tags
14372 (mapconcat
14373 #'identity
14374 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14375 org-tags-sort-function)
14376 ":")))
14378 (if (or (string= ":" tags)
14379 (string= "::" tags))
14380 (setq tags ""))
14381 (if (not (org-string-nw-p tags)) (setq tags "")
14382 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14383 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14385 ;; Insert new tags at the correct column.
14386 (unless (equal current tags)
14387 (save-excursion
14388 (beginning-of-line)
14389 (let ((case-fold-search nil))
14390 (looking-at org-complex-heading-regexp))
14391 ;; Remove current tags, if any.
14392 (when (match-end 5) (replace-match "" nil nil nil 5))
14393 ;; Insert new tags, if any. Otherwise, remove trailing
14394 ;; white spaces.
14395 (end-of-line)
14396 (if (not (equal tags ""))
14397 ;; When text is being inserted on an invisible
14398 ;; region boundary, it can be inadvertently sucked
14399 ;; into invisibility.
14400 (org-flag-region (point) (progn (insert " " tags) (point))
14402 'outline)
14403 (skip-chars-backward " \t")
14404 (delete-region (point) (line-end-position)))))
14405 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14406 ;; is on.
14407 (unless (equal tags "")
14408 (let* ((level (save-excursion
14409 (beginning-of-line)
14410 (skip-chars-forward "\\*")))
14411 (offset (if (bound-and-true-p org-indent-mode)
14412 (* (1- org-indent-indentation-per-level)
14413 (1- level))
14415 (tags-column
14416 (+ org-tags-column
14417 (if (> org-tags-column 0) (- offset) offset))))
14418 (org--align-tags-here tags-column))))
14419 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14421 (defun org-change-tag-in-region (beg end tag off)
14422 "Add or remove TAG for each entry in the region.
14423 This works in the agenda, and also in an Org buffer."
14424 (interactive
14425 (list (region-beginning) (region-end)
14426 (let ((org-last-tags-completion-table
14427 (if (derived-mode-p 'org-mode)
14428 (org-tag-add-to-alist
14429 (org-get-buffer-tags)
14430 (org-global-tags-completion-table))
14431 (org-global-tags-completion-table))))
14432 (completing-read
14433 "Tag: " 'org-tags-completion-function nil nil nil
14434 'org-tags-history))
14435 (progn
14436 (message "[s]et or [r]emove? ")
14437 (equal (read-char-exclusive) ?r))))
14438 (when (fboundp 'deactivate-mark) (deactivate-mark))
14439 (let ((agendap (equal major-mode 'org-agenda-mode))
14440 l1 l2 m buf pos newhead (cnt 0))
14441 (goto-char end)
14442 (setq l2 (1- (org-current-line)))
14443 (goto-char beg)
14444 (setq l1 (org-current-line))
14445 (cl-loop for l from l1 to l2 do
14446 (org-goto-line l)
14447 (setq m (get-text-property (point) 'org-hd-marker))
14448 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14449 (and agendap m))
14450 (setq buf (if agendap (marker-buffer m) (current-buffer))
14451 pos (if agendap m (point)))
14452 (with-current-buffer buf
14453 (save-excursion
14454 (save-restriction
14455 (goto-char pos)
14456 (setq cnt (1+ cnt))
14457 (org-toggle-tag tag (if off 'off 'on))
14458 (setq newhead (org-get-heading)))))
14459 (and agendap (org-agenda-change-all-lines newhead m))))
14460 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14462 (defun org-tags-completion-function (string _predicate &optional flag)
14463 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14464 (confirm (lambda (x) (stringp (car x)))))
14465 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14466 (setq s1 (match-string 1 string)
14467 s2 (match-string 2 string))
14468 (setq s1 "" s2 string))
14469 (cond
14470 ((eq flag nil)
14471 ;; try completion
14472 (setq rtn (try-completion s2 ctable confirm))
14473 (when (stringp rtn)
14474 (setq rtn
14475 (concat s1 s2 (substring rtn (length s2))
14476 (if (and org-add-colon-after-tag-completion
14477 (assoc rtn ctable))
14478 ":" ""))))
14479 rtn)
14480 ((eq flag t)
14481 ;; all-completions
14482 (all-completions s2 ctable confirm))
14483 ((eq flag 'lambda)
14484 ;; exact match?
14485 (assoc s2 ctable)))))
14487 (defun org-fast-tag-insert (kwd tags face &optional end)
14488 "Insert KDW, and the TAGS, the latter with face FACE.
14489 Also insert END."
14490 (insert (format "%-12s" (concat kwd ":"))
14491 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14492 (or end "")))
14494 (defun org-fast-tag-show-exit (flag)
14495 (save-excursion
14496 (org-goto-line 3)
14497 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14498 (replace-match ""))
14499 (when flag
14500 (end-of-line 1)
14501 (org-move-to-column (- (window-width) 19) t)
14502 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14504 (defun org-set-current-tags-overlay (current prefix)
14505 "Add an overlay to CURRENT tag with PREFIX."
14506 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14507 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14508 (org-overlay-display org-tags-overlay (concat prefix s))))
14510 (defvar org-last-tag-selection-key nil)
14511 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14512 "Fast tag selection with single keys.
14513 CURRENT is the current list of tags in the headline, INHERITED is the
14514 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14515 possibly with grouping information. TODO-TABLE is a similar table with
14516 TODO keywords, should these have keys assigned to them.
14517 If the keys are nil, a-z are automatically assigned.
14518 Returns the new tags string, or nil to not change the current settings."
14519 (let* ((fulltable (append table todo-table))
14520 (maxlen (apply 'max (mapcar
14521 (lambda (x)
14522 (if (stringp (car x)) (string-width (car x)) 0))
14523 fulltable)))
14524 (buf (current-buffer))
14525 (expert (eq org-fast-tag-selection-single-key 'expert))
14526 (buffer-tags nil)
14527 (fwidth (+ maxlen 3 1 3))
14528 (ncol (/ (- (window-width) 4) fwidth))
14529 (i-face 'org-done)
14530 (c-face 'org-todo)
14531 tg cnt e c char c1 c2 ntable tbl rtn
14532 ov-start ov-end ov-prefix
14533 (exit-after-next org-fast-tag-selection-single-key)
14534 (done-keywords org-done-keywords)
14535 groups ingroup intaggroup)
14536 (save-excursion
14537 (beginning-of-line 1)
14538 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14539 (setq ov-start (match-beginning 1)
14540 ov-end (match-end 1)
14541 ov-prefix "")
14542 (setq ov-start (1- (point-at-eol))
14543 ov-end (1+ ov-start))
14544 (skip-chars-forward "^\n\r")
14545 (setq ov-prefix
14546 (concat
14547 (buffer-substring (1- (point)) (point))
14548 (if (> (current-column) org-tags-column)
14550 (make-string (- org-tags-column (current-column)) ?\ ))))))
14551 (move-overlay org-tags-overlay ov-start ov-end)
14552 (save-window-excursion
14553 (if expert
14554 (set-buffer (get-buffer-create " *Org tags*"))
14555 (delete-other-windows)
14556 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14557 (org-switch-to-buffer-other-window " *Org tags*"))
14558 (erase-buffer)
14559 (setq-local org-done-keywords done-keywords)
14560 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14561 (org-fast-tag-insert "Current" current c-face "\n\n")
14562 (org-fast-tag-show-exit exit-after-next)
14563 (org-set-current-tags-overlay current ov-prefix)
14564 (setq tbl fulltable char ?a cnt 0)
14565 (while (setq e (pop tbl))
14566 (cond
14567 ((eq (car e) :startgroup)
14568 (push '() groups) (setq ingroup t)
14569 (unless (zerop cnt)
14570 (setq cnt 0)
14571 (insert "\n"))
14572 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14573 ((eq (car e) :endgroup)
14574 (setq ingroup nil cnt 0)
14575 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14576 ((eq (car e) :startgrouptag)
14577 (setq intaggroup t)
14578 (unless (zerop cnt)
14579 (setq cnt 0)
14580 (insert "\n"))
14581 (insert "[ "))
14582 ((eq (car e) :endgrouptag)
14583 (setq intaggroup nil cnt 0)
14584 (insert "]\n"))
14585 ((equal e '(:newline))
14586 (unless (zerop cnt)
14587 (setq cnt 0)
14588 (insert "\n")
14589 (setq e (car tbl))
14590 (while (equal (car tbl) '(:newline))
14591 (insert "\n")
14592 (setq tbl (cdr tbl)))))
14593 ((equal e '(:grouptags)) (insert " : "))
14595 (setq tg (copy-sequence (car e)) c2 nil)
14596 (if (cdr e)
14597 (setq c (cdr e))
14598 ;; automatically assign a character.
14599 (setq c1 (string-to-char
14600 (downcase (substring
14601 tg (if (= (string-to-char tg) ?@) 1 0)))))
14602 (if (or (rassoc c1 ntable) (rassoc c1 table))
14603 (while (or (rassoc char ntable) (rassoc char table))
14604 (setq char (1+ char)))
14605 (setq c2 c1))
14606 (setq c (or c2 char)))
14607 (when ingroup (push tg (car groups)))
14608 (setq tg (org-add-props tg nil 'face
14609 (cond
14610 ((not (assoc tg table))
14611 (org-get-todo-face tg))
14612 ((member tg current) c-face)
14613 ((member tg inherited) i-face))))
14614 (when (equal (caar tbl) :grouptags)
14615 (org-add-props tg nil 'face 'org-tag-group))
14616 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14617 (insert "[" c "] " tg (make-string
14618 (- fwidth 4 (length tg)) ?\ ))
14619 (push (cons tg c) ntable)
14620 (when (= (cl-incf cnt) ncol)
14621 (insert "\n")
14622 (when (or ingroup intaggroup) (insert " "))
14623 (setq cnt 0)))))
14624 (setq ntable (nreverse ntable))
14625 (insert "\n")
14626 (goto-char (point-min))
14627 (unless expert (org-fit-window-to-buffer))
14628 (setq rtn
14629 (catch 'exit
14630 (while t
14631 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14632 (if (not groups) "no " "")
14633 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14634 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14635 (setq org-last-tag-selection-key c)
14636 (cond
14637 ((= c ?\r) (throw 'exit t))
14638 ((= c ?!)
14639 (setq groups (not groups))
14640 (goto-char (point-min))
14641 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14642 ((= c ?\C-c)
14643 (if (not expert)
14644 (org-fast-tag-show-exit
14645 (setq exit-after-next (not exit-after-next)))
14646 (setq expert nil)
14647 (delete-other-windows)
14648 (set-window-buffer (split-window-vertically) " *Org tags*")
14649 (org-switch-to-buffer-other-window " *Org tags*")
14650 (org-fit-window-to-buffer)))
14651 ((or (= c ?\C-g)
14652 (and (= c ?q) (not (rassoc c ntable))))
14653 (delete-overlay org-tags-overlay)
14654 (setq quit-flag t))
14655 ((= c ?\ )
14656 (setq current nil)
14657 (when exit-after-next (setq exit-after-next 'now)))
14658 ((= c ?\t)
14659 (condition-case nil
14660 (setq tg (completing-read
14661 "Tag: "
14662 (or buffer-tags
14663 (with-current-buffer buf
14664 (setq buffer-tags
14665 (org-get-buffer-tags))))))
14666 (quit (setq tg "")))
14667 (when (string-match "\\S-" tg)
14668 (cl-pushnew (list tg) buffer-tags :test #'equal)
14669 (if (member tg current)
14670 (setq current (delete tg current))
14671 (push tg current)))
14672 (when exit-after-next (setq exit-after-next 'now)))
14673 ((setq e (rassoc c todo-table) tg (car e))
14674 (with-current-buffer buf
14675 (save-excursion (org-todo tg)))
14676 (when exit-after-next (setq exit-after-next 'now)))
14677 ((setq e (rassoc c ntable) tg (car e))
14678 (if (member tg current)
14679 (setq current (delete tg current))
14680 (cl-loop for g in groups do
14681 (when (member tg g)
14682 (dolist (x g) (setq current (delete x current)))))
14683 (push tg current))
14684 (when exit-after-next (setq exit-after-next 'now))))
14686 ;; Create a sorted list
14687 (setq current
14688 (sort current
14689 (lambda (a b)
14690 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14691 (when (eq exit-after-next 'now) (throw 'exit t))
14692 (goto-char (point-min))
14693 (beginning-of-line 2)
14694 (delete-region (point) (point-at-eol))
14695 (org-fast-tag-insert "Current" current c-face)
14696 (org-set-current-tags-overlay current ov-prefix)
14697 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14698 (setq tg (match-string 1))
14699 (add-text-properties
14700 (match-beginning 1) (match-end 1)
14701 (list 'face
14702 (cond
14703 ((member tg current) c-face)
14704 ((member tg inherited) i-face)
14705 (t (get-text-property (match-beginning 1) 'face))))))
14706 (goto-char (point-min)))))
14707 (delete-overlay org-tags-overlay)
14708 (if rtn
14709 (mapconcat 'identity current ":")
14710 nil))))
14712 (defun org-get-tags-string ()
14713 "Get the TAGS string in the current headline."
14714 (unless (org-at-heading-p t)
14715 (user-error "Not on a heading"))
14716 (save-excursion
14717 (beginning-of-line 1)
14718 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14719 (match-string-no-properties 1)
14720 "")))
14722 (defun org--get-local-tags ()
14723 "Return list of tags for the current headline.
14724 Assume point is at the beginning of the headline."
14725 (and (looking-at org-tag-line-re)
14726 (split-string (match-string-no-properties 2) ":" t)))
14728 (defun org-get-tags (&optional pos local)
14729 "Get the list of tags specified in the current headline.
14731 When argument POS is non-nil, retrieve tags for headline at POS.
14733 Accoring to `org-use-tags-inheritance', tags may be inherited
14734 from parent headlines, and from the whole document, through
14735 `org-file-tags'. However, when optional argument LOCAL is
14736 non-nil, only return tags really specified in the considered
14737 headline.
14739 Inherited tags have the `inherited' text property."
14740 (if (and org-trust-scanner-tags
14741 (or (not pos) (eq pos (point)))
14742 (not local))
14743 org-scanner-tags
14744 (org-with-point-at (or pos (point))
14745 (unless (org-before-first-heading-p)
14746 (org-back-to-heading t)
14747 (let ((tags (org--get-local-tags)))
14748 (if (or local (not org-use-tag-inheritance)) tags
14749 (while (org-up-heading-safe)
14750 (setq tags (append (mapcar #'org-add-prop-inherited
14751 (org--get-local-tags))
14752 tags)))
14753 (org-remove-uninherited-tags
14754 (delete-dups (append org-file-tags tags)))))))))
14756 (defun org-get-buffer-tags ()
14757 "Get a table of all tags used in the buffer, for completion."
14758 (org-with-point-at 1
14759 (let (tags)
14760 (while (re-search-forward org-tag-line-re nil t)
14761 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14762 tags)))
14763 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14765 ;;;; The mapping API
14767 (defvar org-agenda-skip-comment-trees)
14768 (defvar org-agenda-skip-function)
14769 (defun org-map-entries (func &optional match scope &rest skip)
14770 "Call FUNC at each headline selected by MATCH in SCOPE.
14772 FUNC is a function or a lisp form. The function will be called without
14773 arguments, with the cursor positioned at the beginning of the headline.
14774 The return values of all calls to the function will be collected and
14775 returned as a list.
14777 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14778 does not need to preserve point. After evaluation, the cursor will be
14779 moved to the end of the line (presumably of the headline of the
14780 processed entry) and search continues from there. Under some
14781 circumstances, this may not produce the wanted results. For example,
14782 if you have removed (e.g. archived) the current (sub)tree it could
14783 mean that the next entry will be skipped entirely. In such cases, you
14784 can specify the position from where search should continue by making
14785 FUNC set the variable `org-map-continue-from' to the desired buffer
14786 position.
14788 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14789 Only headlines that are matched by this query will be considered during
14790 the iteration. When MATCH is nil or t, all headlines will be
14791 visited by the iteration.
14793 SCOPE determines the scope of this command. It can be any of:
14795 nil The current buffer, respecting the restriction if any
14796 tree The subtree started with the entry at point
14797 region The entries within the active region, if any
14798 region-start-level
14799 The entries within the active region, but only those at
14800 the same level than the first one.
14801 file The current buffer, without restriction
14802 file-with-archives
14803 The current buffer, and any archives associated with it
14804 agenda All agenda files
14805 agenda-with-archives
14806 All agenda files with any archive files associated with them
14807 \(file1 file2 ...)
14808 If this is a list, all files in the list will be scanned
14810 The remaining args are treated as settings for the skipping facilities of
14811 the scanner. The following items can be given here:
14813 archive skip trees with the archive tag
14814 comment skip trees with the COMMENT keyword
14815 function or Emacs Lisp form:
14816 will be used as value for `org-agenda-skip-function', so
14817 whenever the function returns a position, FUNC will not be
14818 called for that entry and search will continue from the
14819 position returned
14821 If your function needs to retrieve the tags including inherited tags
14822 at the *current* entry, you can use the value of the variable
14823 `org-scanner-tags' which will be much faster than getting the value
14824 with `org-get-tags-at'. If your function gets properties with
14825 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14826 to t around the call to `org-entry-properties' to get the same speedup.
14827 Note that if your function moves around to retrieve tags and properties at
14828 a *different* entry, you cannot use these techniques."
14829 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14830 (not (org-region-active-p)))
14831 (let* ((org-agenda-archives-mode nil) ; just to make sure
14832 (org-agenda-skip-archived-trees (memq 'archive skip))
14833 (org-agenda-skip-comment-trees (memq 'comment skip))
14834 (org-agenda-skip-function
14835 (car (org-delete-all '(comment archive) skip)))
14836 (org-tags-match-list-sublevels t)
14837 (start-level (eq scope 'region-start-level))
14838 matcher res
14839 org-todo-keywords-for-agenda
14840 org-done-keywords-for-agenda
14841 org-todo-keyword-alist-for-agenda
14842 org-tag-alist-for-agenda
14843 org--matcher-tags-todo-only)
14845 (cond
14846 ((eq match t) (setq matcher t))
14847 ((eq match nil) (setq matcher t))
14848 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14850 (save-excursion
14851 (save-restriction
14852 (cond ((eq scope 'tree)
14853 (org-back-to-heading t)
14854 (org-narrow-to-subtree)
14855 (setq scope nil))
14856 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14857 (org-region-active-p))
14858 ;; If needed, set start-level to a string like "2"
14859 (when start-level
14860 (save-excursion
14861 (goto-char (region-beginning))
14862 (unless (org-at-heading-p) (outline-next-heading))
14863 (setq start-level (org-current-level))))
14864 (narrow-to-region (region-beginning)
14865 (save-excursion
14866 (goto-char (region-end))
14867 (unless (and (bolp) (org-at-heading-p))
14868 (outline-next-heading))
14869 (point)))
14870 (setq scope nil)))
14872 (if (not scope)
14873 (progn
14874 (org-agenda-prepare-buffers
14875 (and buffer-file-name (list buffer-file-name)))
14876 (setq res
14877 (org-scan-tags
14878 func matcher org--matcher-tags-todo-only start-level)))
14879 ;; Get the right scope
14880 (cond
14881 ((and scope (listp scope) (symbolp (car scope)))
14882 (setq scope (eval scope)))
14883 ((eq scope 'agenda)
14884 (setq scope (org-agenda-files t)))
14885 ((eq scope 'agenda-with-archives)
14886 (setq scope (org-agenda-files t))
14887 (setq scope (org-add-archive-files scope)))
14888 ((eq scope 'file)
14889 (setq scope (and buffer-file-name (list buffer-file-name))))
14890 ((eq scope 'file-with-archives)
14891 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14892 (org-agenda-prepare-buffers scope)
14893 (dolist (file scope)
14894 (with-current-buffer (org-find-base-buffer-visiting file)
14895 (org-with-wide-buffer
14896 (goto-char (point-min))
14897 (setq res
14898 (append
14900 (org-scan-tags
14901 func matcher org--matcher-tags-todo-only)))))))))
14902 res)))
14904 ;;; Properties API
14906 (defconst org-special-properties
14907 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14908 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14909 "The special properties valid in Org mode.
14910 These are properties that are not defined in the property drawer,
14911 but in some other way.")
14913 (defconst org-default-properties
14914 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14915 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14916 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14917 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14918 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14919 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14920 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14921 "Some properties that are used by Org mode for various purposes.
14922 Being in this list makes sure that they are offered for completion.")
14924 (defun org--valid-property-p (property)
14925 "Non nil when string PROPERTY is a valid property name."
14926 (not
14927 (or (equal property "")
14928 (string-match-p "\\s-" property))))
14930 (defun org--update-property-plist (key val props)
14931 "Associate KEY to VAL in alist PROPS.
14932 Modifications are made by side-effect. Return new alist."
14933 (let* ((appending (string= (substring key -1) "+"))
14934 (key (if appending (substring key 0 -1) key))
14935 (old (assoc-string key props t)))
14936 (if (not old) (cons (cons key val) props)
14937 (setcdr old (if appending (concat (cdr old) " " val) val))
14938 props)))
14940 (defun org-get-property-block (&optional beg force)
14941 "Return the (beg . end) range of the body of the property drawer.
14942 BEG is the beginning of the current subtree, or of the part
14943 before the first headline. If it is not given, it will be found.
14944 If the drawer does not exist, create it if FORCE is non-nil, or
14945 return nil."
14946 (org-with-wide-buffer
14947 (when beg (goto-char beg))
14948 (unless (org-before-first-heading-p)
14949 (let ((beg (cond (beg)
14950 ((or (not (featurep 'org-inlinetask))
14951 (org-inlinetask-in-task-p))
14952 (org-back-to-heading t))
14953 (t (org-with-limited-levels (org-back-to-heading t))))))
14954 (forward-line)
14955 (when (looking-at-p org-planning-line-re) (forward-line))
14956 (cond ((looking-at org-property-drawer-re)
14957 (forward-line)
14958 (cons (point) (progn (goto-char (match-end 0))
14959 (line-beginning-position))))
14960 (force
14961 (goto-char beg)
14962 (org-insert-property-drawer)
14963 (let ((pos (save-excursion (search-forward ":END:")
14964 (line-beginning-position))))
14965 (cons pos pos))))))))
14967 (defun org-at-property-p ()
14968 "Non-nil when point is inside a property drawer.
14969 See `org-property-re' for match data, if applicable."
14970 (save-excursion
14971 (beginning-of-line)
14972 (and (looking-at org-property-re)
14973 (let ((property-drawer (save-match-data (org-get-property-block))))
14974 (and property-drawer
14975 (>= (point) (car property-drawer))
14976 (< (point) (cdr property-drawer)))))))
14978 (defun org-property-action ()
14979 "Do an action on properties."
14980 (interactive)
14981 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14982 (let ((c (read-char-exclusive)))
14983 (cl-case c
14984 (?s (call-interactively #'org-set-property))
14985 (?d (call-interactively #'org-delete-property))
14986 (?D (call-interactively #'org-delete-property-globally))
14987 (?c (call-interactively #'org-compute-property-at-point))
14988 (otherwise (user-error "No such property action %c" c)))))
14990 (defun org-inc-effort ()
14991 "Increment the value of the effort property in the current entry."
14992 (interactive)
14993 (org-set-effort t))
14995 (defvar org-clock-effort) ; Defined in org-clock.el.
14996 (defvar org-clock-current-task) ; Defined in org-clock.el.
14997 (defun org-set-effort (&optional increment value)
14998 "Set the effort property of the current entry.
14999 If INCREMENT is non-nil, set the property to the next allowed
15000 value. Otherwise, if optional argument VALUE is provided, use
15001 it. Eventually, prompt for the new value if none of the previous
15002 variables is set."
15003 (interactive "P")
15004 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
15005 (current (org-entry-get nil org-effort-property))
15006 (value
15007 (cond
15008 (increment
15009 (unless allowed (user-error "Allowed effort values are not set"))
15010 (or (cl-caadr (member (list current) allowed))
15011 (user-error "Unknown value %S among allowed values" current)))
15012 (value
15013 (if (stringp value) value
15014 (error "Invalid effort value: %S" value)))
15016 (let ((must-match
15017 (and allowed
15018 (not (get-text-property 0 'org-unrestricted
15019 (caar allowed))))))
15020 (completing-read "Effort: " allowed nil must-match))))))
15021 (unless (equal current value)
15022 (org-entry-put nil org-effort-property value))
15023 (org-refresh-property '((effort . identity)
15024 (effort-minutes . org-duration-to-minutes))
15025 value)
15026 (when (equal (org-get-heading t t t t)
15027 (bound-and-true-p org-clock-current-task))
15028 (setq org-clock-effort (org-get-at-bol 'effort))
15029 (org-clock-update-mode-line))
15030 (message "%s is now %s" org-effort-property value)))
15032 (defun org-entry-properties (&optional pom which)
15033 "Get all properties of the current entry.
15035 When POM is a buffer position, get all properties from the entry
15036 there instead.
15038 This includes the TODO keyword, the tags, time strings for
15039 deadline, scheduled, and clocking, and any additional properties
15040 defined in the entry.
15042 If WHICH is nil or `all', get all properties. If WHICH is
15043 `special' or `standard', only get that subclass. If WHICH is
15044 a string, only get that property.
15046 Return value is an alist. Keys are properties, as upcased
15047 strings."
15048 (org-with-point-at pom
15049 (when (and (derived-mode-p 'org-mode)
15050 (ignore-errors (org-back-to-heading t)))
15051 (catch 'exit
15052 (let* ((beg (point))
15053 (specific (and (stringp which) (upcase which)))
15054 (which (cond ((not specific) which)
15055 ((member specific org-special-properties) 'special)
15056 (t 'standard)))
15057 props)
15058 ;; Get the special properties, like TODO and TAGS.
15059 (when (memq which '(nil all special))
15060 (when (or (not specific) (string= specific "CLOCKSUM"))
15061 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15062 (when clocksum
15063 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15064 props)))
15065 (when specific (throw 'exit props)))
15066 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15067 (let ((clocksumt (get-text-property (point)
15068 :org-clock-minutes-today)))
15069 (when clocksumt
15070 (push (cons "CLOCKSUM_T"
15071 (org-duration-from-minutes clocksumt))
15072 props)))
15073 (when specific (throw 'exit props)))
15074 (when (or (not specific) (string= specific "ITEM"))
15075 (let ((case-fold-search nil))
15076 (when (looking-at org-complex-heading-regexp)
15077 (push (cons "ITEM"
15078 (let ((title (match-string-no-properties 4)))
15079 (if (org-string-nw-p title)
15080 (org-remove-tabs title)
15081 "")))
15082 props)))
15083 (when specific (throw 'exit props)))
15084 (when (or (not specific) (string= specific "TODO"))
15085 (let ((case-fold-search nil))
15086 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15087 (push (cons "TODO" (match-string-no-properties 2)) props)))
15088 (when specific (throw 'exit props)))
15089 (when (or (not specific) (string= specific "PRIORITY"))
15090 (push (cons "PRIORITY"
15091 (if (looking-at org-priority-regexp)
15092 (match-string-no-properties 2)
15093 (char-to-string org-default-priority)))
15094 props)
15095 (when specific (throw 'exit props)))
15096 (when (or (not specific) (string= specific "FILE"))
15097 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15098 props)
15099 (when specific (throw 'exit props)))
15100 (when (or (not specific) (string= specific "TAGS"))
15101 (let ((value (org-string-nw-p (org-get-tags-string))))
15102 (when value (push (cons "TAGS" value) props)))
15103 (when specific (throw 'exit props)))
15104 (when (or (not specific) (string= specific "ALLTAGS"))
15105 (let ((value (org-get-tags-at)))
15106 (when value
15107 (push (cons "ALLTAGS"
15108 (format ":%s:" (mapconcat #'identity value ":")))
15109 props)))
15110 (when specific (throw 'exit props)))
15111 (when (or (not specific) (string= specific "BLOCKED"))
15112 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15113 (when specific (throw 'exit props)))
15114 (when (or (not specific)
15115 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15116 (forward-line)
15117 (when (looking-at-p org-planning-line-re)
15118 (end-of-line)
15119 (let ((bol (line-beginning-position))
15120 ;; Backward compatibility: time keywords used to
15121 ;; be configurable (before 8.3). Make sure we
15122 ;; get the correct keyword.
15123 (key-assoc `(("CLOSED" . ,org-closed-string)
15124 ("DEADLINE" . ,org-deadline-string)
15125 ("SCHEDULED" . ,org-scheduled-string))))
15126 (dolist (pair (if specific (list (assoc specific key-assoc))
15127 key-assoc))
15128 (save-excursion
15129 (when (search-backward (cdr pair) bol t)
15130 (goto-char (match-end 0))
15131 (skip-chars-forward " \t")
15132 (and (looking-at org-ts-regexp-both)
15133 (push (cons (car pair)
15134 (match-string-no-properties 0))
15135 props)))))))
15136 (when specific (throw 'exit props)))
15137 (when (or (not specific)
15138 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15139 (let ((find-ts
15140 (lambda (end ts)
15141 ;; Fix next time-stamp before END. TS is the
15142 ;; list of time-stamps found so far.
15143 (let ((ts ts)
15144 (regexp (cond
15145 ((string= specific "TIMESTAMP")
15146 org-ts-regexp)
15147 ((string= specific "TIMESTAMP_IA")
15148 org-ts-regexp-inactive)
15149 ((assoc "TIMESTAMP_IA" ts)
15150 org-ts-regexp)
15151 ((assoc "TIMESTAMP" ts)
15152 org-ts-regexp-inactive)
15153 (t org-ts-regexp-both))))
15154 (catch 'next
15155 (while (re-search-forward regexp end t)
15156 (backward-char)
15157 (let ((object (org-element-context)))
15158 ;; Accept to match timestamps in node
15159 ;; properties, too.
15160 (when (memq (org-element-type object)
15161 '(node-property timestamp))
15162 (let ((type
15163 (org-element-property :type object)))
15164 (cond
15165 ((and (memq type '(active active-range))
15166 (not (equal specific "TIMESTAMP_IA")))
15167 (unless (assoc "TIMESTAMP" ts)
15168 (push (cons "TIMESTAMP"
15169 (org-element-property
15170 :raw-value object))
15172 (when specific (throw 'exit ts))))
15173 ((and (memq type '(inactive inactive-range))
15174 (not (string= specific "TIMESTAMP")))
15175 (unless (assoc "TIMESTAMP_IA" ts)
15176 (push (cons "TIMESTAMP_IA"
15177 (org-element-property
15178 :raw-value object))
15180 (when specific (throw 'exit ts))))))
15181 ;; Both timestamp types are found,
15182 ;; move to next part.
15183 (when (= (length ts) 2) (throw 'next ts)))))
15184 ts)))))
15185 (goto-char beg)
15186 ;; First look for timestamps within headline.
15187 (let ((ts (funcall find-ts (line-end-position) nil)))
15188 (if (= (length ts) 2) (setq props (nconc ts props))
15189 ;; Then find timestamps in the section, skipping
15190 ;; planning line.
15191 (let ((end (save-excursion (outline-next-heading))))
15192 (forward-line)
15193 (when (looking-at-p org-planning-line-re) (forward-line))
15194 (setq props (nconc (funcall find-ts end ts) props))))))))
15195 ;; Get the standard properties, like :PROP:.
15196 (when (memq which '(nil all standard))
15197 ;; If we are looking after a specific property, delegate
15198 ;; to `org-entry-get', which is faster. However, make an
15199 ;; exception for "CATEGORY", since it can be also set
15200 ;; through keywords (i.e. #+CATEGORY).
15201 (if (and specific (not (equal specific "CATEGORY")))
15202 (let ((value (org-entry-get beg specific nil t)))
15203 (throw 'exit (and value (list (cons specific value)))))
15204 (let ((range (org-get-property-block beg)))
15205 (when range
15206 (let ((end (cdr range)) seen-base)
15207 (goto-char (car range))
15208 ;; Unlike to `org--update-property-plist', we
15209 ;; handle the case where base values is found
15210 ;; after its extension. We also forbid standard
15211 ;; properties to be named as special properties.
15212 (while (re-search-forward org-property-re end t)
15213 (let* ((key (upcase (match-string-no-properties 2)))
15214 (extendp (string-match-p "\\+\\'" key))
15215 (key-base (if extendp (substring key 0 -1) key))
15216 (value (match-string-no-properties 3)))
15217 (cond
15218 ((member-ignore-case key-base org-special-properties))
15219 (extendp
15220 (setq props
15221 (org--update-property-plist key value props)))
15222 ((member key seen-base))
15223 (t (push key seen-base)
15224 (let ((p (assoc-string key props t)))
15225 (if p (setcdr p (concat value " " (cdr p)))
15226 (push (cons key value) props))))))))))))
15227 (unless (assoc "CATEGORY" props)
15228 (push (cons "CATEGORY" (org-get-category beg)) props)
15229 (when (string= specific "CATEGORY") (throw 'exit props)))
15230 ;; Return value.
15231 props)))))
15233 (defun org--property-local-values (property literal-nil)
15234 "Return value for PROPERTY in current entry.
15235 Value is a list whose car is the base value for PROPERTY and cdr
15236 a list of accumulated values. Return nil if neither is found in
15237 the entry. Also return nil when PROPERTY is set to \"nil\",
15238 unless LITERAL-NIL is non-nil."
15239 (let ((range (org-get-property-block)))
15240 (when range
15241 (goto-char (car range))
15242 (let* ((case-fold-search t)
15243 (end (cdr range))
15244 (value
15245 ;; Base value.
15246 (save-excursion
15247 (let ((v (and (re-search-forward
15248 (org-re-property property nil t) end t)
15249 (match-string-no-properties 3))))
15250 (list (if literal-nil v (org-not-nil v)))))))
15251 ;; Find additional values.
15252 (let* ((property+ (org-re-property (concat property "+") nil t)))
15253 (while (re-search-forward property+ end t)
15254 (push (match-string-no-properties 3) value)))
15255 ;; Return final values.
15256 (and (not (equal value '(nil))) (nreverse value))))))
15258 (defun org--property-global-value (property literal-nil)
15259 "Return value for PROPERTY in current buffer.
15260 Return value is a string. Return nil if property is not set
15261 globally. Also return nil when PROPERTY is set to \"nil\",
15262 unless LITERAL-NIL is non-nil."
15263 (let ((global
15264 (cdr (or (assoc-string property org-file-properties t)
15265 (assoc-string property org-global-properties t)
15266 (assoc-string property org-global-properties-fixed t)))))
15267 (if literal-nil global (org-not-nil global))))
15269 (defun org-entry-get (pom property &optional inherit literal-nil)
15270 "Get value of PROPERTY for entry or content at point-or-marker POM.
15272 If INHERIT is non-nil and the entry does not have the property,
15273 then also check higher levels of the hierarchy. If INHERIT is
15274 the symbol `selective', use inheritance only if the setting in
15275 `org-use-property-inheritance' selects PROPERTY for inheritance.
15277 If the property is present but empty, the return value is the
15278 empty string. If the property is not present at all, nil is
15279 returned. In any other case, return the value as a string.
15280 Search is case-insensitive.
15282 If LITERAL-NIL is set, return the string value \"nil\" as
15283 a string, do not interpret it as the list atom nil. This is used
15284 for inheritance when a \"nil\" value can supersede a non-nil
15285 value higher up the hierarchy."
15286 (org-with-point-at pom
15287 (cond
15288 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15289 ;; We need a special property. Use `org-entry-properties' to
15290 ;; retrieve it, but specify the wanted property.
15291 (cdr (assoc-string property (org-entry-properties nil property))))
15292 ((and inherit
15293 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15294 (org-entry-get-with-inheritance property literal-nil))
15296 (let* ((local (org--property-local-values property literal-nil))
15297 (value (and local (mapconcat #'identity (delq nil local) " "))))
15298 (if literal-nil value (org-not-nil value)))))))
15300 (defun org-property-or-variable-value (var &optional inherit)
15301 "Check if there is a property fixing the value of VAR.
15302 If yes, return this value. If not, return the current value of the variable."
15303 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15304 (if (and prop (stringp prop) (string-match "\\S-" prop))
15305 (read prop)
15306 (symbol-value var))))
15308 (defun org-entry-delete (pom property)
15309 "Delete PROPERTY from entry at point-or-marker POM.
15310 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15311 non-nil when a property was removed."
15312 (org-with-point-at pom
15313 (pcase (org-get-property-block)
15314 (`(,begin . ,origin)
15315 (let* ((end (copy-marker origin))
15316 (re (org-re-property
15317 (concat (regexp-quote property) "\\+?") t t)))
15318 (goto-char begin)
15319 (while (re-search-forward re end t)
15320 (delete-region (match-beginning 0) (line-beginning-position 2)))
15321 ;; If drawer is empty, remove it altogether.
15322 (when (= begin end)
15323 (delete-region (line-beginning-position 0)
15324 (line-beginning-position 2)))
15325 ;; Return non-nil if some property was removed.
15326 (prog1 (/= end origin) (set-marker end nil))))
15327 (_ nil))))
15329 ;; Multi-values properties are properties that contain multiple values
15330 ;; These values are assumed to be single words, separated by whitespace.
15331 (defun org-entry-add-to-multivalued-property (pom property value)
15332 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15333 (let* ((old (org-entry-get pom property))
15334 (values (and old (split-string old))))
15335 (setq value (org-entry-protect-space value))
15336 (unless (member value values)
15337 (setq values (append values (list value)))
15338 (org-entry-put pom property (mapconcat #'identity values " ")))))
15340 (defun org-entry-remove-from-multivalued-property (pom property value)
15341 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15342 (let* ((old (org-entry-get pom property))
15343 (values (and old (split-string old))))
15344 (setq value (org-entry-protect-space value))
15345 (when (member value values)
15346 (setq values (delete value values))
15347 (org-entry-put pom property (mapconcat #'identity values " ")))))
15349 (defun org-entry-member-in-multivalued-property (pom property value)
15350 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15351 (let* ((old (org-entry-get pom property))
15352 (values (and old (split-string old))))
15353 (setq value (org-entry-protect-space value))
15354 (member value values)))
15356 (defun org-entry-get-multivalued-property (pom property)
15357 "Return a list of values in a multivalued property."
15358 (let* ((value (org-entry-get pom property))
15359 (values (and value (split-string value))))
15360 (mapcar #'org-entry-restore-space values)))
15362 (defun org-entry-put-multivalued-property (pom property &rest values)
15363 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15364 VALUES should be a list of strings. Spaces will be protected."
15365 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15366 (let* ((value (org-entry-get pom property))
15367 (values (and value (split-string value))))
15368 (mapcar #'org-entry-restore-space values)))
15370 (defun org-entry-protect-space (s)
15371 "Protect spaces and newline in string S."
15372 (while (string-match " " s)
15373 (setq s (replace-match "%20" t t s)))
15374 (while (string-match "\n" s)
15375 (setq s (replace-match "%0A" t t s)))
15378 (defun org-entry-restore-space (s)
15379 "Restore spaces and newline in string S."
15380 (while (string-match "%20" s)
15381 (setq s (replace-match " " t t s)))
15382 (while (string-match "%0A" s)
15383 (setq s (replace-match "\n" t t s)))
15386 (defvar org-entry-property-inherited-from (make-marker)
15387 "Marker pointing to the entry from where a property was inherited.
15388 Each call to `org-entry-get-with-inheritance' will set this marker to the
15389 location of the entry where the inheritance search matched. If there was
15390 no match, the marker will point nowhere.
15391 Note that also `org-entry-get' calls this function, if the INHERIT flag
15392 is set.")
15394 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15395 "Get PROPERTY of entry or content at point, search higher levels if needed.
15396 The search will stop at the first ancestor which has the property defined.
15397 If the value found is \"nil\", return nil to show that the property
15398 should be considered as undefined (this is the meaning of nil here).
15399 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15400 (move-marker org-entry-property-inherited-from nil)
15401 (org-with-wide-buffer
15402 (let (value)
15403 (catch 'exit
15404 (while t
15405 (let ((v (org--property-local-values property literal-nil)))
15406 (when v
15407 (setq value
15408 (concat (mapconcat #'identity (delq nil v) " ")
15409 (and value " ")
15410 value)))
15411 (cond
15412 ((car v)
15413 (org-back-to-heading t)
15414 (move-marker org-entry-property-inherited-from (point))
15415 (throw 'exit nil))
15416 ((org-up-heading-safe))
15418 (let ((global (org--property-global-value property literal-nil)))
15419 (cond ((not global))
15420 (value (setq value (concat global " " value)))
15421 (t (setq value global))))
15422 (throw 'exit nil))))))
15423 (if literal-nil value (org-not-nil value)))))
15425 (defvar org-property-changed-functions nil
15426 "Hook called when the value of a property has changed.
15427 Each hook function should accept two arguments, the name of the property
15428 and the new value.")
15430 (defun org-entry-put (pom property value)
15431 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15433 If the value is nil, it is converted to the empty string. If it
15434 is not a string, an error is raised. Also raise an error on
15435 invalid property names.
15437 PROPERTY can be any regular property (see
15438 `org-special-properties'). It can also be \"TODO\",
15439 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15441 For the last two properties, VALUE may have any of the special
15442 values \"earlier\" and \"later\". The function then increases or
15443 decreases scheduled or deadline date by one day."
15444 (cond ((null value) (setq value ""))
15445 ((not (stringp value)) (error "Properties values should be strings"))
15446 ((not (org--valid-property-p property))
15447 (user-error "Invalid property name: \"%s\"" property)))
15448 (org-with-point-at pom
15449 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15450 (org-back-to-heading t)
15451 (org-with-limited-levels (org-back-to-heading t)))
15452 (let ((beg (point)))
15453 (cond
15454 ((equal property "TODO")
15455 (cond ((not (org-string-nw-p value)) (setq value 'none))
15456 ((not (member value org-todo-keywords-1))
15457 (user-error "\"%s\" is not a valid TODO state" value)))
15458 (org-todo value)
15459 (org-set-tags nil 'align))
15460 ((equal property "PRIORITY")
15461 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15462 (org-set-tags nil 'align))
15463 ((equal property "SCHEDULED")
15464 (forward-line)
15465 (if (and (looking-at-p org-planning-line-re)
15466 (re-search-forward
15467 org-scheduled-time-regexp (line-end-position) t))
15468 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15469 ((string= value "later") (org-timestamp-change 1 'day))
15470 ((string= value "") (org-schedule '(4)))
15471 (t (org-schedule nil value)))
15472 (if (member value '("earlier" "later" ""))
15473 (call-interactively #'org-schedule)
15474 (org-schedule nil value))))
15475 ((equal property "DEADLINE")
15476 (forward-line)
15477 (if (and (looking-at-p org-planning-line-re)
15478 (re-search-forward
15479 org-deadline-time-regexp (line-end-position) t))
15480 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15481 ((string= value "later") (org-timestamp-change 1 'day))
15482 ((string= value "") (org-deadline '(4)))
15483 (t (org-deadline nil value)))
15484 (if (member value '("earlier" "later" ""))
15485 (call-interactively #'org-deadline)
15486 (org-deadline nil value))))
15487 ((member property org-special-properties)
15488 (error "The %s property cannot be set with `org-entry-put'" property))
15490 (let* ((range (org-get-property-block beg 'force))
15491 (end (cdr range))
15492 (case-fold-search t))
15493 (goto-char (car range))
15494 (if (re-search-forward (org-re-property property nil t) end t)
15495 (progn (delete-region (match-beginning 0) (match-end 0))
15496 (goto-char (match-beginning 0)))
15497 (goto-char end)
15498 (insert "\n")
15499 (backward-char))
15500 (insert ":" property ":")
15501 (when value (insert " " value))
15502 (org-indent-line)))))
15503 (run-hook-with-args 'org-property-changed-functions property value)))
15505 (defun org-buffer-property-keys (&optional specials defaults columns)
15506 "Get all property keys in the current buffer.
15508 When SPECIALS is non-nil, also list the special properties that
15509 reflect things like tags and TODO state.
15511 When DEFAULTS is non-nil, also include properties that has
15512 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15513 DESCRIPTION, LOCATION, and LOGGING and others.
15515 When COLUMNS in non-nil, also include property names given in
15516 COLUMN formats in the current buffer."
15517 (let ((case-fold-search t)
15518 (props (append
15519 (and specials org-special-properties)
15520 (and defaults (cons org-effort-property org-default-properties))
15521 nil)))
15522 (org-with-wide-buffer
15523 (goto-char (point-min))
15524 (while (re-search-forward org-property-start-re nil t)
15525 (catch :skip
15526 (let ((range (org-get-property-block)))
15527 (unless range (throw :skip nil))
15528 (goto-char (car range))
15529 (let ((begin (car range))
15530 (end (cdr range)))
15531 ;; Make sure that found property block is not located
15532 ;; before current point, as it would generate an infloop.
15533 ;; It can happen, for example, in the following
15534 ;; situation:
15536 ;; * Headline
15537 ;; :PROPERTIES:
15538 ;; ...
15539 ;; :END:
15540 ;; *************** Inlinetask
15541 ;; #+BEGIN_EXAMPLE
15542 ;; :PROPERTIES:
15543 ;; #+END_EXAMPLE
15545 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15546 (while (< (point) end)
15547 (let ((p (progn (looking-at org-property-re)
15548 (match-string-no-properties 2))))
15549 ;; Only add true property name, not extension symbol.
15550 (push (if (not (string-match-p "\\+\\'" p)) p
15551 (substring p 0 -1))
15552 props))
15553 (forward-line))))
15554 (outline-next-heading)))
15555 (when columns
15556 (goto-char (point-min))
15557 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15558 (let ((element (org-element-at-point)))
15559 (when (memq (org-element-type element) '(keyword node-property))
15560 (let ((value (org-element-property :value element))
15561 (start 0))
15562 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15563 \\(?:{[^}]+}\\)?"
15564 value start)
15565 (setq start (match-end 0))
15566 (let ((p (match-string-no-properties 1 value)))
15567 (unless (member-ignore-case p org-special-properties)
15568 (push p props))))))))))
15569 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15571 (defun org-property-values (key)
15572 "List all non-nil values of property KEY in current buffer."
15573 (org-with-wide-buffer
15574 (goto-char (point-min))
15575 (let ((case-fold-search t)
15576 (re (org-re-property key))
15577 values)
15578 (while (re-search-forward re nil t)
15579 (push (org-entry-get (point) key) values))
15580 (delete-dups values))))
15582 (defun org-insert-property-drawer ()
15583 "Insert a property drawer into the current entry."
15584 (org-with-wide-buffer
15585 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15586 (org-back-to-heading t)
15587 (org-with-limited-levels (org-back-to-heading t)))
15588 (forward-line)
15589 (when (looking-at-p org-planning-line-re) (forward-line))
15590 (unless (looking-at-p org-property-drawer-re)
15591 ;; Make sure we start editing a line from current entry, not from
15592 ;; next one. It prevents extending text properties or overlays
15593 ;; belonging to the latter.
15594 (when (bolp) (backward-char))
15595 (let ((begin (1+ (point)))
15596 (inhibit-read-only t))
15597 (insert "\n:PROPERTIES:\n:END:")
15598 (when (eobp) (insert "\n"))
15599 (org-indent-region begin (point))))))
15601 (defun org-insert-drawer (&optional arg drawer)
15602 "Insert a drawer at point.
15604 When optional argument ARG is non-nil, insert a property drawer.
15606 Optional argument DRAWER, when non-nil, is a string representing
15607 drawer's name. Otherwise, the user is prompted for a name.
15609 If a region is active, insert the drawer around that region
15610 instead.
15612 Point is left between drawer's boundaries."
15613 (interactive "P")
15614 (let* ((drawer (if arg "PROPERTIES"
15615 (or drawer (read-from-minibuffer "Drawer: ")))))
15616 (cond
15617 ;; With C-u, fall back on `org-insert-property-drawer'
15618 (arg (org-insert-property-drawer))
15619 ;; Check validity of suggested drawer's name.
15620 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15621 (user-error "Invalid drawer name"))
15622 ;; With an active region, insert a drawer at point.
15623 ((not (org-region-active-p))
15624 (progn
15625 (unless (bolp) (insert "\n"))
15626 (insert (format ":%s:\n\n:END:\n" drawer))
15627 (forward-line -2)))
15628 ;; Otherwise, insert the drawer at point
15630 (let ((rbeg (region-beginning))
15631 (rend (copy-marker (region-end))))
15632 (unwind-protect
15633 (progn
15634 (goto-char rbeg)
15635 (beginning-of-line)
15636 (when (save-excursion
15637 (re-search-forward org-outline-regexp-bol rend t))
15638 (user-error "Drawers cannot contain headlines"))
15639 ;; Position point at the beginning of the first
15640 ;; non-blank line in region. Insert drawer's opening
15641 ;; there, then indent it.
15642 (org-skip-whitespace)
15643 (beginning-of-line)
15644 (insert ":" drawer ":\n")
15645 (forward-line -1)
15646 (indent-for-tab-command)
15647 ;; Move point to the beginning of the first blank line
15648 ;; after the last non-blank line in region. Insert
15649 ;; drawer's closing, then indent it.
15650 (goto-char rend)
15651 (skip-chars-backward " \r\t\n")
15652 (insert "\n:END:")
15653 (deactivate-mark t)
15654 (indent-for-tab-command)
15655 (unless (eolp) (insert "\n")))
15656 ;; Clear marker, whatever the outcome of insertion is.
15657 (set-marker rend nil)))))))
15659 (defvar org-property-set-functions-alist nil
15660 "Property set function alist.
15661 Each entry should have the following format:
15663 (PROPERTY . READ-FUNCTION)
15665 The read function will be called with the same argument as
15666 `org-completing-read'.")
15668 (defun org-set-property-function (property)
15669 "Get the function that should be used to set PROPERTY.
15670 This is computed according to `org-property-set-functions-alist'."
15671 (or (cdr (assoc property org-property-set-functions-alist))
15672 'org-completing-read))
15674 (defun org-read-property-value (property)
15675 "Read PROPERTY value from user."
15676 (let* ((completion-ignore-case t)
15677 (allowed (org-property-get-allowed-values nil property 'table))
15678 (cur (org-entry-get nil property))
15679 (prompt (concat property " value"
15680 (if (and cur (string-match "\\S-" cur))
15681 (concat " [" cur "]") "") ": "))
15682 (set-function (org-set-property-function property))
15683 (val (if allowed
15684 (funcall set-function prompt allowed nil
15685 (not (get-text-property 0 'org-unrestricted
15686 (caar allowed))))
15687 (funcall set-function prompt
15688 (mapcar 'list (org-property-values property))
15689 nil nil "" nil cur))))
15690 (org-trim val)))
15692 (defvar org-last-set-property nil)
15693 (defvar org-last-set-property-value nil)
15694 (defun org-read-property-name ()
15695 "Read a property name."
15696 (let ((completion-ignore-case t)
15697 (default-prop (or (and (org-at-property-p)
15698 (match-string-no-properties 2))
15699 org-last-set-property)))
15700 (org-completing-read
15701 (concat "Property"
15702 (if default-prop (concat " [" default-prop "]") "")
15703 ": ")
15704 (mapcar #'list (org-buffer-property-keys nil t t))
15705 nil nil nil nil default-prop)))
15707 (defun org-set-property-and-value (use-last)
15708 "Allow to set [PROPERTY]: [value] direction from prompt.
15709 When use-default, don't even ask, just use the last
15710 \"[PROPERTY]: [value]\" string from the history."
15711 (interactive "P")
15712 (let* ((completion-ignore-case t)
15713 (pv (or (and use-last org-last-set-property-value)
15714 (org-completing-read
15715 "Enter a \"[Property]: [value]\" pair: "
15716 nil nil nil nil nil
15717 org-last-set-property-value)))
15718 prop val)
15719 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15720 (setq prop (match-string 1 pv)
15721 val (match-string 2 pv))
15722 (org-set-property prop val))))
15724 (defun org-set-property (property value)
15725 "In the current entry, set PROPERTY to VALUE.
15727 When called interactively, this will prompt for a property name, offering
15728 completion on existing and default properties. And then it will prompt
15729 for a value, offering completion either on allowed values (via an inherited
15730 xxx_ALL property) or on existing values in other instances of this property
15731 in the current file.
15733 Throw an error when trying to set a property with an invalid name."
15734 (interactive (list nil nil))
15735 (let ((property (or property (org-read-property-name))))
15736 ;; `org-entry-put' also makes the following check, but this one
15737 ;; avoids polluting `org-last-set-property' and
15738 ;; `org-last-set-property-value' needlessly.
15739 (unless (org--valid-property-p property)
15740 (user-error "Invalid property name: \"%s\"" property))
15741 (let ((value (or value (org-read-property-value property)))
15742 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15743 (setq org-last-set-property property)
15744 (setq org-last-set-property-value (concat property ": " value))
15745 ;; Possibly postprocess the inserted value:
15746 (when fn (setq value (funcall fn value)))
15747 (unless (equal (org-entry-get nil property) value)
15748 (org-entry-put nil property value)))))
15750 (defun org-find-property (property &optional value)
15751 "Find first entry in buffer that sets PROPERTY.
15753 When optional argument VALUE is non-nil, only consider an entry
15754 if it contains PROPERTY set to this value. If PROPERTY should be
15755 explicitly set to nil, use string \"nil\" for VALUE.
15757 Return position where the entry begins, or nil if there is no
15758 such entry. If narrowing is in effect, only search the visible
15759 part of the buffer."
15760 (save-excursion
15761 (goto-char (point-min))
15762 (let ((case-fold-search t)
15763 (re (org-re-property property nil (not value) value)))
15764 (catch 'exit
15765 (while (re-search-forward re nil t)
15766 (when (if value (org-at-property-p)
15767 (org-entry-get (point) property nil t))
15768 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15770 (defun org-delete-property (property)
15771 "In the current entry, delete PROPERTY."
15772 (interactive
15773 (let* ((completion-ignore-case t)
15774 (cat (org-entry-get (point) "CATEGORY"))
15775 (props0 (org-entry-properties nil 'standard))
15776 (props (if cat props0
15777 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15778 (prop (if (< 1 (length props))
15779 (completing-read "Property: " props nil t)
15780 (caar props))))
15781 (list prop)))
15782 (if (not property)
15783 (message "No property to delete in this entry")
15784 (org-entry-delete nil property)
15785 (message "Property \"%s\" deleted" property)))
15787 (defun org-delete-property-globally (property)
15788 "Remove PROPERTY globally, from all entries.
15789 This function ignores narrowing, if any."
15790 (interactive
15791 (let* ((completion-ignore-case t)
15792 (prop (completing-read
15793 "Globally remove property: "
15794 (mapcar #'list (org-buffer-property-keys)))))
15795 (list prop)))
15796 (org-with-wide-buffer
15797 (goto-char (point-min))
15798 (let ((count 0)
15799 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15800 (while (re-search-forward re nil t)
15801 (when (org-entry-delete (point) property) (cl-incf count)))
15802 (message "Property \"%s\" removed from %d entries" property count))))
15804 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15806 (defun org-compute-property-at-point ()
15807 "Compute the property at point.
15808 This looks for an enclosing column format, extracts the operator and
15809 then applies it to the property in the column format's scope."
15810 (interactive)
15811 (unless (org-at-property-p)
15812 (user-error "Not at a property"))
15813 (let ((prop (match-string-no-properties 2)))
15814 (org-columns-get-format-and-top-level)
15815 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15816 (user-error "No operator defined for property %s" prop))
15817 (org-columns-compute prop)))
15819 (defvar org-property-allowed-value-functions nil
15820 "Hook for functions supplying allowed values for a specific property.
15821 The functions must take a single argument, the name of the property, and
15822 return a flat list of allowed values. If \":ETC\" is one of
15823 the values, this means that these values are intended as defaults for
15824 completion, but that other values should be allowed too.
15825 The functions must return nil if they are not responsible for this
15826 property.")
15828 (defun org-property-get-allowed-values (pom property &optional table)
15829 "Get allowed values for the property PROPERTY.
15830 When TABLE is non-nil, return an alist that can directly be used for
15831 completion."
15832 (let (vals)
15833 (cond
15834 ((equal property "TODO")
15835 (setq vals (org-with-point-at pom
15836 (append org-todo-keywords-1 '("")))))
15837 ((equal property "PRIORITY")
15838 (let ((n org-lowest-priority))
15839 (while (>= n org-highest-priority)
15840 (push (char-to-string n) vals)
15841 (setq n (1- n)))))
15842 ((equal property "CATEGORY"))
15843 ((member property org-special-properties))
15844 ((setq vals (run-hook-with-args-until-success
15845 'org-property-allowed-value-functions property)))
15847 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15848 (when (and vals (string-match "\\S-" vals))
15849 (setq vals (car (read-from-string (concat "(" vals ")"))))
15850 (setq vals (mapcar (lambda (x)
15851 (cond ((stringp x) x)
15852 ((numberp x) (number-to-string x))
15853 ((symbolp x) (symbol-name x))
15854 (t "???")))
15855 vals)))))
15856 (when (member ":ETC" vals)
15857 (setq vals (remove ":ETC" vals))
15858 (org-add-props (car vals) '(org-unrestricted t)))
15859 (if table (mapcar 'list vals) vals)))
15861 (defun org-property-previous-allowed-value (&optional _previous)
15862 "Switch to the next allowed value for this property."
15863 (interactive)
15864 (org-property-next-allowed-value t))
15866 (defun org-property-next-allowed-value (&optional previous)
15867 "Switch to the next allowed value for this property."
15868 (interactive)
15869 (unless (org-at-property-p)
15870 (user-error "Not at a property"))
15871 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15872 (key (match-string 2))
15873 (value (match-string 3))
15874 (allowed (or (org-property-get-allowed-values (point) key)
15875 (and (member value '("[ ]" "[-]" "[X]"))
15876 '("[ ]" "[X]"))))
15877 (heading (save-match-data (nth 4 (org-heading-components))))
15878 nval)
15879 (unless allowed
15880 (user-error "Allowed values for this property have not been defined"))
15881 (when previous (setq allowed (reverse allowed)))
15882 (when (member value allowed)
15883 (setq nval (car (cdr (member value allowed)))))
15884 (setq nval (or nval (car allowed)))
15885 (when (equal nval value)
15886 (user-error "Only one allowed value for this property"))
15887 (org-at-property-p)
15888 (replace-match (concat " :" key ": " nval) t t)
15889 (org-indent-line)
15890 (beginning-of-line 1)
15891 (skip-chars-forward " \t")
15892 (when (equal prop org-effort-property)
15893 (org-refresh-property
15894 '((effort . identity)
15895 (effort-minutes . org-duration-to-minutes))
15896 nval)
15897 (when (string= org-clock-current-task heading)
15898 (setq org-clock-effort nval)
15899 (org-clock-update-mode-line)))
15900 (run-hook-with-args 'org-property-changed-functions key nval)))
15902 (defun org-find-olp (path &optional this-buffer)
15903 "Return a marker pointing to the entry at outline path OLP.
15904 If anything goes wrong, throw an error.
15905 You can wrap this call to catch the error like this:
15907 (condition-case msg
15908 (org-mobile-locate-entry (match-string 4))
15909 (error (nth 1 msg)))
15911 The return value will then be either a string with the error message,
15912 or a marker if everything is OK.
15914 If THIS-BUFFER is set, the outline path does not contain a file,
15915 only headings."
15916 (let* ((file (if this-buffer buffer-file-name (pop path)))
15917 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15918 (level 1)
15919 (lmin 1)
15920 (lmax 1)
15921 end found flevel)
15922 (unless buffer (error "File not found :%s" file))
15923 (with-current-buffer buffer
15924 (unless (derived-mode-p 'org-mode)
15925 (error "Buffer %s needs to be in Org mode" buffer))
15926 (org-with-wide-buffer
15927 (goto-char (point-min))
15928 (dolist (heading path)
15929 (let ((re (format org-complex-heading-regexp-format
15930 (regexp-quote heading)))
15931 (cnt 0))
15932 (while (re-search-forward re end t)
15933 (setq level (- (match-end 1) (match-beginning 1)))
15934 (when (and (>= level lmin) (<= level lmax))
15935 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15936 (when (= cnt 0)
15937 (error "Heading not found on level %d: %s" lmax heading))
15938 (when (> cnt 1)
15939 (error "Heading not unique on level %d: %s" lmax heading))
15940 (goto-char found)
15941 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15942 (setq end (save-excursion (org-end-of-subtree t t)))))
15943 (when (org-at-heading-p)
15944 (point-marker))))))
15946 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15947 "Find node HEADING in BUFFER.
15948 Return a marker to the heading if it was found, or nil if not.
15949 If POS-ONLY is set, return just the position instead of a marker.
15951 The heading text must match exact, but it may have a TODO keyword,
15952 a priority cookie and tags in the standard locations."
15953 (with-current-buffer (or buffer (current-buffer))
15954 (org-with-wide-buffer
15955 (goto-char (point-min))
15956 (let (case-fold-search)
15957 (when (re-search-forward
15958 (format org-complex-heading-regexp-format
15959 (regexp-quote heading)) nil t)
15960 (if pos-only
15961 (match-beginning 0)
15962 (move-marker (make-marker) (match-beginning 0))))))))
15964 (defun org-find-exact-heading-in-directory (heading &optional dir)
15965 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15966 When the target headline is found, return a marker to this location."
15967 (let ((files (directory-files (or dir default-directory)
15968 t "\\`[^.#].*\\.org\\'"))
15969 visiting m buffer)
15970 (catch 'found
15971 (dolist (file files)
15972 (message "trying %s" file)
15973 (setq visiting (org-find-base-buffer-visiting file))
15974 (setq buffer (or visiting (find-file-noselect file)))
15975 (setq m (org-find-exact-headline-in-buffer
15976 heading buffer))
15977 (when (and (not m) (not visiting)) (kill-buffer buffer))
15978 (and m (throw 'found m))))))
15980 (defun org-find-entry-with-id (ident)
15981 "Locate the entry that contains the ID property with exact value IDENT.
15982 IDENT can be a string, a symbol or a number, this function will search for
15983 the string representation of it.
15984 Return the position where this entry starts, or nil if there is no such entry."
15985 (interactive "sID: ")
15986 (let ((id (cond
15987 ((stringp ident) ident)
15988 ((symbolp ident) (symbol-name ident))
15989 ((numberp ident) (number-to-string ident))
15990 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15991 (org-with-wide-buffer (org-find-property "ID" id))))
15993 ;;;; Timestamps
15995 (defvar org-last-changed-timestamp nil)
15996 (defvar org-last-inserted-timestamp nil
15997 "The last time stamp inserted with `org-insert-time-stamp'.")
15999 (defun org-time-stamp (arg &optional inactive)
16000 "Prompt for a date/time and insert a time stamp.
16002 If the user specifies a time like HH:MM or if this command is
16003 called with at least one prefix argument, the time stamp contains
16004 the date and the time. Otherwise, only the date is included.
16006 All parts of a date not specified by the user are filled in from
16007 the timestamp at point, if any, or the current date/time
16008 otherwise.
16010 If there is already a timestamp at the cursor, it is replaced.
16012 With two universal prefix arguments, insert an active timestamp
16013 with the current time without prompting the user.
16015 When called from lisp, the timestamp is inactive if INACTIVE is
16016 non-nil."
16017 (interactive "P")
16018 (let* ((ts (cond
16019 ((org-at-date-range-p t)
16020 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16021 ((org-at-timestamp-p 'lax) (match-string 0))))
16022 ;; Default time is either the timestamp at point or today.
16023 ;; When entering a range, only the range start is considered.
16024 (default-time (if (not ts) (current-time)
16025 (apply #'encode-time (org-parse-time-string ts))))
16026 (default-input (and ts (org-get-compact-tod ts)))
16027 (repeater (and ts
16028 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16029 (match-string 0 ts)))
16030 org-time-was-given
16031 org-end-time-was-given
16032 (time
16033 (and (if (equal arg '(16)) (current-time)
16034 ;; Preserve `this-command' and `last-command'.
16035 (let ((this-command this-command)
16036 (last-command last-command))
16037 (org-read-date
16038 arg 'totime nil nil default-time default-input
16039 inactive))))))
16040 (cond
16041 ((and ts
16042 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16043 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16044 (insert "--")
16045 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16047 ;; Make sure we're on a timestamp. When in the middle of a date
16048 ;; range, move arbitrarily to range end.
16049 (unless (org-at-timestamp-p 'lax)
16050 (skip-chars-forward "-")
16051 (org-at-timestamp-p 'lax))
16052 (replace-match "")
16053 (setq org-last-changed-timestamp
16054 (org-insert-time-stamp
16055 time (or org-time-was-given arg)
16056 inactive nil nil (list org-end-time-was-given)))
16057 (when repeater
16058 (backward-char)
16059 (insert " " repeater)
16060 (setq org-last-changed-timestamp
16061 (concat (substring org-last-inserted-timestamp 0 -1)
16062 " " repeater ">")))
16063 (message "Timestamp updated"))
16064 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16065 (t (org-insert-time-stamp
16066 time (or org-time-was-given arg) inactive nil nil
16067 (list org-end-time-was-given))))))
16069 ;; FIXME: can we use this for something else, like computing time differences?
16070 (defun org-get-compact-tod (s)
16071 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16072 (let* ((t1 (match-string 1 s))
16073 (h1 (string-to-number (match-string 2 s)))
16074 (m1 (string-to-number (match-string 3 s)))
16075 (t2 (and (match-end 4) (match-string 5 s)))
16076 (h2 (and t2 (string-to-number (match-string 6 s))))
16077 (m2 (and t2 (string-to-number (match-string 7 s))))
16078 dh dm)
16079 (if (not t2)
16081 (setq dh (- h2 h1) dm (- m2 m1))
16082 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16083 (concat t1 "+" (number-to-string dh)
16084 (and (/= 0 dm) (format ":%02d" dm)))))))
16086 (defun org-time-stamp-inactive (&optional arg)
16087 "Insert an inactive time stamp.
16089 An inactive time stamp is enclosed in square brackets instead of angle
16090 brackets. It is inactive in the sense that it does not trigger agenda entries,
16091 does not link to the calendar and cannot be changed with the S-cursor keys.
16092 So these are more for recording a certain time/date.
16094 If the user specifies a time like HH:MM or if this command is called with
16095 at least one prefix argument, the time stamp contains the date and the time.
16096 Otherwise, only the date is included.
16098 When called with two universal prefix arguments, insert an active time stamp
16099 with the current time without prompting the user."
16100 (interactive "P")
16101 (org-time-stamp arg 'inactive))
16103 (defvar org-date-ovl (make-overlay 1 1))
16104 (overlay-put org-date-ovl 'face 'org-date-selected)
16105 (delete-overlay org-date-ovl)
16107 (defvar org-ans1) ; dynamically scoped parameter
16108 (defvar org-ans2) ; dynamically scoped parameter
16110 (defvar org-plain-time-of-day-regexp) ; defined below
16112 (defvar org-overriding-default-time nil) ; dynamically scoped
16113 (defvar org-read-date-overlay nil)
16114 (defvar org-dcst nil) ; dynamically scoped
16115 (defvar org-read-date-history nil)
16116 (defvar org-read-date-final-answer nil)
16117 (defvar org-read-date-analyze-futurep nil)
16118 (defvar org-read-date-analyze-forced-year nil)
16119 (defvar org-read-date-inactive)
16121 (defvar org-read-date-minibuffer-local-map
16122 (let* ((map (make-sparse-keymap)))
16123 (set-keymap-parent map minibuffer-local-map)
16124 (org-defkey map (kbd ".")
16125 (lambda () (interactive)
16126 ;; Are we at the beginning of the prompt?
16127 (if (looking-back "^[^:]+: "
16128 (let ((inhibit-field-text-motion t))
16129 (line-beginning-position)))
16130 (org-eval-in-calendar '(calendar-goto-today))
16131 (insert "."))))
16132 (org-defkey map (kbd "C-.")
16133 (lambda () (interactive)
16134 (org-eval-in-calendar '(calendar-goto-today))))
16135 (org-defkey map (kbd "M-S-<left>")
16136 (lambda () (interactive)
16137 (org-eval-in-calendar '(calendar-backward-month 1))))
16138 (org-defkey map (kbd "ESC S-<left>")
16139 (lambda () (interactive)
16140 (org-eval-in-calendar '(calendar-backward-month 1))))
16141 (org-defkey map (kbd "M-S-<right>")
16142 (lambda () (interactive)
16143 (org-eval-in-calendar '(calendar-forward-month 1))))
16144 (org-defkey map (kbd "ESC S-<right>")
16145 (lambda () (interactive)
16146 (org-eval-in-calendar '(calendar-forward-month 1))))
16147 (org-defkey map (kbd "M-S-<up>")
16148 (lambda () (interactive)
16149 (org-eval-in-calendar '(calendar-backward-year 1))))
16150 (org-defkey map (kbd "ESC S-<up>")
16151 (lambda () (interactive)
16152 (org-eval-in-calendar '(calendar-backward-year 1))))
16153 (org-defkey map (kbd "M-S-<down>")
16154 (lambda () (interactive)
16155 (org-eval-in-calendar '(calendar-forward-year 1))))
16156 (org-defkey map (kbd "ESC S-<down>")
16157 (lambda () (interactive)
16158 (org-eval-in-calendar '(calendar-forward-year 1))))
16159 (org-defkey map (kbd "S-<up>")
16160 (lambda () (interactive)
16161 (org-eval-in-calendar '(calendar-backward-week 1))))
16162 (org-defkey map (kbd "S-<down>")
16163 (lambda () (interactive)
16164 (org-eval-in-calendar '(calendar-forward-week 1))))
16165 (org-defkey map (kbd "S-<left>")
16166 (lambda () (interactive)
16167 (org-eval-in-calendar '(calendar-backward-day 1))))
16168 (org-defkey map (kbd "S-<right>")
16169 (lambda () (interactive)
16170 (org-eval-in-calendar '(calendar-forward-day 1))))
16171 (org-defkey map (kbd "!")
16172 (lambda () (interactive)
16173 (org-eval-in-calendar '(diary-view-entries))
16174 (message "")))
16175 (org-defkey map (kbd ">")
16176 (lambda () (interactive)
16177 (org-eval-in-calendar '(calendar-scroll-left 1))))
16178 (org-defkey map (kbd "<")
16179 (lambda () (interactive)
16180 (org-eval-in-calendar '(calendar-scroll-right 1))))
16181 (org-defkey map (kbd "C-v")
16182 (lambda () (interactive)
16183 (org-eval-in-calendar
16184 '(calendar-scroll-left-three-months 1))))
16185 (org-defkey map (kbd "M-v")
16186 (lambda () (interactive)
16187 (org-eval-in-calendar
16188 '(calendar-scroll-right-three-months 1))))
16189 map)
16190 "Keymap for minibuffer commands when using `org-read-date'.")
16192 (defvar org-def)
16193 (defvar org-defdecode)
16194 (defvar org-with-time)
16196 (defvar calendar-setup) ; Dynamically scoped.
16197 (defun org-read-date (&optional with-time to-time from-string prompt
16198 default-time default-input inactive)
16199 "Read a date, possibly a time, and make things smooth for the user.
16200 The prompt will suggest to enter an ISO date, but you can also enter anything
16201 which will at least partially be understood by `parse-time-string'.
16202 Unrecognized parts of the date will default to the current day, month, year,
16203 hour and minute. If this command is called to replace a timestamp at point,
16204 or to enter the second timestamp of a range, the default time is taken
16205 from the existing stamp. Furthermore, the command prefers the future,
16206 so if you are giving a date where the year is not given, and the day-month
16207 combination is already past in the current year, it will assume you
16208 mean next year. For details, see the manual. A few examples:
16210 3-2-5 --> 2003-02-05
16211 feb 15 --> currentyear-02-15
16212 2/15 --> currentyear-02-15
16213 sep 12 9 --> 2009-09-12
16214 12:45 --> today 12:45
16215 22 sept 0:34 --> currentyear-09-22 0:34
16216 12 --> currentyear-currentmonth-12
16217 Fri --> nearest Friday after today
16218 -Tue --> last Tuesday
16219 etc.
16221 Furthermore you can specify a relative date by giving, as the *first* thing
16222 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16223 change in days weeks, months, years.
16224 With a single plus or minus, the date is relative to today. With a double
16225 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16226 +4d --> four days from today
16227 +4 --> same as above
16228 +2w --> two weeks from today
16229 ++5 --> five days from default date
16231 The function understands only English month and weekday abbreviations.
16233 While prompting, a calendar is popped up - you can also select the
16234 date with the mouse (button 1). The calendar shows a period of three
16235 months. To scroll it to other months, use the keys `>' and `<'.
16236 If you don't like the calendar, turn it off with
16237 (setq org-read-date-popup-calendar nil)
16239 With optional argument TO-TIME, the date will immediately be converted
16240 to an internal time.
16241 With an optional argument WITH-TIME, the prompt will suggest to
16242 also insert a time. Note that when WITH-TIME is not set, you can
16243 still enter a time, and this function will inform the calling routine
16244 about this change. The calling routine may then choose to change the
16245 format used to insert the time stamp into the buffer to include the time.
16246 With optional argument FROM-STRING, read from this string instead from
16247 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16248 the time/date that is used for everything that is not specified by the
16249 user."
16250 (require 'parse-time)
16251 (let* ((org-with-time with-time)
16252 (org-time-stamp-rounding-minutes
16253 (if (equal org-with-time '(16))
16254 '(0 0)
16255 org-time-stamp-rounding-minutes))
16256 (org-dcst org-display-custom-times)
16257 (ct (org-current-time))
16258 (org-def (or org-overriding-default-time default-time ct))
16259 (org-defdecode (decode-time org-def))
16260 (cur-frame (selected-frame))
16261 (mouse-autoselect-window nil) ; Don't let the mouse jump
16262 (calendar-setup
16263 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16264 (calendar-move-hook nil)
16265 (calendar-view-diary-initially-flag nil)
16266 (calendar-view-holidays-initially-flag nil)
16267 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16268 ;; Rationalize `org-def' and `org-defdecode', if required.
16269 (when (< (nth 2 org-defdecode) org-extend-today-until)
16270 (setf (nth 2 org-defdecode) -1)
16271 (setf (nth 1 org-defdecode) 59)
16272 (setq org-def (apply #'encode-time org-defdecode))
16273 (setq org-defdecode (decode-time org-def)))
16274 (let* ((timestr (format-time-string
16275 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16276 org-def))
16277 (prompt (concat (if prompt (concat prompt " ") "")
16278 (format "Date+time [%s]: " timestr))))
16279 (cond
16280 (from-string (setq ans from-string))
16281 (org-read-date-popup-calendar
16282 (save-excursion
16283 (save-window-excursion
16284 (calendar)
16285 (when (eq calendar-setup 'calendar-only)
16286 (setq cal-frame
16287 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16288 (select-frame cal-frame))
16289 (org-eval-in-calendar '(setq cursor-type nil) t)
16290 (unwind-protect
16291 (progn
16292 (calendar-forward-day (- (time-to-days org-def)
16293 (calendar-absolute-from-gregorian
16294 (calendar-current-date))))
16295 (org-eval-in-calendar nil t)
16296 (let* ((old-map (current-local-map))
16297 (map (copy-keymap calendar-mode-map))
16298 (minibuffer-local-map
16299 (copy-keymap org-read-date-minibuffer-local-map)))
16300 (org-defkey map (kbd "RET") 'org-calendar-select)
16301 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16302 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16303 (unwind-protect
16304 (progn
16305 (use-local-map map)
16306 (setq org-read-date-inactive inactive)
16307 (add-hook 'post-command-hook 'org-read-date-display)
16308 (setq org-ans0
16309 (read-string prompt
16310 default-input
16311 'org-read-date-history
16312 nil))
16313 ;; org-ans0: from prompt
16314 ;; org-ans1: from mouse click
16315 ;; org-ans2: from calendar motion
16316 (setq ans
16317 (concat org-ans0 " " (or org-ans1 org-ans2))))
16318 (remove-hook 'post-command-hook 'org-read-date-display)
16319 (use-local-map old-map)
16320 (when org-read-date-overlay
16321 (delete-overlay org-read-date-overlay)
16322 (setq org-read-date-overlay nil)))))
16323 (bury-buffer "*Calendar*")
16324 (when cal-frame
16325 (delete-frame cal-frame)
16326 (select-frame-set-input-focus cur-frame))))))
16328 (t ; Naked prompt only
16329 (unwind-protect
16330 (setq ans (read-string prompt default-input
16331 'org-read-date-history timestr))
16332 (when org-read-date-overlay
16333 (delete-overlay org-read-date-overlay)
16334 (setq org-read-date-overlay nil))))))
16336 (setq final (org-read-date-analyze ans org-def org-defdecode))
16338 (when org-read-date-analyze-forced-year
16339 (message "Year was forced into %s"
16340 (if org-read-date-force-compatible-dates
16341 "compatible range (1970-2037)"
16342 "range representable on this machine"))
16343 (ding))
16345 ;; One round trip to get rid of 34th of August and stuff like that....
16346 (setq final (decode-time (apply 'encode-time final)))
16348 (setq org-read-date-final-answer ans)
16350 (if to-time
16351 (apply 'encode-time final)
16352 (if (and (boundp 'org-time-was-given) org-time-was-given)
16353 (format "%04d-%02d-%02d %02d:%02d"
16354 (nth 5 final) (nth 4 final) (nth 3 final)
16355 (nth 2 final) (nth 1 final))
16356 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16358 (defun org-read-date-display ()
16359 "Display the current date prompt interpretation in the minibuffer."
16360 (when org-read-date-display-live
16361 (when org-read-date-overlay
16362 (delete-overlay org-read-date-overlay))
16363 (when (minibufferp (current-buffer))
16364 (save-excursion
16365 (end-of-line 1)
16366 (while (not (equal (buffer-substring
16367 (max (point-min) (- (point) 4)) (point))
16368 " "))
16369 (insert " ")))
16370 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16371 " " (or org-ans1 org-ans2)))
16372 (org-end-time-was-given nil)
16373 (f (org-read-date-analyze ans org-def org-defdecode))
16374 (fmts (if org-dcst
16375 org-time-stamp-custom-formats
16376 org-time-stamp-formats))
16377 (fmt (if (or org-with-time
16378 (and (boundp 'org-time-was-given) org-time-was-given))
16379 (cdr fmts)
16380 (car fmts)))
16381 (txt (format-time-string fmt (apply 'encode-time f)))
16382 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16383 (txt (concat "=> " txt)))
16384 (when (and org-end-time-was-given
16385 (string-match org-plain-time-of-day-regexp txt))
16386 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16387 org-end-time-was-given
16388 (substring txt (match-end 0)))))
16389 (when org-read-date-analyze-futurep
16390 (setq txt (concat txt " (=>F)")))
16391 (setq org-read-date-overlay
16392 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16393 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16395 (defun org-read-date-analyze (ans def defdecode)
16396 "Analyze the combined answer of the date prompt."
16397 ;; FIXME: cleanup and comment
16398 ;; Pass `current-time' result to `decode-time' (instead of calling
16399 ;; without arguments) so that only `current-time' has to be
16400 ;; overridden in tests.
16401 (let ((org-def def)
16402 (org-defdecode defdecode)
16403 (nowdecode (decode-time (current-time)))
16404 delta deltan deltaw deltadef year month day
16405 hour minute second wday pm h2 m2 tl wday1
16406 iso-year iso-weekday iso-week iso-date futurep kill-year)
16407 (setq org-read-date-analyze-futurep nil
16408 org-read-date-analyze-forced-year nil)
16409 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16410 (setq ans "+0"))
16412 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16413 (setq ans (replace-match "" t t ans)
16414 deltan (car delta)
16415 deltaw (nth 1 delta)
16416 deltadef (nth 2 delta)))
16418 ;; Check if there is an iso week date in there. If yes, store the
16419 ;; info and postpone interpreting it until the rest of the parsing
16420 ;; is done.
16421 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16422 (setq iso-year (when (match-end 1)
16423 (org-small-year-to-year
16424 (string-to-number (match-string 1 ans))))
16425 iso-weekday (when (match-end 3)
16426 (string-to-number (match-string 3 ans)))
16427 iso-week (string-to-number (match-string 2 ans)))
16428 (setq ans (replace-match "" t t ans)))
16430 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16431 (when (string-match
16432 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16433 (setq year (if (match-end 2)
16434 (string-to-number (match-string 2 ans))
16435 (progn (setq kill-year t)
16436 (string-to-number (format-time-string "%Y"))))
16437 month (string-to-number (match-string 3 ans))
16438 day (string-to-number (match-string 4 ans)))
16439 (setq year (org-small-year-to-year year))
16440 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16441 t nil ans)))
16443 ;; Help matching dotted european dates
16444 (when (string-match
16445 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16446 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16447 (setq kill-year t)
16448 (string-to-number (format-time-string "%Y")))
16449 day (string-to-number (match-string 1 ans))
16450 month (string-to-number (match-string 2 ans))
16451 ans (replace-match (format "%04d-%02d-%02d" year month day)
16452 t nil ans)))
16454 ;; Help matching american dates, like 5/30 or 5/30/7
16455 (when (string-match
16456 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16457 (setq year (if (match-end 4)
16458 (string-to-number (match-string 4 ans))
16459 (progn (setq kill-year t)
16460 (string-to-number (format-time-string "%Y"))))
16461 month (string-to-number (match-string 1 ans))
16462 day (string-to-number (match-string 2 ans)))
16463 (setq year (org-small-year-to-year year))
16464 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16465 t nil ans)))
16466 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16467 ;; If there is a time with am/pm, and *no* time without it, we convert
16468 ;; so that matching will be successful.
16469 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16470 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16471 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16472 (setq hour (string-to-number (match-string 1 ans))
16473 minute (if (match-end 3)
16474 (string-to-number (match-string 3 ans))
16476 pm (equal ?p
16477 (string-to-char (downcase (match-string 4 ans)))))
16478 (if (and (= hour 12) (not pm))
16479 (setq hour 0)
16480 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16481 (setq ans (replace-match (format "%02d:%02d" hour minute)
16482 t t ans))))
16484 ;; Check if a time range is given as a duration
16485 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16486 (setq hour (string-to-number (match-string 1 ans))
16487 h2 (+ hour (string-to-number (match-string 3 ans)))
16488 minute (string-to-number (match-string 2 ans))
16489 m2 (+ minute (if (match-end 5) (string-to-number
16490 (match-string 5 ans))0)))
16491 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16492 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16493 t t ans)))
16495 ;; Check if there is a time range
16496 (when (boundp 'org-end-time-was-given)
16497 (setq org-time-was-given nil)
16498 (when (and (string-match org-plain-time-of-day-regexp ans)
16499 (match-end 8))
16500 (setq org-end-time-was-given (match-string 8 ans))
16501 (setq ans (concat (substring ans 0 (match-beginning 7))
16502 (substring ans (match-end 7))))))
16504 (setq tl (parse-time-string ans)
16505 day (or (nth 3 tl) (nth 3 org-defdecode))
16506 month
16507 (cond ((nth 4 tl))
16508 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16509 ;; Day was specified. Make sure DAY+MONTH
16510 ;; combination happens in the future.
16511 ((nth 3 tl)
16512 (setq futurep t)
16513 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16514 (nth 4 nowdecode)))
16515 (t (nth 4 org-defdecode)))
16516 year
16517 (cond ((and (not kill-year) (nth 5 tl)))
16518 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16519 ;; Month was guessed in the future and is at least
16520 ;; equal to NOWDECODE's. Fix year accordingly.
16521 (futurep
16522 (if (or (> month (nth 4 nowdecode))
16523 (>= day (nth 3 nowdecode)))
16524 (nth 5 nowdecode)
16525 (1+ (nth 5 nowdecode))))
16526 ;; Month was specified. Make sure MONTH+YEAR
16527 ;; combination happens in the future.
16528 ((nth 4 tl)
16529 (setq futurep t)
16530 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16531 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16532 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16533 (t (nth 5 nowdecode))))
16534 (t (nth 5 org-defdecode)))
16535 hour (or (nth 2 tl) (nth 2 org-defdecode))
16536 minute (or (nth 1 tl) (nth 1 org-defdecode))
16537 second (or (nth 0 tl) 0)
16538 wday (nth 6 tl))
16540 (when (and (eq org-read-date-prefer-future 'time)
16541 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16542 (equal day (nth 3 nowdecode))
16543 (equal month (nth 4 nowdecode))
16544 (equal year (nth 5 nowdecode))
16545 (nth 2 tl)
16546 (or (< (nth 2 tl) (nth 2 nowdecode))
16547 (and (= (nth 2 tl) (nth 2 nowdecode))
16548 (nth 1 tl)
16549 (< (nth 1 tl) (nth 1 nowdecode)))))
16550 (setq day (1+ day)
16551 futurep t))
16553 ;; Special date definitions below
16554 (cond
16555 (iso-week
16556 ;; There was an iso week
16557 (require 'cal-iso)
16558 (setq futurep nil)
16559 (setq year (or iso-year year)
16560 day (or iso-weekday wday 1)
16561 wday nil ; to make sure that the trigger below does not match
16562 iso-date (calendar-gregorian-from-absolute
16563 (calendar-iso-to-absolute
16564 (list iso-week day year))))
16565 ; FIXME: Should we also push ISO weeks into the future?
16566 ; (when (and org-read-date-prefer-future
16567 ; (not iso-year)
16568 ; (< (calendar-absolute-from-gregorian iso-date)
16569 ; (time-to-days (current-time))))
16570 ; (setq year (1+ year)
16571 ; iso-date (calendar-gregorian-from-absolute
16572 ; (calendar-iso-to-absolute
16573 ; (list iso-week day year)))))
16574 (setq month (car iso-date)
16575 year (nth 2 iso-date)
16576 day (nth 1 iso-date)))
16577 (deltan
16578 (setq futurep nil)
16579 (unless deltadef
16580 ;; Pass `current-time' result to `decode-time' (instead of
16581 ;; calling without arguments) so that only `current-time' has
16582 ;; to be overridden in tests.
16583 (let ((now (decode-time (current-time))))
16584 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16585 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16586 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16587 ((equal deltaw "m") (setq month (+ month deltan)))
16588 ((equal deltaw "y") (setq year (+ year deltan)))))
16589 ((and wday (not (nth 3 tl)))
16590 ;; Weekday was given, but no day, so pick that day in the week
16591 ;; on or after the derived date.
16592 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16593 (unless (equal wday wday1)
16594 (setq day (+ day (% (- wday wday1 -7) 7))))))
16595 (when (and (boundp 'org-time-was-given)
16596 (nth 2 tl))
16597 (setq org-time-was-given t))
16598 (when (< year 100) (setq year (+ 2000 year)))
16599 ;; Check of the date is representable
16600 (if org-read-date-force-compatible-dates
16601 (progn
16602 (when (< year 1970)
16603 (setq year 1970 org-read-date-analyze-forced-year t))
16604 (when (> year 2037)
16605 (setq year 2037 org-read-date-analyze-forced-year t)))
16606 (condition-case nil
16607 (ignore (encode-time second minute hour day month year))
16608 (error
16609 (setq year (nth 5 org-defdecode))
16610 (setq org-read-date-analyze-forced-year t))))
16611 (setq org-read-date-analyze-futurep futurep)
16612 (list second minute hour day month year)))
16614 (defvar parse-time-weekdays)
16615 (defun org-read-date-get-relative (s today default)
16616 "Check string S for special relative date string.
16617 TODAY and DEFAULT are internal times, for today and for a default.
16618 Return shift list (N what def-flag)
16619 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16620 N is the number of WHATs to shift.
16621 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16622 the DEFAULT date rather than TODAY."
16623 (require 'parse-time)
16624 (when (and
16625 (string-match
16626 (concat
16627 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16628 "\\([0-9]+\\)?"
16629 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16630 "\\([ \t]\\|$\\)") s)
16631 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16632 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16633 (string-to-char (substring (match-string 1 s) -1))
16634 ?+))
16635 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16636 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16637 (what (if (match-end 3) (match-string 3 s) "d"))
16638 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16639 (date (if rel default today))
16640 (wday (nth 6 (decode-time date)))
16641 delta)
16642 (if wday1
16643 (progn
16644 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16645 (when (= delta 0) (setq delta 7))
16646 (when (= dir ?-)
16647 (setq delta (- delta 7))
16648 (when (= delta 0) (setq delta -7)))
16649 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16650 (list delta "d" rel))
16651 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16653 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16654 "Turn a user-specified date into the internal representation.
16655 The internal representation needed by the calendar is (month day year).
16656 This is a wrapper to handle the brain-dead convention in calendar that
16657 user function argument order change dependent on argument order."
16658 (pcase calendar-date-style
16659 (`american (list arg1 arg2 arg3))
16660 (`european (list arg2 arg1 arg3))
16661 (`iso (list arg2 arg3 arg1))))
16663 (defun org-eval-in-calendar (form &optional keepdate)
16664 "Eval FORM in the calendar window and return to current window.
16665 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16666 (let ((sf (selected-frame))
16667 (sw (selected-window)))
16668 (select-window (get-buffer-window "*Calendar*" t))
16669 (eval form)
16670 (when (and (not keepdate) (calendar-cursor-to-date))
16671 (let* ((date (calendar-cursor-to-date))
16672 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16673 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16674 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16675 (select-window sw)
16676 (select-frame-set-input-focus sf)))
16678 (defun org-calendar-select ()
16679 "Return to `org-read-date' with the date currently selected.
16680 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16681 (interactive)
16682 (when (calendar-cursor-to-date)
16683 (let* ((date (calendar-cursor-to-date))
16684 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16685 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16686 (when (active-minibuffer-window) (exit-minibuffer))))
16688 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16689 "Insert a date stamp for the date given by the internal TIME.
16690 See `format-time-string' for the format of TIME.
16691 WITH-HM means use the stamp format that includes the time of the day.
16692 INACTIVE means use square brackets instead of angular ones, so that the
16693 stamp will not contribute to the agenda.
16694 PRE and POST are optional strings to be inserted before and after the
16695 stamp.
16696 The command returns the inserted time stamp."
16697 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16698 stamp)
16699 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16700 (insert-before-markers (or pre ""))
16701 (when (listp extra)
16702 (setq extra (car extra))
16703 (if (and (stringp extra)
16704 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16705 (setq extra (format "-%02d:%02d"
16706 (string-to-number (match-string 1 extra))
16707 (string-to-number (match-string 2 extra))))
16708 (setq extra nil)))
16709 (when extra
16710 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16711 (insert-before-markers (setq stamp (format-time-string fmt time)))
16712 (insert-before-markers (or post ""))
16713 (setq org-last-inserted-timestamp stamp)))
16715 (defun org-toggle-time-stamp-overlays ()
16716 "Toggle the use of custom time stamp formats."
16717 (interactive)
16718 (setq org-display-custom-times (not org-display-custom-times))
16719 (unless org-display-custom-times
16720 (let ((p (point-min)) (bmp (buffer-modified-p)))
16721 (while (setq p (next-single-property-change p 'display))
16722 (when (and (get-text-property p 'display)
16723 (eq (get-text-property p 'face) 'org-date))
16724 (remove-text-properties
16725 p (setq p (next-single-property-change p 'display))
16726 '(display t))))
16727 (set-buffer-modified-p bmp)))
16728 (org-restart-font-lock)
16729 (setq org-table-may-need-update t)
16730 (if org-display-custom-times
16731 (message "Time stamps are overlaid with custom format")
16732 (message "Time stamp overlays removed")))
16734 (defun org-display-custom-time (beg end)
16735 "Overlay modified time stamp format over timestamp between BEG and END."
16736 (let* ((ts (buffer-substring beg end))
16737 t1 with-hm tf time str (off 0))
16738 (save-match-data
16739 (setq t1 (org-parse-time-string ts t))
16740 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16741 (setq off (- (match-end 0) (match-beginning 0)))))
16742 (setq end (- end off))
16743 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16744 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16745 time (org-fix-decoded-time t1)
16746 str (org-add-props
16747 (format-time-string
16748 (substring tf 1 -1) (apply 'encode-time time))
16749 nil 'mouse-face 'highlight))
16750 (put-text-property beg end 'display str)))
16752 (defun org-fix-decoded-time (time)
16753 "Set 0 instead of nil for the first 6 elements of time.
16754 Don't touch the rest."
16755 (let ((n 0))
16756 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16758 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16759 "Difference between TIMESTAMP-STRING and now in days.
16760 If SECONDS is non-nil, return the difference in seconds."
16761 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16762 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16763 (funcall fdiff (current-time)))))
16765 (defun org-deadline-close-p (timestamp-string &optional ndays)
16766 "Is the time in TIMESTAMP-STRING close to the current date?"
16767 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16768 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16769 (not (org-entry-is-done-p))))
16771 (defun org-get-wdays (ts &optional delay zero-delay)
16772 "Get the deadline lead time appropriate for timestring TS.
16773 When DELAY is non-nil, get the delay time for scheduled items
16774 instead of the deadline lead time. When ZERO-DELAY is non-nil
16775 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16776 don't try to find the delay cookie in the scheduled timestamp."
16777 (let ((tv (if delay org-scheduled-delay-days
16778 org-deadline-warning-days)))
16779 (cond
16780 ((or (and delay (< tv 0))
16781 (and delay zero-delay (<= tv 0))
16782 (and (not delay) (<= tv 0)))
16783 ;; Enforce this value no matter what
16784 (- tv))
16785 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16786 ;; lead time is specified.
16787 (floor (* (string-to-number (match-string 1 ts))
16788 (cdr (assoc (match-string 2 ts)
16789 '(("d" . 1) ("w" . 7)
16790 ("m" . 30.4) ("y" . 365.25)
16791 ("h" . 0.041667)))))))
16792 ;; go for the default.
16793 (t tv))))
16795 (defun org-calendar-select-mouse (ev)
16796 "Return to `org-read-date' with the date currently selected.
16797 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16798 (interactive "e")
16799 (mouse-set-point ev)
16800 (when (calendar-cursor-to-date)
16801 (let* ((date (calendar-cursor-to-date))
16802 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16803 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16804 (when (active-minibuffer-window) (exit-minibuffer))))
16806 (defun org-check-deadlines (ndays)
16807 "Check if there are any deadlines due or past due.
16808 A deadline is considered due if it happens within `org-deadline-warning-days'
16809 days from today's date. If the deadline appears in an entry marked DONE,
16810 it is not shown. A numeric prefix argument NDAYS can be used to test that
16811 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16812 are shown."
16813 (interactive "P")
16814 (let* ((org-warn-days
16815 (cond
16816 ((equal ndays '(4)) 100000)
16817 (ndays (prefix-numeric-value ndays))
16818 (t (abs org-deadline-warning-days))))
16819 (case-fold-search nil)
16820 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16821 (callback
16822 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16823 (message "%d deadlines past-due or due within %d days"
16824 (org-occur regexp nil callback)
16825 org-warn-days)))
16827 (defsubst org-re-timestamp (type)
16828 "Return a regexp for timestamp TYPE.
16829 Allowed values for TYPE are:
16831 all: all timestamps
16832 active: only active timestamps (<...>)
16833 inactive: only inactive timestamps ([...])
16834 scheduled: only scheduled timestamps
16835 deadline: only deadline timestamps
16836 closed: only closed time-stamps
16838 When TYPE is nil, fall back on returning a regexp that matches
16839 both scheduled and deadline timestamps."
16840 (cl-case type
16841 (all org-ts-regexp-both)
16842 (active org-ts-regexp)
16843 (inactive org-ts-regexp-inactive)
16844 (scheduled org-scheduled-time-regexp)
16845 (deadline org-deadline-time-regexp)
16846 (closed org-closed-time-regexp)
16847 (otherwise
16848 (concat "\\<"
16849 (regexp-opt (list org-deadline-string org-scheduled-string))
16850 " *<\\([^>]+\\)>"))))
16852 (defun org-check-before-date (d)
16853 "Check if there are deadlines or scheduled entries before date D."
16854 (interactive (list (org-read-date)))
16855 (let* ((case-fold-search nil)
16856 (regexp (org-re-timestamp org-ts-type))
16857 (ts-type org-ts-type)
16858 (callback
16859 (lambda ()
16860 (let ((match (match-string 1)))
16861 (and (if (memq ts-type '(active inactive all))
16862 (eq (org-element-type (save-excursion
16863 (backward-char)
16864 (org-element-context)))
16865 'timestamp)
16866 (org-at-planning-p))
16867 (time-less-p
16868 (org-time-string-to-time match)
16869 (org-time-string-to-time d)))))))
16870 (message "%d entries before %s"
16871 (org-occur regexp nil callback)
16872 d)))
16874 (defun org-check-after-date (d)
16875 "Check if there are deadlines or scheduled entries after date D."
16876 (interactive (list (org-read-date)))
16877 (let* ((case-fold-search nil)
16878 (regexp (org-re-timestamp org-ts-type))
16879 (ts-type org-ts-type)
16880 (callback
16881 (lambda ()
16882 (let ((match (match-string 1)))
16883 (and (if (memq ts-type '(active inactive all))
16884 (eq (org-element-type (save-excursion
16885 (backward-char)
16886 (org-element-context)))
16887 'timestamp)
16888 (org-at-planning-p))
16889 (not (time-less-p
16890 (org-time-string-to-time match)
16891 (org-time-string-to-time d))))))))
16892 (message "%d entries after %s"
16893 (org-occur regexp nil callback)
16894 d)))
16896 (defun org-check-dates-range (start-date end-date)
16897 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16898 (interactive (list (org-read-date nil nil nil "Range starts")
16899 (org-read-date nil nil nil "Range end")))
16900 (let ((case-fold-search nil)
16901 (regexp (org-re-timestamp org-ts-type))
16902 (callback
16903 (let ((type org-ts-type))
16904 (lambda ()
16905 (let ((match (match-string 1)))
16906 (and
16907 (if (memq type '(active inactive all))
16908 (eq (org-element-type (save-excursion
16909 (backward-char)
16910 (org-element-context)))
16911 'timestamp)
16912 (org-at-planning-p))
16913 (not (time-less-p
16914 (org-time-string-to-time match)
16915 (org-time-string-to-time start-date)))
16916 (time-less-p
16917 (org-time-string-to-time match)
16918 (org-time-string-to-time end-date))))))))
16919 (message "%d entries between %s and %s"
16920 (org-occur regexp nil callback) start-date end-date)))
16922 (defun org-evaluate-time-range (&optional to-buffer)
16923 "Evaluate a time range by computing the difference between start and end.
16924 Normally the result is just printed in the echo area, but with prefix arg
16925 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16926 If the time range is actually in a table, the result is inserted into the
16927 next column.
16928 For time difference computation, a year is assumed to be exactly 365
16929 days in order to avoid rounding problems."
16930 (interactive "P")
16932 (org-clock-update-time-maybe)
16933 (save-excursion
16934 (unless (org-at-date-range-p t)
16935 (goto-char (point-at-bol))
16936 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16937 (unless (org-at-date-range-p t)
16938 (user-error "Not at a time-stamp range, and none found in current line")))
16939 (let* ((ts1 (match-string 1))
16940 (ts2 (match-string 2))
16941 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16942 (match-end (match-end 0))
16943 (time1 (org-time-string-to-time ts1))
16944 (time2 (org-time-string-to-time ts2))
16945 (t1 (float-time time1))
16946 (t2 (float-time time2))
16947 (diff (abs (- t2 t1)))
16948 (negative (< (- t2 t1) 0))
16949 ;; (ys (floor (* 365 24 60 60)))
16950 (ds (* 24 60 60))
16951 (hs (* 60 60))
16952 (fy "%dy %dd %02d:%02d")
16953 (fy1 "%dy %dd")
16954 (fd "%dd %02d:%02d")
16955 (fd1 "%dd")
16956 (fh "%02d:%02d")
16957 y d h m align)
16958 (if havetime
16959 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16961 d (floor (/ diff ds)) diff (mod diff ds)
16962 h (floor (/ diff hs)) diff (mod diff hs)
16963 m (floor (/ diff 60)))
16964 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16966 d (floor (+ (/ diff ds) 0.5))
16967 h 0 m 0))
16968 (if (not to-buffer)
16969 (message "%s" (org-make-tdiff-string y d h m))
16970 (if (org-at-table-p)
16971 (progn
16972 (goto-char match-end)
16973 (setq align t)
16974 (and (looking-at " *|") (goto-char (match-end 0))))
16975 (goto-char match-end))
16976 (when (looking-at
16977 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16978 (replace-match ""))
16979 (when negative (insert " -"))
16980 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16981 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16982 (insert " " (format fh h m))))
16983 (when align (org-table-align))
16984 (message "Time difference inserted")))))
16986 (defun org-make-tdiff-string (y d h m)
16987 (let ((fmt "")
16988 (l nil))
16989 (when (> y 0)
16990 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16991 (push y l))
16992 (when (> d 0)
16993 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16994 (push d l))
16995 (when (> h 0)
16996 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16997 (push h l))
16998 (when (> m 0)
16999 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17000 (push m l))
17001 (apply 'format fmt (nreverse l))))
17003 (defun org-time-string-to-time (s)
17004 "Convert timestamp string S into internal time."
17005 (apply #'encode-time (org-parse-time-string s)))
17007 (defun org-time-string-to-seconds (s)
17008 "Convert a timestamp string S into a number of seconds."
17009 (float-time (org-time-string-to-time s)))
17011 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17013 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17014 "Convert time stamp S to an absolute day number.
17016 If DAYNR in non-nil, and there is a specifier for a cyclic time
17017 stamp, get the closest date to DAYNR. If PREFER is
17018 `past' (respectively `future') return a date past (respectively
17019 after) or equal to DAYNR.
17021 POS is the location of time stamp S, as a buffer position in
17022 BUFFER.
17024 Diary sexp timestamps are matched against DAYNR, when non-nil.
17025 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17026 signaled."
17027 (cond
17028 ((string-match "\\`%%\\((.*)\\)" s)
17029 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17030 ;; only able to match individual dates. If it fails, raise an
17031 ;; error.
17032 (if (and daynr
17033 (org-diary-sexp-entry
17034 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17035 daynr
17036 (signal 'org-diary-sexp-no-match (list s))))
17037 (daynr (org-closest-date s daynr prefer))
17038 (t (time-to-days
17039 (condition-case errdata
17040 (apply #'encode-time (org-parse-time-string s))
17041 (error (error "Bad timestamp `%s'%s\nError was: %s"
17043 (if (not (and buffer pos)) ""
17044 (format-message " at %d in buffer `%s'" pos buffer))
17045 (cdr errdata))))))))
17047 (defun org-days-to-iso-week (days)
17048 "Return the iso week number."
17049 (require 'cal-iso)
17050 (car (calendar-iso-from-absolute days)))
17052 (defun org-small-year-to-year (year)
17053 "Convert 2-digit years into 4-digit years.
17054 YEAR is expanded into one of the 30 next years, if possible, or
17055 into a past one. Any year larger than 99 is returned unchanged."
17056 (if (>= year 100) year
17057 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17058 (century (/ current 100))
17059 (offset (- year (% current 100))))
17060 (cond ((> offset 30) (+ (* (1- century) 100) year))
17061 ((> offset -70) (+ (* century 100) year))
17062 (t (+ (* (1+ century) 100) year))))))
17064 (defun org-time-from-absolute (d)
17065 "Return the time corresponding to date D.
17066 D may be an absolute day number, or a calendar-type list (month day year)."
17067 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17068 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17070 (defvar org-agenda-current-date)
17071 (defun org-calendar-holiday ()
17072 "List of holidays, for Diary display in Org mode."
17073 (require 'holidays)
17074 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17075 (and hl (mapconcat #'identity hl "; "))))
17077 (defun org-diary-sexp-entry (sexp entry d)
17078 "Process a SEXP diary ENTRY for date D."
17079 (require 'diary-lib)
17080 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17081 ;; dynamically.
17082 (let* ((sexp `(let ((entry ,entry)
17083 (date ',d))
17084 ,(car (read-from-string sexp))))
17085 (result (if calendar-debug-sexp (eval sexp)
17086 (condition-case nil
17087 (eval sexp)
17088 (error
17089 (beep)
17090 (message "Bad sexp at line %d in %s: %s"
17091 (org-current-line)
17092 (buffer-file-name) sexp)
17093 (sleep-for 2))))))
17094 (cond ((stringp result) (split-string result "; "))
17095 ((and (consp result)
17096 (not (consp (cdr result)))
17097 (stringp (cdr result))) (cdr result))
17098 ((and (consp result)
17099 (stringp (car result))) result)
17100 (result entry))))
17102 (defun org-diary-to-ical-string (frombuf)
17103 "Get iCalendar entries from diary entries in buffer FROMBUF.
17104 This uses the icalendar.el library."
17105 (let* ((tmpdir temporary-file-directory)
17106 (tmpfile (make-temp-name
17107 (expand-file-name "orgics" tmpdir)))
17108 buf rtn b e)
17109 (with-current-buffer frombuf
17110 (icalendar-export-region (point-min) (point-max) tmpfile)
17111 (setq buf (find-buffer-visiting tmpfile))
17112 (set-buffer buf)
17113 (goto-char (point-min))
17114 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17115 (setq b (match-beginning 0)))
17116 (goto-char (point-max))
17117 (when (re-search-backward "^END:VEVENT" nil t)
17118 (setq e (match-end 0)))
17119 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17120 (kill-buffer buf)
17121 (delete-file tmpfile)
17122 rtn))
17124 (defun org-closest-date (start current prefer)
17125 "Return closest date to CURRENT starting from START.
17127 CURRENT and START are both time stamps.
17129 When PREFER is `past', return a date that is either CURRENT or
17130 past. When PREFER is `future', return a date that is either
17131 CURRENT or future.
17133 Only time stamps with a repeater are modified. Any other time
17134 stamp stay unchanged. In any case, return value is an absolute
17135 day number."
17136 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17137 ;; No repeater. Do not shift time stamp.
17138 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17139 (let ((value (string-to-number (match-string 1 start)))
17140 (type (match-string 2 start)))
17141 (if (= 0 value)
17142 ;; Repeater with a 0-value is considered as void.
17143 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17144 (let* ((base (org-date-to-gregorian start))
17145 (target (org-date-to-gregorian current))
17146 (sday (calendar-absolute-from-gregorian base))
17147 (cday (calendar-absolute-from-gregorian target))
17148 n1 n2)
17149 ;; If START is already past CURRENT, just return START.
17150 (if (<= cday sday) sday
17151 ;; Compute closest date before (N1) and closest date past
17152 ;; (N2) CURRENT.
17153 (pcase type
17154 ("h"
17155 (let ((missing-hours
17156 (mod (+ (- (* 24 (- cday sday))
17157 (nth 2 (org-parse-time-string start)))
17158 org-extend-today-until)
17159 value)))
17160 (setf n1 (if (= missing-hours 0) cday
17161 (- cday (1+ (/ missing-hours 24)))))
17162 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17163 ((or "d" "w")
17164 (let ((value (if (equal type "w") (* 7 value) value)))
17165 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17166 (setf n2 (+ n1 value))))
17167 ("m"
17168 (let* ((add-months
17169 (lambda (d n)
17170 ;; Add N months to gregorian date D, i.e.,
17171 ;; a list (MONTH DAY YEAR). Return a valid
17172 ;; gregorian date.
17173 (let ((m (+ (nth 0 d) n)))
17174 (list (mod m 12)
17175 (nth 1 d)
17176 (+ (/ m 12) (nth 2 d))))))
17177 (months ; Complete months to TARGET.
17178 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17179 (- (nth 0 target) (nth 0 base))
17180 ;; If START's day is greater than
17181 ;; TARGET's, remove incomplete month.
17182 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17183 value)
17184 value))
17185 (before (funcall add-months base months)))
17186 (setf n1 (calendar-absolute-from-gregorian before))
17187 (setf n2
17188 (calendar-absolute-from-gregorian
17189 (funcall add-months before value)))))
17191 (let* ((d (nth 1 base))
17192 (m (nth 0 base))
17193 (y (nth 2 base))
17194 (years ; Complete years to TARGET.
17195 (* (/ (- (nth 2 target)
17197 ;; If START's month and day are
17198 ;; greater than TARGET's, remove
17199 ;; incomplete year.
17200 (if (or (> (nth 0 target) m)
17201 (and (= (nth 0 target) m)
17202 (> (nth 1 target) d)))
17205 value)
17206 value))
17207 (before (list m d (+ y years))))
17208 (setf n1 (calendar-absolute-from-gregorian before))
17209 (setf n2 (calendar-absolute-from-gregorian
17210 (list m d (+ (nth 2 before) value)))))))
17211 ;; Handle PREFER parameter, if any.
17212 (cond
17213 ((eq prefer 'past) (if (= cday n2) n2 n1))
17214 ((eq prefer 'future) (if (= cday n1) n1 n2))
17215 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17217 (defun org-date-to-gregorian (d)
17218 "Turn any specification of date D into a Gregorian date for the calendar."
17219 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17220 ((and (listp d) (= (length d) 3)) d)
17221 ((stringp d)
17222 (let ((d (org-parse-time-string d)))
17223 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17224 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17226 (defun org-parse-time-string (s &optional nodefault)
17227 "Parse the standard Org time string.
17229 This should be a lot faster than the normal `parse-time-string'.
17231 If time is not given, defaults to 0:00. However, with optional
17232 NODEFAULT, hour and minute fields will be nil if not given."
17233 (cond ((string-match org-ts-regexp0 s)
17234 (list 0
17235 (when (or (match-beginning 8) (not nodefault))
17236 (string-to-number (or (match-string 8 s) "0")))
17237 (when (or (match-beginning 7) (not nodefault))
17238 (string-to-number (or (match-string 7 s) "0")))
17239 (string-to-number (match-string 4 s))
17240 (string-to-number (match-string 3 s))
17241 (string-to-number (match-string 2 s))
17242 nil nil nil))
17243 ((string-match "^<[^>]+>$" s)
17244 ;; FIXME: `decode-time' needs to be called with ZONE as its
17245 ;; second argument. However, this requires at least Emacs
17246 ;; 25.1. We can do it when we switch to this version as our
17247 ;; minimal requirement.
17248 (decode-time (seconds-to-time (org-matcher-time s))))
17249 (t (error "Not a standard Org time string: %s" s))))
17251 (defun org-timestamp-up (&optional arg)
17252 "Increase the date item at the cursor by one.
17253 If the cursor is on the year, change the year. If it is on the month,
17254 the day or the time, change that.
17255 With prefix ARG, change by that many units."
17256 (interactive "p")
17257 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17259 (defun org-timestamp-down (&optional arg)
17260 "Decrease the date item at the cursor by one.
17261 If the cursor is on the year, change the year. If it is on the month,
17262 the day or the time, change that.
17263 With prefix ARG, change by that many units."
17264 (interactive "p")
17265 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17267 (defun org-timestamp-up-day (&optional arg)
17268 "Increase the date in the time stamp by one day.
17269 With prefix ARG, change that many days."
17270 (interactive "p")
17271 (if (and (not (org-at-timestamp-p 'lax))
17272 (org-at-heading-p))
17273 (org-todo 'up)
17274 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17276 (defun org-timestamp-down-day (&optional arg)
17277 "Decrease the date in the time stamp by one day.
17278 With prefix ARG, change that many days."
17279 (interactive "p")
17280 (if (and (not (org-at-timestamp-p 'lax))
17281 (org-at-heading-p))
17282 (org-todo 'down)
17283 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17285 (defun org-at-timestamp-p (&optional extended)
17286 "Non-nil if point is inside a timestamp.
17288 By default, the function only consider syntactically valid active
17289 timestamps. However, the caller may have a broader definition
17290 for timestamps. As a consequence, optional argument EXTENDED can
17291 be set to the following values
17293 `inactive'
17295 Include also syntactically valid inactive timestamps.
17297 `agenda'
17299 Include timestamps allowed in Agenda, i.e., those in
17300 properties drawers, planning lines and clock lines.
17302 `lax'
17304 Ignore context. The function matches any part of the
17305 document looking like a timestamp. This includes comments,
17306 example blocks...
17308 For backward-compatibility with Org 9.0, every other non-nil
17309 value is equivalent to `inactive'.
17311 When at a timestamp, return the position of the point as a symbol
17312 among `bracket', `after', `year', `month', `hour', `minute',
17313 `day' or a number of character from the last know part of the
17314 time stamp.
17316 When matching, the match groups are the following:
17317 group 1: year
17318 group 2: month
17319 group 3: day number
17320 group 4: day name
17321 group 5: hours, if any
17322 group 6: minutes, if any"
17323 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17324 (pos (point))
17325 (match?
17326 (let ((boundaries (org-in-regexp regexp)))
17327 (save-match-data
17328 (cond ((null boundaries) nil)
17329 ((eq extended 'lax) t)
17331 (or (and (eq extended 'agenda)
17332 (or (org-at-planning-p)
17333 (org-at-property-p)
17334 (and (bound-and-true-p
17335 org-agenda-include-inactive-timestamps)
17336 (org-at-clock-log-p))))
17337 (eq 'timestamp
17338 (save-excursion
17339 (when (= pos (cdr boundaries)) (forward-char -1))
17340 (org-element-type (org-element-context)))))))))))
17341 (cond
17342 ((not match?) nil)
17343 ((= pos (match-beginning 0)) 'bracket)
17344 ;; Distinguish location right before the closing bracket from
17345 ;; right after it.
17346 ((= pos (1- (match-end 0))) 'bracket)
17347 ((= pos (match-end 0)) 'after)
17348 ((org-pos-in-match-range pos 2) 'year)
17349 ((org-pos-in-match-range pos 3) 'month)
17350 ((org-pos-in-match-range pos 7) 'hour)
17351 ((org-pos-in-match-range pos 8) 'minute)
17352 ((or (org-pos-in-match-range pos 4)
17353 (org-pos-in-match-range pos 5)) 'day)
17354 ((and (> pos (or (match-end 8) (match-end 5)))
17355 (< pos (match-end 0)))
17356 (- pos (or (match-end 8) (match-end 5))))
17357 (t 'day))))
17359 (defun org-toggle-timestamp-type ()
17360 "Toggle the type (<active> or [inactive]) of a time stamp."
17361 (interactive)
17362 (when (org-at-timestamp-p 'lax)
17363 (let ((beg (match-beginning 0)) (end (match-end 0))
17364 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17365 (save-excursion
17366 (goto-char beg)
17367 (while (re-search-forward "[][<>]" end t)
17368 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17369 t t)))
17370 (message "Timestamp is now %sactive"
17371 (if (equal (char-after beg) ?<) "" "in")))))
17373 (defun org-at-clock-log-p ()
17374 "Non-nil if point is on a clock log line."
17375 (and (org-match-line org-clock-line-re)
17376 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17378 (defvar org-clock-history) ; defined in org-clock.el
17379 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17380 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17381 "Change the date in the time stamp at point.
17382 The date will be changed by N times WHAT. WHAT can be `day', `month',
17383 `year', `minute', `second'. If WHAT is not given, the cursor position
17384 in the timestamp determines what will be changed.
17385 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17386 (let ((origin (point))
17387 (timestamp? (org-at-timestamp-p 'lax))
17388 origin-cat
17389 with-hm inactive
17390 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17391 extra rem
17392 ts time time0 fixnext clrgx)
17393 (unless timestamp? (user-error "Not at a timestamp"))
17394 (if (and (not what) (eq timestamp? 'bracket))
17395 (org-toggle-timestamp-type)
17396 ;; Point isn't on brackets. Remember the part of the time-stamp
17397 ;; the point was in. Indeed, size of time-stamps may change,
17398 ;; but point must be kept in the same category nonetheless.
17399 (setq origin-cat timestamp?)
17400 (when (and (not what) (not (eq timestamp? 'day))
17401 org-display-custom-times
17402 (get-text-property (point) 'display)
17403 (not (get-text-property (1- (point)) 'display)))
17404 (setq timestamp? 'day))
17405 (setq timestamp? (or what timestamp?)
17406 inactive (= (char-after (match-beginning 0)) ?\[)
17407 ts (match-string 0))
17408 (replace-match "")
17409 (when (string-match
17410 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17412 (setq extra (match-string 1 ts))
17413 (when suppress-tmp-delay
17414 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17415 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17416 (setq with-hm t))
17417 (setq time0 (org-parse-time-string ts))
17418 (when (and updown
17419 (eq timestamp? 'minute)
17420 (not current-prefix-arg))
17421 ;; This looks like s-up and s-down. Change by one rounding step.
17422 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17423 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17424 (setcar (cdr time0) (+ (nth 1 time0)
17425 (if (> n 0) (- rem) (- dm rem))))))
17426 (setq time
17427 (apply #'encode-time
17428 (or (car time0) 0)
17429 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17430 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17431 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17432 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17433 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17434 (nthcdr 6 time0)))
17435 (when (and (memq timestamp? '(hour minute))
17436 extra
17437 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17438 (setq extra (org-modify-ts-extra
17439 extra
17440 (if (eq timestamp? 'hour) 2 5)
17441 n dm)))
17442 (when (integerp timestamp?)
17443 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17444 (when (eq what 'calendar)
17445 (let ((cal-date (org-get-date-from-calendar)))
17446 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17447 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17448 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17449 (setcar time0 (or (car time0) 0))
17450 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17451 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17452 (setq time (apply 'encode-time time0))))
17453 ;; Insert the new time-stamp, and ensure point stays in the same
17454 ;; category as before (i.e. not after the last position in that
17455 ;; category).
17456 (let ((pos (point)))
17457 ;; Stay before inserted string. `save-excursion' is of no use.
17458 (setq org-last-changed-timestamp
17459 (org-insert-time-stamp time with-hm inactive nil nil extra))
17460 (goto-char pos))
17461 (save-match-data
17462 (looking-at org-ts-regexp3)
17463 (goto-char
17464 (pcase origin-cat
17465 ;; `day' category ends before `hour' if any, or at the end
17466 ;; of the day name.
17467 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17468 (`hour (min (match-end 7) origin))
17469 (`minute (min (1- (match-end 8)) origin))
17470 ((pred integerp) (min (1- (match-end 0)) origin))
17471 ;; Point was right after the time-stamp. However, the
17472 ;; time-stamp length might have changed, so refer to
17473 ;; (match-end 0) instead.
17474 (`after (match-end 0))
17475 ;; `year' and `month' have both fixed size: point couldn't
17476 ;; have moved into another part.
17477 (_ origin))))
17478 ;; Update clock if on a CLOCK line.
17479 (org-clock-update-time-maybe)
17480 ;; Maybe adjust the closest clock in `org-clock-history'
17481 (when org-clock-adjust-closest
17482 (if (not (and (org-at-clock-log-p)
17483 (< 1 (length (delq nil (mapcar 'marker-position
17484 org-clock-history))))))
17485 (message "No clock to adjust")
17486 (cond ((save-excursion ; fix previous clock?
17487 (re-search-backward org-ts-regexp0 nil t)
17488 (looking-back (concat org-clock-string " \\[")
17489 (line-beginning-position)))
17490 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17491 ((save-excursion ; fix next clock?
17492 (re-search-backward org-ts-regexp0 nil t)
17493 (looking-at (concat org-ts-regexp0 "\\] =>")))
17494 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17495 (save-window-excursion
17496 ;; Find closest clock to point, adjust the previous/next one in history
17497 (let* ((p (save-excursion (org-back-to-heading t)))
17498 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17499 (clfixnth
17500 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17501 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17502 (if (not clfixpos)
17503 (message "No clock to adjust")
17504 (save-excursion
17505 (org-goto-marker-or-bmk clfixpos)
17506 (org-show-subtree)
17507 (when (re-search-forward clrgx nil t)
17508 (goto-char (match-beginning 1))
17509 (let (org-clock-adjust-closest)
17510 (org-timestamp-change n timestamp? updown))
17511 (message "Clock adjusted in %s for heading: %s"
17512 (file-name-nondirectory (buffer-file-name))
17513 (org-get-heading t t)))))))))
17514 ;; Try to recenter the calendar window, if any.
17515 (when (and org-calendar-follow-timestamp-change
17516 (get-buffer-window "*Calendar*" t)
17517 (memq timestamp? '(day month year)))
17518 (org-recenter-calendar (time-to-days time))))))
17520 (defun org-modify-ts-extra (s pos n dm)
17521 "Change the different parts of the lead-time and repeat fields in timestamp."
17522 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17523 ng h m new rem)
17524 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17525 (cond
17526 ((or (org-pos-in-match-range pos 2)
17527 (org-pos-in-match-range pos 3))
17528 (setq m (string-to-number (match-string 3 s))
17529 h (string-to-number (match-string 2 s)))
17530 (if (org-pos-in-match-range pos 2)
17531 (setq h (+ h n))
17532 (setq n (* dm (with-no-warnings (signum n))))
17533 (unless (= 0 (setq rem (% m dm)))
17534 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17535 (setq m (+ m n)))
17536 (when (< m 0) (setq m (+ m 60) h (1- h)))
17537 (when (> m 59) (setq m (- m 60) h (1+ h)))
17538 (setq h (mod h 24))
17539 (setq ng 1 new (format "-%02d:%02d" h m)))
17540 ((org-pos-in-match-range pos 6)
17541 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17542 ((org-pos-in-match-range pos 5)
17543 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17545 ((org-pos-in-match-range pos 9)
17546 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17547 ((org-pos-in-match-range pos 8)
17548 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17550 (when ng
17551 (setq s (concat
17552 (substring s 0 (match-beginning ng))
17554 (substring s (match-end ng))))))
17557 (defun org-recenter-calendar (d)
17558 "If the calendar is visible, recenter it to date D."
17559 (let ((cwin (get-buffer-window "*Calendar*" t)))
17560 (when cwin
17561 (let ((calendar-move-hook nil))
17562 (with-selected-window cwin
17563 (calendar-goto-date
17564 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17566 (defun org-goto-calendar (&optional arg)
17567 "Go to the Emacs calendar at the current date.
17568 If there is a time stamp in the current line, go to that date.
17569 A prefix ARG can be used to force the current date."
17570 (interactive "P")
17571 (let ((calendar-move-hook nil)
17572 (calendar-view-holidays-initially-flag nil)
17573 (calendar-view-diary-initially-flag nil)
17574 diff)
17575 (when (or (org-at-timestamp-p 'lax)
17576 (org-match-line (concat ".*" org-ts-regexp)))
17577 (let ((d1 (time-to-days (current-time)))
17578 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17579 (setq diff (- d2 d1))))
17580 (calendar)
17581 (calendar-goto-today)
17582 (when (and diff (not arg)) (calendar-forward-day diff))))
17584 (defun org-get-date-from-calendar ()
17585 "Return a list (month day year) of date at point in calendar."
17586 (with-current-buffer "*Calendar*"
17587 (save-match-data
17588 (calendar-cursor-to-date))))
17590 (defun org-date-from-calendar ()
17591 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17592 If there is already a time stamp at the cursor position, update it."
17593 (interactive)
17594 (if (org-at-timestamp-p 'lax)
17595 (org-timestamp-change 0 'calendar)
17596 (let ((cal-date (org-get-date-from-calendar)))
17597 (org-insert-time-stamp
17598 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17600 (defcustom org-effort-durations
17601 `(("min" . 1)
17602 ("h" . 60)
17603 ("d" . ,(* 60 8))
17604 ("w" . ,(* 60 8 5))
17605 ("m" . ,(* 60 8 5 4))
17606 ("y" . ,(* 60 8 5 40)))
17607 "Conversion factor to minutes for an effort modifier.
17609 Each entry has the form (MODIFIER . MINUTES).
17611 In an effort string, a number followed by MODIFIER is multiplied
17612 by the specified number of MINUTES to obtain an effort in
17613 minutes.
17615 For example, if the value of this variable is ((\"hours\" . 60)), then an
17616 effort string \"2hours\" is equivalent to 120 minutes."
17617 :group 'org-agenda
17618 :version "26.1"
17619 :package-version '(Org . "8.3")
17620 :type '(alist :key-type (string :tag "Modifier")
17621 :value-type (number :tag "Minutes")))
17623 (defcustom org-image-actual-width t
17624 "Should we use the actual width of images when inlining them?
17626 When set to t, always use the image width.
17628 When set to a number, use imagemagick (when available) to set
17629 the image's width to this value.
17631 When set to a number in a list, try to get the width from any
17632 #+ATTR.* keyword if it matches a width specification like
17634 #+ATTR_HTML: :width 300px
17636 and fall back on that number if none is found.
17638 When set to nil, try to get the width from an #+ATTR.* keyword
17639 and fall back on the original width if none is found.
17641 This requires Emacs >= 24.1, build with imagemagick support."
17642 :group 'org-appearance
17643 :version "24.4"
17644 :package-version '(Org . "8.0")
17645 :type '(choice
17646 (const :tag "Use the image width" t)
17647 (integer :tag "Use a number of pixels")
17648 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17649 (const :tag "Use #+ATTR* or don't resize" nil)))
17651 (defcustom org-agenda-inhibit-startup nil
17652 "Inhibit startup when preparing agenda buffers.
17653 When this variable is t, the initialization of the Org agenda
17654 buffers is inhibited: e.g. the visibility state is not set, the
17655 tables are not re-aligned, etc."
17656 :type 'boolean
17657 :version "24.3"
17658 :group 'org-agenda)
17660 (defcustom org-agenda-ignore-properties nil
17661 "Avoid updating text properties when building the agenda.
17662 Properties are used to prepare buffers for effort estimates,
17663 appointments, statistics and subtree-local categories.
17664 If you don't use these in the agenda, you can add them to this
17665 list and agenda building will be a bit faster.
17666 The value is a list, with zero or more of the symbols `effort', `appt',
17667 `stats' or `category'."
17668 :type '(set :greedy t
17669 (const effort)
17670 (const appt)
17671 (const stats)
17672 (const category))
17673 :version "26.1"
17674 :package-version '(Org . "8.3")
17675 :group 'org-agenda)
17677 ;;;; Files
17679 (defun org-save-all-org-buffers ()
17680 "Save all Org buffers without user confirmation."
17681 (interactive)
17682 (message "Saving all Org buffers...")
17683 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17684 (when (featurep 'org-id) (org-id-locations-save))
17685 (message "Saving all Org buffers... done"))
17687 (defun org-revert-all-org-buffers ()
17688 "Revert all Org buffers.
17689 Prompt for confirmation when there are unsaved changes.
17690 Be sure you know what you are doing before letting this function
17691 overwrite your changes.
17693 This function is useful in a setup where one tracks Org files
17694 with a version control system, to revert on one machine after pulling
17695 changes from another. I believe the procedure must be like this:
17697 1. M-x org-save-all-org-buffers
17698 2. Pull changes from the other machine, resolve conflicts
17699 3. M-x org-revert-all-org-buffers"
17700 (interactive)
17701 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17702 (user-error "Abort"))
17703 (save-excursion
17704 (save-window-excursion
17705 (dolist (b (buffer-list))
17706 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17707 (with-current-buffer b buffer-file-name))
17708 (pop-to-buffer-same-window b)
17709 (revert-buffer t 'no-confirm)))
17710 (when (and (featurep 'org-id) org-id-track-globally)
17711 (org-id-locations-load)))))
17713 ;;;; Agenda files
17715 ;;;###autoload
17716 (defun org-switchb (&optional arg)
17717 "Switch between Org buffers.
17719 With `\\[universal-argument]' prefix, restrict available buffers to files.
17721 With `\\[universal-argument] \\[universal-argument]' \
17722 prefix, restrict available buffers to agenda files."
17723 (interactive "P")
17724 (let ((blist (org-buffer-list
17725 (cond ((equal arg '(4)) 'files)
17726 ((equal arg '(16)) 'agenda)))))
17727 (pop-to-buffer-same-window
17728 (completing-read "Org buffer: "
17729 (mapcar #'list (mapcar #'buffer-name blist))
17730 nil t))))
17732 (defun org-buffer-list (&optional predicate exclude-tmp)
17733 "Return a list of Org buffers.
17734 PREDICATE can be `export', `files' or `agenda'.
17736 export restrict the list to Export buffers.
17737 files restrict the list to buffers visiting Org files.
17738 agenda restrict the list to buffers visiting agenda files.
17740 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17741 (let* ((bfn nil)
17742 (agenda-files (and (eq predicate 'agenda)
17743 (mapcar 'file-truename (org-agenda-files t))))
17744 (filter
17745 (cond
17746 ((eq predicate 'files)
17747 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17748 ((eq predicate 'export)
17749 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17750 ((eq predicate 'agenda)
17751 (lambda (b)
17752 (with-current-buffer b
17753 (and (derived-mode-p 'org-mode)
17754 (setq bfn (buffer-file-name b))
17755 (member (file-truename bfn) agenda-files)))))
17756 (t (lambda (b) (with-current-buffer b
17757 (or (derived-mode-p 'org-mode)
17758 (string-match "\\*Org .*Export"
17759 (buffer-name b)))))))))
17760 (delq nil
17761 (mapcar
17762 (lambda(b)
17763 (if (and (funcall filter b)
17764 (or (not exclude-tmp)
17765 (not (string-match "tmp" (buffer-name b)))))
17767 nil))
17768 (buffer-list)))))
17770 (defun org-agenda-files (&optional unrestricted archives)
17771 "Get the list of agenda files.
17772 Optional UNRESTRICTED means return the full list even if a restriction
17773 is currently in place.
17774 When ARCHIVES is t, include all archive files that are really being
17775 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17776 `org-agenda-archives-mode' is t."
17777 (let ((files
17778 (cond
17779 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17780 ((stringp org-agenda-files) (org-read-agenda-file-list))
17781 ((listp org-agenda-files) org-agenda-files)
17782 (t (error "Invalid value of `org-agenda-files'")))))
17783 (setq files (apply 'append
17784 (mapcar (lambda (f)
17785 (if (file-directory-p f)
17786 (directory-files
17787 f t org-agenda-file-regexp)
17788 (list f)))
17789 files)))
17790 (when org-agenda-skip-unavailable-files
17791 (setq files (delq nil
17792 (mapcar (function
17793 (lambda (file)
17794 (and (file-readable-p file) file)))
17795 files))))
17796 (when (or (eq archives t)
17797 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17798 (setq files (org-add-archive-files files)))
17799 files))
17801 (defun org-agenda-file-p (&optional file)
17802 "Return non-nil, if FILE is an agenda file.
17803 If FILE is omitted, use the file associated with the current
17804 buffer."
17805 (let ((fname (or file (buffer-file-name))))
17806 (and fname
17807 (member (file-truename fname)
17808 (mapcar #'file-truename (org-agenda-files t))))))
17810 (defun org-edit-agenda-file-list ()
17811 "Edit the list of agenda files.
17812 Depending on setup, this either uses customize to edit the variable
17813 `org-agenda-files', or it visits the file that is holding the list. In the
17814 latter case, the buffer is set up in a way that saving it automatically kills
17815 the buffer and restores the previous window configuration."
17816 (interactive)
17817 (if (stringp org-agenda-files)
17818 (let ((cw (current-window-configuration)))
17819 (find-file org-agenda-files)
17820 (setq-local org-window-configuration cw)
17821 (add-hook 'after-save-hook
17822 (lambda ()
17823 (set-window-configuration
17824 (prog1 org-window-configuration
17825 (kill-buffer (current-buffer))))
17826 (org-install-agenda-files-menu)
17827 (message "New agenda file list installed"))
17828 nil 'local)
17829 (message "%s" (substitute-command-keys
17830 "Edit list and finish with \\[save-buffer]")))
17831 (customize-variable 'org-agenda-files)))
17833 (defun org-store-new-agenda-file-list (list)
17834 "Set new value for the agenda file list and save it correctly."
17835 (if (stringp org-agenda-files)
17836 (let ((fe (org-read-agenda-file-list t)) b u)
17837 (while (setq b (find-buffer-visiting org-agenda-files))
17838 (kill-buffer b))
17839 (with-temp-file org-agenda-files
17840 (insert
17841 (mapconcat
17842 (lambda (f) ;; Keep un-expanded entries.
17843 (if (setq u (assoc f fe))
17844 (cdr u)
17846 list "\n")
17847 "\n")))
17848 (let ((org-mode-hook nil) (org-inhibit-startup t)
17849 (org-insert-mode-line-in-empty-file nil))
17850 (setq org-agenda-files list)
17851 (customize-save-variable 'org-agenda-files org-agenda-files))))
17853 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17854 "Read the list of agenda files from a file.
17855 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17856 filenames, used by `org-store-new-agenda-file-list' to write back
17857 un-expanded file names."
17858 (when (file-directory-p org-agenda-files)
17859 (error "`org-agenda-files' cannot be a single directory"))
17860 (when (stringp org-agenda-files)
17861 (with-temp-buffer
17862 (insert-file-contents org-agenda-files)
17863 (mapcar
17864 (lambda (f)
17865 (let ((e (expand-file-name (substitute-in-file-name f)
17866 org-directory)))
17867 (if pair-with-expansion
17868 (cons e f)
17869 e)))
17870 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17872 ;;;###autoload
17873 (defun org-cycle-agenda-files ()
17874 "Cycle through the files in `org-agenda-files'.
17875 If the current buffer visits an agenda file, find the next one in the list.
17876 If the current buffer does not, find the first agenda file."
17877 (interactive)
17878 (let* ((fs (or (org-agenda-files t)
17879 (user-error "No agenda files")))
17880 (files (copy-sequence fs))
17881 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17882 file)
17883 (when tcf
17884 (while (and (setq file (pop files))
17885 (not (equal (file-truename file) tcf)))))
17886 (find-file (car (or files fs)))
17887 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17889 (defun org-agenda-file-to-front (&optional to-end)
17890 "Move/add the current file to the top of the agenda file list.
17891 If the file is not present in the list, it is added to the front. If it is
17892 present, it is moved there. With optional argument TO-END, add/move to the
17893 end of the list."
17894 (interactive "P")
17895 (let ((org-agenda-skip-unavailable-files nil)
17896 (file-alist (mapcar (lambda (x)
17897 (cons (file-truename x) x))
17898 (org-agenda-files t)))
17899 (ctf (file-truename
17900 (or buffer-file-name
17901 (user-error "Please save the current buffer to a file"))))
17902 x had)
17903 (setq x (assoc ctf file-alist) had x)
17905 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17906 (if to-end
17907 (setq file-alist (append (delq x file-alist) (list x)))
17908 (setq file-alist (cons x (delq x file-alist))))
17909 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17910 (org-install-agenda-files-menu)
17911 (message "File %s to %s of agenda file list"
17912 (if had "moved" "added") (if to-end "end" "front"))))
17914 (defun org-remove-file (&optional file)
17915 "Remove current file from the list of files in variable `org-agenda-files'.
17916 These are the files which are being checked for agenda entries.
17917 Optional argument FILE means use this file instead of the current."
17918 (interactive)
17919 (let* ((org-agenda-skip-unavailable-files nil)
17920 (file (or file buffer-file-name
17921 (user-error "Current buffer does not visit a file")))
17922 (true-file (file-truename file))
17923 (afile (abbreviate-file-name file))
17924 (files (delq nil (mapcar
17925 (lambda (x)
17926 (unless (equal true-file
17927 (file-truename x))
17929 (org-agenda-files t)))))
17930 (if (not (= (length files) (length (org-agenda-files t))))
17931 (progn
17932 (org-store-new-agenda-file-list files)
17933 (org-install-agenda-files-menu)
17934 (message "Removed from Org Agenda list: %s" afile))
17935 (message "File was not in list: %s (not removed)" afile))))
17937 (defun org-file-menu-entry (file)
17938 (vector file (list 'find-file file) t))
17940 (defun org-check-agenda-file (file)
17941 "Make sure FILE exists. If not, ask user what to do."
17942 (unless (file-exists-p file)
17943 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17944 (abbreviate-file-name file))
17945 (let ((r (downcase (read-char-exclusive))))
17946 (cond
17947 ((equal r ?r)
17948 (org-remove-file file)
17949 (throw 'nextfile t))
17950 (t (user-error "Abort"))))))
17952 (defun org-get-agenda-file-buffer (file)
17953 "Get an agenda buffer visiting FILE.
17954 If the buffer needs to be created, add it to the list of buffers
17955 which might be released later."
17956 (let ((buf (org-find-base-buffer-visiting file)))
17957 (if buf
17958 buf ; just return it
17959 ;; Make a new buffer and remember it
17960 (setq buf (find-file-noselect file))
17961 (when buf (push buf org-agenda-new-buffers))
17962 buf)))
17964 (defun org-release-buffers (blist)
17965 "Release all buffers in list, asking the user for confirmation when needed.
17966 When a buffer is unmodified, it is just killed. When modified, it is saved
17967 \(if the user agrees) and then killed."
17968 (let (file)
17969 (dolist (buf blist)
17970 (setq file (buffer-file-name buf))
17971 (when (and (buffer-modified-p buf)
17972 file
17973 (y-or-n-p (format "Save file %s? " file)))
17974 (with-current-buffer buf (save-buffer)))
17975 (kill-buffer buf))))
17977 (defun org-agenda-prepare-buffers (files)
17978 "Create buffers for all agenda files, protect archived trees and comments."
17979 (interactive)
17980 (let ((pa '(:org-archived t))
17981 (pc '(:org-comment t))
17982 (pall '(:org-archived t :org-comment t))
17983 (inhibit-read-only t)
17984 (org-inhibit-startup org-agenda-inhibit-startup)
17985 (rea (concat ":" org-archive-tag ":"))
17986 re pos)
17987 (setq org-tag-alist-for-agenda nil
17988 org-tag-groups-alist-for-agenda nil)
17989 (save-excursion
17990 (save-restriction
17991 (dolist (file files)
17992 (catch 'nextfile
17993 (if (bufferp file)
17994 (set-buffer file)
17995 (org-check-agenda-file file)
17996 (set-buffer (org-get-agenda-file-buffer file)))
17997 (widen)
17998 (org-set-regexps-and-options 'tags-only)
17999 (setq pos (point))
18000 (or (memq 'category org-agenda-ignore-properties)
18001 (org-refresh-category-properties))
18002 (or (memq 'stats org-agenda-ignore-properties)
18003 (org-refresh-stats-properties))
18004 (or (memq 'effort org-agenda-ignore-properties)
18005 (org-refresh-effort-properties))
18006 (or (memq 'appt org-agenda-ignore-properties)
18007 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18008 (setq org-todo-keywords-for-agenda
18009 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18010 (setq org-done-keywords-for-agenda
18011 (append org-done-keywords-for-agenda org-done-keywords))
18012 (setq org-todo-keyword-alist-for-agenda
18013 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18014 (setq org-tag-alist-for-agenda
18015 (org-tag-add-to-alist
18016 org-tag-alist-for-agenda
18017 org-current-tag-alist))
18018 ;; Merge current file's tag groups into global
18019 ;; `org-tag-groups-alist-for-agenda'.
18020 (when org-group-tags
18021 (dolist (alist org-tag-groups-alist)
18022 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18023 (if old
18024 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18025 (push alist org-tag-groups-alist-for-agenda)))))
18026 (org-with-silent-modifications
18027 (save-excursion
18028 (remove-text-properties (point-min) (point-max) pall)
18029 (when org-agenda-skip-archived-trees
18030 (goto-char (point-min))
18031 (while (re-search-forward rea nil t)
18032 (when (org-at-heading-p t)
18033 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18034 (goto-char (point-min))
18035 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18036 (while (re-search-forward re nil t)
18037 (when (save-match-data (org-in-commented-heading-p t))
18038 (add-text-properties
18039 (match-beginning 0) (org-end-of-subtree t) pc)))))
18040 (goto-char pos)))))
18041 (setq org-todo-keywords-for-agenda
18042 (org-uniquify org-todo-keywords-for-agenda))
18043 (setq org-todo-keyword-alist-for-agenda
18044 (org-uniquify org-todo-keyword-alist-for-agenda))))
18047 ;;;; CDLaTeX minor mode
18049 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18050 "Keymap for the minor `org-cdlatex-mode'.")
18052 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
18053 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
18054 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
18055 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
18056 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
18058 (defvar org-cdlatex-texmathp-advice-is-done nil
18059 "Flag remembering if we have applied the advice to texmathp already.")
18061 (define-minor-mode org-cdlatex-mode
18062 "Toggle the minor `org-cdlatex-mode'.
18063 This mode supports entering LaTeX environment and math in LaTeX fragments
18064 in Org mode.
18065 \\{org-cdlatex-mode-map}"
18066 nil " OCDL" nil
18067 (when org-cdlatex-mode
18068 (require 'cdlatex)
18069 (run-hooks 'cdlatex-mode-hook)
18070 (cdlatex-compute-tables))
18071 (unless org-cdlatex-texmathp-advice-is-done
18072 (setq org-cdlatex-texmathp-advice-is-done t)
18073 (defadvice texmathp (around org-math-always-on activate)
18074 "Always return t in Org buffers.
18075 This is because we want to insert math symbols without dollars even outside
18076 the LaTeX math segments. If Org mode thinks that point is actually inside
18077 an embedded LaTeX fragment, let `texmathp' do its job.
18078 `\\[org-cdlatex-mode-map]'"
18079 (interactive)
18080 (let (p)
18081 (cond
18082 ((not (derived-mode-p 'org-mode)) ad-do-it)
18083 ((eq this-command 'cdlatex-math-symbol)
18084 (setq ad-return-value t
18085 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18087 (let ((p (org-inside-LaTeX-fragment-p)))
18088 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18089 (setq ad-return-value t
18090 texmathp-why '("Org mode embedded math" . 0))
18091 (when p ad-do-it)))))))))
18093 (defun turn-on-org-cdlatex ()
18094 "Unconditionally turn on `org-cdlatex-mode'."
18095 (org-cdlatex-mode 1))
18097 (defun org-try-cdlatex-tab ()
18098 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18099 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18100 - inside a LaTeX fragment, or
18101 - after the first word in a line, where an abbreviation expansion could
18102 insert a LaTeX environment."
18103 (when org-cdlatex-mode
18104 (cond
18105 ;; Before any word on the line: No expansion possible.
18106 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18107 ;; Just after first word on the line: Expand it. Make sure it
18108 ;; cannot happen on headlines, though.
18109 ((save-excursion
18110 (skip-chars-backward "a-zA-Z0-9*")
18111 (skip-chars-backward " \t")
18112 (and (bolp) (not (org-at-heading-p))))
18113 (cdlatex-tab) t)
18114 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18116 (defun org-cdlatex-underscore-caret (&optional _arg)
18117 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18118 Revert to the normal definition outside of these fragments."
18119 (interactive "P")
18120 (if (org-inside-LaTeX-fragment-p)
18121 (call-interactively 'cdlatex-sub-superscript)
18122 (let (org-cdlatex-mode)
18123 (call-interactively (key-binding (vector last-input-event))))))
18125 (defun org-cdlatex-math-modify (&optional _arg)
18126 "Execute `cdlatex-math-modify' in LaTeX fragments.
18127 Revert to the normal definition outside of these fragments."
18128 (interactive "P")
18129 (if (org-inside-LaTeX-fragment-p)
18130 (call-interactively 'cdlatex-math-modify)
18131 (let (org-cdlatex-mode)
18132 (call-interactively (key-binding (vector last-input-event))))))
18134 (defun org-cdlatex-environment-indent (&optional environment item)
18135 "Execute `cdlatex-environment' and indent the inserted environment.
18137 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18139 The inserted environment is indented to current indentation
18140 unless point is at the beginning of the line, in which the
18141 environment remains unintended."
18142 (interactive)
18143 ;; cdlatex-environment always return nil. Therefore, capture output
18144 ;; first and determine if an environment was selected.
18145 (let* ((beg (point-marker))
18146 (end (copy-marker (point) t))
18147 (inserted (progn
18148 (ignore-errors (cdlatex-environment environment item))
18149 (< beg end)))
18150 ;; Figure out how many lines to move forward after the
18151 ;; environment has been inserted.
18152 (lines (when inserted
18153 (save-excursion
18154 (- (cl-loop while (< beg (point))
18155 with x = 0
18156 do (forward-line -1)
18157 (cl-incf x)
18158 finally return x)
18159 (if (progn (goto-char beg)
18160 (and (progn (skip-chars-forward " \t") (eolp))
18161 (progn (skip-chars-backward " \t") (bolp))))
18162 1 0)))))
18163 (env (org-trim (delete-and-extract-region beg end))))
18164 (when inserted
18165 ;; Get indentation of next line unless at column 0.
18166 (let ((ind (if (bolp) 0
18167 (save-excursion
18168 (org-return-indent)
18169 (prog1 (org-get-indentation)
18170 (when (progn (skip-chars-forward " \t") (eolp))
18171 (delete-region beg (point)))))))
18172 (bol (progn (skip-chars-backward " \t") (bolp))))
18173 ;; Insert a newline before environment unless at column zero
18174 ;; to "escape" the current line. Insert a newline if
18175 ;; something is one the same line as \end{ENVIRONMENT}.
18176 (insert
18177 (concat (unless bol "\n") env
18178 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18179 (unless (zerop ind)
18180 (save-excursion
18181 (goto-char beg)
18182 (while (< (point) end)
18183 (unless (eolp) (indent-line-to ind))
18184 (forward-line))))
18185 (goto-char beg)
18186 (forward-line lines)
18187 (indent-line-to ind)))
18188 (set-marker beg nil)
18189 (set-marker end nil)))
18192 ;;;; LaTeX fragments
18194 (defun org-inside-LaTeX-fragment-p ()
18195 "Test if point is inside a LaTeX fragment.
18196 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18197 sequence appearing also before point.
18198 Even though the matchers for math are configurable, this function assumes
18199 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18200 delimiters are skipped when they have been removed by customization.
18201 The return value is nil, or a cons cell with the delimiter and the
18202 position of this delimiter.
18204 This function does a reasonably good job, but can locally be fooled by
18205 for example currency specifications. For example it will assume being in
18206 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18207 fragments that are properly closed, but during editing, we have to live
18208 with the uncertainty caused by missing closing delimiters. This function
18209 looks only before point, not after."
18210 (catch 'exit
18211 (let ((pos (point))
18212 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18213 (lim (save-excursion (org-backward-paragraph) (point)))
18214 dd-on str (start 0) m re)
18215 (goto-char pos)
18216 (when dodollar
18217 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18218 re (nth 1 (assoc "$" org-latex-regexps)))
18219 (while (string-match re str start)
18220 (cond
18221 ((= (match-end 0) (length str))
18222 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18223 ((= (match-end 0) (- (length str) 5))
18224 (throw 'exit nil))
18225 (t (setq start (match-end 0))))))
18226 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18227 (goto-char pos)
18228 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18229 (and (match-beginning 2) (throw 'exit nil))
18230 ;; count $$
18231 (while (re-search-backward "\\$\\$" lim t)
18232 (setq dd-on (not dd-on)))
18233 (goto-char pos)
18234 (when dd-on (cons "$$" m))))))
18236 (defun org-inside-latex-macro-p ()
18237 "Is point inside a LaTeX macro or its arguments?"
18238 (save-match-data
18239 (org-in-regexp
18240 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18242 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18243 "Build an overlay between BEG and END using IMAGE file.
18244 Argument IMAGETYPE is the extension of the displayed image,
18245 as a string. It defaults to \"png\"."
18246 (let ((ov (make-overlay beg end))
18247 (imagetype (or (intern imagetype) 'png)))
18248 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18249 (overlay-put ov 'evaporate t)
18250 (overlay-put ov
18251 'modification-hooks
18252 (list (lambda (o _flag _beg _end &optional _l)
18253 (delete-overlay o))))
18254 (overlay-put ov
18255 'display
18256 (list 'image :type imagetype :file image :ascent 'center))))
18258 (defun org--list-latex-overlays (&optional beg end)
18259 "List all Org LaTeX overlays in current buffer.
18260 Limit to overlays between BEG and END when those are provided."
18261 (cl-remove-if-not
18262 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18263 (overlays-in (or beg (point-min)) (or end (point-max)))))
18265 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18266 "Remove all overlays with LaTeX fragment images in current buffer.
18267 When optional arguments BEG and END are non-nil, remove all
18268 overlays between them instead. Return a non-nil value when some
18269 overlays were removed, nil otherwise."
18270 (let ((overlays (org--list-latex-overlays beg end)))
18271 (mapc #'delete-overlay overlays)
18272 overlays))
18274 (defun org-toggle-latex-fragment (&optional arg)
18275 "Preview the LaTeX fragment at point, or all locally or globally.
18277 If the cursor is on a LaTeX fragment, create the image and overlay
18278 it over the source code, if there is none. Remove it otherwise.
18279 If there is no fragment at point, display all fragments in the
18280 current section.
18282 With prefix ARG, preview or clear image for all fragments in the
18283 current subtree or in the whole buffer when used before the first
18284 headline. With a prefix ARG `\\[universal-argument] \
18285 \\[universal-argument]' preview or clear images
18286 for all fragments in the buffer."
18287 (interactive "P")
18288 (when (display-graphic-p)
18289 (catch 'exit
18290 (save-excursion
18291 (let (beg end msg)
18292 (cond
18293 ((or (equal arg '(16))
18294 (and (equal arg '(4))
18295 (org-with-limited-levels (org-before-first-heading-p))))
18296 (if (org-remove-latex-fragment-image-overlays)
18297 (progn (message "LaTeX fragments images removed from buffer")
18298 (throw 'exit nil))
18299 (setq msg "Creating images for buffer...")))
18300 ((equal arg '(4))
18301 (org-with-limited-levels (org-back-to-heading t))
18302 (setq beg (point))
18303 (setq end (progn (org-end-of-subtree t) (point)))
18304 (if (org-remove-latex-fragment-image-overlays beg end)
18305 (progn
18306 (message "LaTeX fragment images removed from subtree")
18307 (throw 'exit nil))
18308 (setq msg "Creating images for subtree...")))
18309 ((let ((datum (org-element-context)))
18310 (when (memq (org-element-type datum)
18311 '(latex-environment latex-fragment))
18312 (setq beg (org-element-property :begin datum))
18313 (setq end (org-element-property :end datum))
18314 (if (org-remove-latex-fragment-image-overlays beg end)
18315 (progn (message "LaTeX fragment image removed")
18316 (throw 'exit nil))
18317 (setq msg "Creating image...")))))
18319 (org-with-limited-levels
18320 (setq beg (if (org-at-heading-p) (line-beginning-position)
18321 (outline-previous-heading)
18322 (point)))
18323 (setq end (progn (outline-next-heading) (point)))
18324 (if (org-remove-latex-fragment-image-overlays beg end)
18325 (progn
18326 (message "LaTeX fragment images removed from section")
18327 (throw 'exit nil))
18328 (setq msg "Creating images for section...")))))
18329 (let ((file (buffer-file-name (buffer-base-buffer))))
18330 (org-format-latex
18331 (concat org-preview-latex-image-directory "org-ltximg")
18332 beg end
18333 ;; Emacs cannot overlay images from remote hosts. Create
18334 ;; it in `temporary-file-directory' instead.
18335 (if (or (not file) (file-remote-p file))
18336 temporary-file-directory
18337 default-directory)
18338 'overlays msg 'forbuffer org-preview-latex-default-process))
18339 (message (concat msg "done")))))))
18341 (defun org-format-latex
18342 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18343 "Replace LaTeX fragments with links to an image.
18345 The function takes care of creating the replacement image.
18347 Only consider fragments between BEG and END when those are
18348 provided.
18350 When optional argument OVERLAYS is non-nil, display the image on
18351 top of the fragment instead of replacing it.
18353 PROCESSING-TYPE is the conversion method to use, as a symbol.
18355 Some of the options can be changed using the variable
18356 `org-format-latex-options', which see."
18357 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18358 (unless (eq processing-type 'verbatim)
18359 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18360 (cnt 0)
18361 checkdir-flag)
18362 (goto-char (or beg (point-min)))
18363 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18364 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18365 (overlay-recenter (or end (point-max))))
18366 (while (re-search-forward math-regexp end t)
18367 (unless (and overlays
18368 (eq (get-char-property (point) 'org-overlay-type)
18369 'org-latex-overlay))
18370 (let* ((context (org-element-context))
18371 (type (org-element-type context)))
18372 (when (memq type '(latex-environment latex-fragment))
18373 (let ((block-type (eq type 'latex-environment))
18374 (value (org-element-property :value context))
18375 (beg (org-element-property :begin context))
18376 (end (save-excursion
18377 (goto-char (org-element-property :end context))
18378 (skip-chars-backward " \r\t\n")
18379 (point))))
18380 (cond
18381 ((eq processing-type 'mathjax)
18382 ;; Prepare for MathJax processing.
18383 (if (not (string-match "\\`\\$\\$?" value))
18384 (goto-char end)
18385 (delete-region beg end)
18386 (if (string= (match-string 0 value) "$$")
18387 (insert "\\[" (substring value 2 -2) "\\]")
18388 (insert "\\(" (substring value 1 -1) "\\)"))))
18389 ((assq processing-type org-preview-latex-process-alist)
18390 ;; Process to an image.
18391 (cl-incf cnt)
18392 (goto-char beg)
18393 (let* ((processing-info
18394 (cdr (assq processing-type org-preview-latex-process-alist)))
18395 (face (face-at-point))
18396 ;; Get the colors from the face at point.
18398 (let ((color (plist-get org-format-latex-options
18399 :foreground)))
18400 (if (and forbuffer (eq color 'auto))
18401 (face-attribute face :foreground nil 'default)
18402 color)))
18404 (let ((color (plist-get org-format-latex-options
18405 :background)))
18406 (if (and forbuffer (eq color 'auto))
18407 (face-attribute face :background nil 'default)
18408 color)))
18409 (hash (sha1 (prin1-to-string
18410 (list org-format-latex-header
18411 org-latex-default-packages-alist
18412 org-latex-packages-alist
18413 org-format-latex-options
18414 forbuffer value fg bg))))
18415 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18416 (absprefix (expand-file-name prefix dir))
18417 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18418 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18419 (sep (and block-type "\n\n"))
18420 (link (concat sep "[[file:" linkfile "]]" sep))
18421 (options
18422 (org-combine-plists
18423 org-format-latex-options
18424 `(:foreground ,fg :background ,bg))))
18425 (when msg (message msg cnt))
18426 (unless checkdir-flag ; Ensure the directory exists.
18427 (setq checkdir-flag t)
18428 (let ((todir (file-name-directory absprefix)))
18429 (unless (file-directory-p todir)
18430 (make-directory todir t))))
18431 (unless (file-exists-p movefile)
18432 (org-create-formula-image
18433 value movefile options forbuffer processing-type))
18434 (if overlays
18435 (progn
18436 (dolist (o (overlays-in beg end))
18437 (when (eq (overlay-get o 'org-overlay-type)
18438 'org-latex-overlay)
18439 (delete-overlay o)))
18440 (org--format-latex-make-overlay beg end movefile imagetype)
18441 (goto-char end))
18442 (delete-region beg end)
18443 (insert
18444 (org-add-props link
18445 (list 'org-latex-src
18446 (replace-regexp-in-string "\"" "" value)
18447 'org-latex-src-embed-type
18448 (if block-type 'paragraph 'character)))))))
18449 ((eq processing-type 'mathml)
18450 ;; Process to MathML.
18451 (unless (org-format-latex-mathml-available-p)
18452 (user-error "LaTeX to MathML converter not configured"))
18453 (cl-incf cnt)
18454 (when msg (message msg cnt))
18455 (goto-char beg)
18456 (delete-region beg end)
18457 (insert (org-format-latex-as-mathml
18458 value block-type prefix dir)))
18460 (error "Unknown conversion process %s for LaTeX fragments"
18461 processing-type)))))))))))
18463 (defun org-create-math-formula (latex-frag &optional mathml-file)
18464 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18465 Use `org-latex-to-mathml-convert-command'. If the conversion is
18466 sucessful, return the portion between \"<math...> </math>\"
18467 elements otherwise return nil. When MATHML-FILE is specified,
18468 write the results in to that file. When invoked as an
18469 interactive command, prompt for LATEX-FRAG, with initial value
18470 set to the current active region and echo the results for user
18471 inspection."
18472 (interactive (list (let ((frag (when (org-region-active-p)
18473 (buffer-substring-no-properties
18474 (region-beginning) (region-end)))))
18475 (read-string "LaTeX Fragment: " frag nil frag))))
18476 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18477 (let* ((tmp-in-file
18478 (let ((file (file-relative-name
18479 (make-temp-name (expand-file-name "ltxmathml-in")))))
18480 (write-region latex-frag nil file)
18481 file))
18482 (tmp-out-file (file-relative-name
18483 (make-temp-name (expand-file-name "ltxmathml-out"))))
18484 (cmd (format-spec
18485 org-latex-to-mathml-convert-command
18486 `((?j . ,(and org-latex-to-mathml-jar-file
18487 (shell-quote-argument
18488 (expand-file-name
18489 org-latex-to-mathml-jar-file))))
18490 (?I . ,(shell-quote-argument tmp-in-file))
18491 (?i . ,latex-frag)
18492 (?o . ,(shell-quote-argument tmp-out-file)))))
18493 mathml shell-command-output)
18494 (when (called-interactively-p 'any)
18495 (unless (org-format-latex-mathml-available-p)
18496 (user-error "LaTeX to MathML converter not configured")))
18497 (message "Running %s" cmd)
18498 (setq shell-command-output (shell-command-to-string cmd))
18499 (setq mathml
18500 (when (file-readable-p tmp-out-file)
18501 (with-current-buffer (find-file-noselect tmp-out-file t)
18502 (goto-char (point-min))
18503 (when (re-search-forward
18504 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18505 (regexp-quote
18506 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18507 nil t)
18508 (prog1 (match-string 0) (kill-buffer))))))
18509 (cond
18510 (mathml
18511 (setq mathml
18512 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18513 (when mathml-file
18514 (write-region mathml nil mathml-file))
18515 (when (called-interactively-p 'any)
18516 (message mathml)))
18517 ((message "LaTeX to MathML conversion failed")
18518 (message shell-command-output)))
18519 (delete-file tmp-in-file)
18520 (when (file-exists-p tmp-out-file)
18521 (delete-file tmp-out-file))
18522 mathml))
18524 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18525 prefix &optional dir)
18526 "Use `org-create-math-formula' but check local cache first."
18527 (let* ((absprefix (expand-file-name prefix dir))
18528 (print-length nil) (print-level nil)
18529 (formula-id (concat
18530 "formula-"
18531 (sha1
18532 (prin1-to-string
18533 (list latex-frag
18534 org-latex-to-mathml-convert-command)))))
18535 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18536 (formula-cache-dir (file-name-directory formula-cache)))
18538 (unless (file-directory-p formula-cache-dir)
18539 (make-directory formula-cache-dir t))
18541 (unless (file-exists-p formula-cache)
18542 (org-create-math-formula latex-frag formula-cache))
18544 (if (file-exists-p formula-cache)
18545 ;; Successful conversion. Return the link to MathML file.
18546 (org-add-props
18547 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18548 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18549 'org-latex-src-embed-type (if latex-frag-type
18550 'paragraph 'character)))
18551 ;; Failed conversion. Return the LaTeX fragment verbatim
18552 latex-frag)))
18554 (defun org--get-display-dpi ()
18555 "Get the DPI of the display.
18556 The function assumes that the display has the same pixel width in
18557 the horizontal and vertical directions."
18558 (if (display-graphic-p)
18559 (round (/ (display-pixel-height)
18560 (/ (display-mm-height) 25.4)))
18561 (error "Attempt to calculate the dpi of a non-graphic display")))
18563 (defun org-create-formula-image
18564 (string tofile options buffer &optional processing-type)
18565 "Create an image from LaTeX source using external processes.
18567 The LaTeX STRING is saved to a temporary LaTeX file, then
18568 converted to an image file by process PROCESSING-TYPE defined in
18569 `org-preview-latex-process-alist'. A nil value defaults to
18570 `org-preview-latex-default-process'.
18572 The generated image file is eventually moved to TOFILE.
18574 The OPTIONS argument controls the size, foreground color and
18575 background color of the generated image.
18577 When BUFFER non-nil, this function is used for LaTeX previewing.
18578 Otherwise, it is used to deal with LaTeX snippets showed in
18579 a HTML file."
18580 (let* ((processing-type (or processing-type
18581 org-preview-latex-default-process))
18582 (processing-info
18583 (cdr (assq processing-type org-preview-latex-process-alist)))
18584 (programs (plist-get processing-info :programs))
18585 (error-message (or (plist-get processing-info :message) ""))
18586 (use-xcolor (plist-get processing-info :use-xcolor))
18587 (image-input-type (plist-get processing-info :image-input-type))
18588 (image-output-type (plist-get processing-info :image-output-type))
18589 (post-clean (or (plist-get processing-info :post-clean)
18590 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18591 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18592 (latex-header
18593 (or (plist-get processing-info :latex-header)
18594 (org-latex-make-preamble
18595 (org-export-get-environment (org-export-get-backend 'latex))
18596 org-format-latex-header
18597 'snippet)))
18598 (latex-compiler (plist-get processing-info :latex-compiler))
18599 (image-converter (plist-get processing-info :image-converter))
18600 (tmpdir temporary-file-directory)
18601 (texfilebase (make-temp-name
18602 (expand-file-name "orgtex" tmpdir)))
18603 (texfile (concat texfilebase ".tex"))
18604 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18605 '(1.0 . 1.0)))
18606 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18607 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18608 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18609 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18610 "Black"))
18611 (bg (or (plist-get options (if buffer :background :html-background))
18612 "Transparent"))
18613 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18614 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18615 (dolist (program programs)
18616 (org-check-external-command program error-message))
18617 (if use-xcolor
18618 (progn (if (eq fg 'default)
18619 (setq fg (org-latex-color :foreground))
18620 (setq fg (org-latex-color-format fg)))
18621 (if (eq bg 'default)
18622 (setq bg (org-latex-color :background))
18623 (setq bg (org-latex-color-format
18624 (if (string= bg "Transparent") "white" bg))))
18625 (with-temp-file texfile
18626 (insert latex-header)
18627 (insert "\n\\begin{document}\n"
18628 "\\definecolor{fg}{rgb}{" fg "}\n"
18629 "\\definecolor{bg}{rgb}{" bg "}\n"
18630 "\n\\pagecolor{bg}\n"
18631 "\n{\\color{fg}\n"
18632 string
18633 "\n}\n"
18634 "\n\\end{document}\n")))
18635 (if (eq fg 'default)
18636 (setq fg (org-dvipng-color :foreground))
18637 (unless (string= fg "Transparent")
18638 (setq fg (org-dvipng-color-format fg))))
18639 (if (eq bg 'default)
18640 (setq bg (org-dvipng-color :background))
18641 (unless (string= bg "Transparent")
18642 (setq bg (org-dvipng-color-format bg))))
18643 (with-temp-file texfile
18644 (insert latex-header)
18645 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18647 (let* ((err-msg (format "Please adjust `%s' part of \
18648 `org-preview-latex-process-alist'."
18649 processing-type))
18650 (image-input-file
18651 (org-compile-file
18652 texfile latex-compiler image-input-type err-msg log-buf))
18653 (image-output-file
18654 (org-compile-file
18655 image-input-file image-converter image-output-type err-msg log-buf
18656 `((?F . ,(shell-quote-argument fg))
18657 (?B . ,(shell-quote-argument bg))
18658 (?D . ,(shell-quote-argument (format "%s" dpi)))
18659 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18660 (copy-file image-output-file tofile 'replace)
18661 (dolist (e post-clean)
18662 (when (file-exists-p (concat texfilebase e))
18663 (delete-file (concat texfilebase e))))
18664 image-output-file)))
18666 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18667 "Fill a LaTeX header template TPL.
18668 In the template, the following place holders will be recognized:
18670 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18671 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18672 [PACKAGES] \\usepackage statements for PKG
18673 [NO-PACKAGES] do not include PKG
18674 [EXTRA] the string EXTRA
18675 [NO-EXTRA] do not include EXTRA
18677 For backward compatibility, if both the positive and the negative place
18678 holder is missing, the positive one (without the \"NO-\") will be
18679 assumed to be present at the end of the template.
18680 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18681 EXTRA is a string.
18682 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18683 (let (rpl (end ""))
18684 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18685 (setq rpl (if (or (match-end 1) (not def-pkg))
18686 "" (org-latex-packages-to-string def-pkg snippets-p t))
18687 tpl (replace-match rpl t t tpl))
18688 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18690 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18691 (setq rpl (if (or (match-end 1) (not pkg))
18692 "" (org-latex-packages-to-string pkg snippets-p t))
18693 tpl (replace-match rpl t t tpl))
18694 (when pkg (setq end
18695 (concat end "\n"
18696 (org-latex-packages-to-string pkg snippets-p)))))
18698 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18699 (setq rpl (if (or (match-end 1) (not extra))
18700 "" (concat extra "\n"))
18701 tpl (replace-match rpl t t tpl))
18702 (when (and extra (string-match "\\S-" extra))
18703 (setq end (concat end "\n" extra))))
18705 (if (string-match "\\S-" end)
18706 (concat tpl "\n" end)
18707 tpl)))
18709 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18710 "Turn an alist of packages into a string with the \\usepackage macros."
18711 (setq pkg (mapconcat (lambda(p)
18712 (cond
18713 ((stringp p) p)
18714 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18715 (format "%% Package %s omitted" (cadr p)))
18716 ((equal "" (car p))
18717 (format "\\usepackage{%s}" (cadr p)))
18719 (format "\\usepackage[%s]{%s}"
18720 (car p) (cadr p)))))
18722 "\n"))
18723 (if newline (concat pkg "\n") pkg))
18725 (defun org-dvipng-color (attr)
18726 "Return a RGB color specification for dvipng."
18727 (org-dvipng-color-format (face-attribute 'default attr nil)))
18729 (defun org-dvipng-color-format (color-name)
18730 "Convert COLOR-NAME to a RGB color value for dvipng."
18731 (apply #'format "rgb %s %s %s"
18732 (mapcar 'org-normalize-color
18733 (color-values color-name))))
18735 (defun org-latex-color (attr)
18736 "Return a RGB color for the LaTeX color package."
18737 (org-latex-color-format (face-attribute 'default attr nil)))
18739 (defun org-latex-color-format (color-name)
18740 "Convert COLOR-NAME to a RGB color value."
18741 (apply #'format "%s,%s,%s"
18742 (mapcar 'org-normalize-color
18743 (color-values color-name))))
18745 (defun org-normalize-color (value)
18746 "Return string to be used as color value for an RGB component."
18747 (format "%g" (/ value 65535.0)))
18750 ;; Image display
18752 (defvar-local org-inline-image-overlays nil)
18754 (defun org-toggle-inline-images (&optional include-linked)
18755 "Toggle the display of inline images.
18756 INCLUDE-LINKED is passed to `org-display-inline-images'."
18757 (interactive "P")
18758 (if org-inline-image-overlays
18759 (progn
18760 (org-remove-inline-images)
18761 (when (called-interactively-p 'interactive)
18762 (message "Inline image display turned off")))
18763 (org-display-inline-images include-linked)
18764 (when (called-interactively-p 'interactive)
18765 (message (if org-inline-image-overlays
18766 (format "%d images displayed inline"
18767 (length org-inline-image-overlays))
18768 "No images to display inline")))))
18770 (defun org-redisplay-inline-images ()
18771 "Refresh the display of inline images."
18772 (interactive)
18773 (if (not org-inline-image-overlays)
18774 (org-toggle-inline-images)
18775 (org-toggle-inline-images)
18776 (org-toggle-inline-images)))
18778 (defun org-display-inline-images (&optional include-linked refresh beg end)
18779 "Display inline images.
18781 An inline image is a link which follows either of these
18782 conventions:
18784 1. Its path is a file with an extension matching return value
18785 from `image-file-name-regexp' and it has no contents.
18787 2. Its description consists in a single link of the previous
18788 type.
18790 When optional argument INCLUDE-LINKED is non-nil, also links with
18791 a text description part will be inlined. This can be nice for
18792 a quick look at those images, but it does not reflect what
18793 exported files will look like.
18795 When optional argument REFRESH is non-nil, refresh existing
18796 images between BEG and END. This will create new image displays
18797 only if necessary. BEG and END default to the buffer
18798 boundaries."
18799 (interactive "P")
18800 (when (display-graphic-p)
18801 (unless refresh
18802 (org-remove-inline-images)
18803 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18804 (org-with-wide-buffer
18805 (goto-char (or beg (point-min)))
18806 (let* ((case-fold-search t)
18807 (file-extension-re (image-file-name-regexp))
18808 (link-abbrevs (mapcar #'car
18809 (append org-link-abbrev-alist-local
18810 org-link-abbrev-alist)))
18811 ;; Check absolute, relative file names and explicit
18812 ;; "file:" links. Also check link abbreviations since
18813 ;; some might expand to "file" links.
18814 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18815 (if (not link-abbrevs) ""
18816 (format "\\|\\(?:%s:\\)"
18817 (regexp-opt link-abbrevs))))))
18818 (while (re-search-forward file-types-re end t)
18819 (let ((link (save-match-data (org-element-context))))
18820 ;; Check if we're at an inline image, i.e., an image file
18821 ;; link without a description (unless INCLUDE-LINKED is
18822 ;; non-nil).
18823 (when (and (equal "file" (org-element-property :type link))
18824 (or include-linked
18825 (null (org-element-contents link)))
18826 (string-match-p file-extension-re
18827 (org-element-property :path link)))
18828 (let ((file (expand-file-name
18829 (org-link-unescape
18830 (org-element-property :path link)))))
18831 (when (file-exists-p file)
18832 (let ((width
18833 ;; Apply `org-image-actual-width' specifications.
18834 (cond
18835 ((not (image-type-available-p 'imagemagick)) nil)
18836 ((eq org-image-actual-width t) nil)
18837 ((listp org-image-actual-width)
18839 ;; First try to find a width among
18840 ;; attributes associated to the paragraph
18841 ;; containing link.
18842 (let ((paragraph
18843 (let ((e link))
18844 (while (and (setq e (org-element-property
18845 :parent e))
18846 (not (eq (org-element-type e)
18847 'paragraph))))
18848 e)))
18849 (when paragraph
18850 (save-excursion
18851 (goto-char (org-element-property :begin paragraph))
18852 (when
18853 (re-search-forward
18854 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18855 (org-element-property
18856 :post-affiliated paragraph)
18858 (string-to-number (match-string 1))))))
18859 ;; Otherwise, fall-back to provided number.
18860 (car org-image-actual-width)))
18861 ((numberp org-image-actual-width)
18862 org-image-actual-width)))
18863 (old (get-char-property-and-overlay
18864 (org-element-property :begin link)
18865 'org-image-overlay)))
18866 (if (and (car-safe old) refresh)
18867 (image-refresh (overlay-get (cdr old) 'display))
18868 (let ((image (create-image file
18869 (and width 'imagemagick)
18871 :width width)))
18872 (when image
18873 (let ((ov (make-overlay
18874 (org-element-property :begin link)
18875 (progn
18876 (goto-char
18877 (org-element-property :end link))
18878 (skip-chars-backward " \t")
18879 (point)))))
18880 (overlay-put ov 'display image)
18881 (overlay-put ov 'face 'default)
18882 (overlay-put ov 'org-image-overlay t)
18883 (overlay-put
18884 ov 'modification-hooks
18885 (list 'org-display-inline-remove-overlay))
18886 (push ov org-inline-image-overlays)))))))))))))))
18888 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18889 "Remove inline-display overlay if a corresponding region is modified."
18890 (let ((inhibit-modification-hooks t))
18891 (when (and ov after)
18892 (delete ov org-inline-image-overlays)
18893 (delete-overlay ov))))
18895 (defun org-remove-inline-images ()
18896 "Remove inline display of images."
18897 (interactive)
18898 (mapc #'delete-overlay org-inline-image-overlays)
18899 (setq org-inline-image-overlays nil))
18902 ;;; Key bindings
18904 (defun org-remap (map &rest commands)
18905 "In MAP, remap the functions given in COMMANDS.
18906 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18907 (let (new old)
18908 (while commands
18909 (setq old (pop commands) new (pop commands))
18910 (org-defkey map (vector 'remap old) new))))
18912 ;;;; Outline functions that can be remapped in Org
18913 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18914 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18915 (define-key org-mode-map [remap outline-forward-same-level]
18916 #'org-forward-heading-same-level)
18917 (define-key org-mode-map [remap outline-backward-same-level]
18918 #'org-backward-heading-same-level)
18919 (define-key org-mode-map [remap outline-show-branches]
18920 #'org-kill-note-or-show-branches)
18921 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18922 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18923 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18924 (define-key org-mode-map [remap outline-next-visible-heading]
18925 #'org-next-visible-heading)
18926 (define-key org-mode-map [remap outline-previous-visible-heading]
18927 #'org-previous-visible-heading)
18928 (define-key org-mode-map [remap show-children] #'org-show-children)
18930 ;;;; Make `C-c C-x' a prefix key
18931 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18933 ;;;; TAB key with modifiers
18934 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18935 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18936 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18937 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18938 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18940 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18941 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18942 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18944 ;;;; RET key with modifiers
18945 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18946 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18947 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18948 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18949 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18951 ;;;; Cursor keys with modifiers
18952 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18953 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18954 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18955 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18956 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18957 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18958 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18960 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18961 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18962 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18963 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18964 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18965 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18966 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18967 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18968 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18969 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18971 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18972 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18973 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18974 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18976 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18977 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18978 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18979 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18981 ;;;; Babel keys
18982 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18983 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18984 (define-key org-babel-map key def))
18986 ;;;; Extra keys for TTY access.
18988 ;; We only set them when really needed because otherwise the
18989 ;; menus don't show the simple keys
18991 (when (or org-use-extra-keys (not window-system))
18992 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18993 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18994 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18995 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18996 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18997 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18998 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18999 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
19000 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
19001 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
19002 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
19003 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
19004 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
19005 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
19006 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
19007 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
19008 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
19009 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
19010 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
19011 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
19012 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
19014 ;;;; Narrow map
19015 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
19016 (org-defkey narrow-map "b" #'org-narrow-to-block)
19017 (org-defkey narrow-map "e" #'org-narrow-to-element)
19019 ;;;; Remap usual Emacs bindings
19020 (org-remap org-mode-map
19021 'self-insert-command 'org-self-insert-command
19022 'delete-char 'org-delete-char
19023 'delete-backward-char 'org-delete-backward-char
19024 'kill-line 'org-kill-line
19025 'open-line 'org-open-line
19026 'yank 'org-yank
19027 'comment-dwim 'org-comment-dwim
19028 'move-beginning-of-line 'org-beginning-of-line
19029 'move-end-of-line 'org-end-of-line
19030 'forward-paragraph 'org-forward-paragraph
19031 'backward-paragraph 'org-backward-paragraph
19032 'backward-sentence 'org-backward-sentence
19033 'forward-sentence 'org-forward-sentence
19034 'fill-paragraph 'org-fill-paragraph
19035 'delete-indentation 'org-delete-indentation
19036 'transpose-words 'org-transpose-words)
19038 ;;;; All the other keys
19039 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
19040 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
19041 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
19042 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
19043 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
19044 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
19045 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
19046 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
19047 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
19048 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
19049 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
19050 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
19051 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
19052 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
19053 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
19054 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
19055 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
19056 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
19057 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
19058 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
19059 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
19060 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
19061 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
19062 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
19063 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
19064 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
19065 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
19066 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
19067 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
19068 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
19069 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
19070 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
19071 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
19072 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
19073 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
19074 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
19075 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
19076 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
19077 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
19078 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
19079 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
19080 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
19081 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
19082 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19083 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19084 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19085 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19086 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19087 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19088 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19089 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19090 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19091 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19092 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19093 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19094 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19095 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19096 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19097 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19098 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19099 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19100 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19101 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19102 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19103 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19104 (org-defkey org-mode-map (kbd "RET") #'org-return)
19105 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19106 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19107 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19108 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19109 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19110 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19111 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19112 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19113 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19114 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19115 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19116 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19117 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19118 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19119 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19120 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19121 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19122 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19123 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19124 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19125 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19126 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19127 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19129 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19130 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19131 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19133 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19134 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19135 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19136 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19137 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19138 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19139 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19140 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19141 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19142 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19143 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19144 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19145 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19146 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19147 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19148 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19149 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19150 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19151 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19152 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19153 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19154 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19155 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19156 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19157 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19158 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19159 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19160 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19162 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19164 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19166 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19167 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19169 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19172 ;;; Speed commands
19174 (defconst org-speed-commands-default
19176 ("Outline Navigation")
19177 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19178 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19179 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19180 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19181 ("F" . org-next-block)
19182 ("B" . org-previous-block)
19183 ("u" . (org-speed-move-safe 'outline-up-heading))
19184 ("j" . org-goto)
19185 ("g" . (org-refile t))
19186 ("Outline Visibility")
19187 ("c" . org-cycle)
19188 ("C" . org-shifttab)
19189 (" " . org-display-outline-path)
19190 ("s" . org-narrow-to-subtree)
19191 ("=" . org-columns)
19192 ("Outline Structure Editing")
19193 ("U" . org-metaup)
19194 ("D" . org-metadown)
19195 ("r" . org-metaright)
19196 ("l" . org-metaleft)
19197 ("R" . org-shiftmetaright)
19198 ("L" . org-shiftmetaleft)
19199 ("i" . (progn (forward-char 1) (call-interactively
19200 'org-insert-heading-respect-content)))
19201 ("^" . org-sort)
19202 ("w" . org-refile)
19203 ("a" . org-archive-subtree-default-with-confirmation)
19204 ("@" . org-mark-subtree)
19205 ("#" . org-toggle-comment)
19206 ("Clock Commands")
19207 ("I" . org-clock-in)
19208 ("O" . org-clock-out)
19209 ("Meta Data Editing")
19210 ("t" . org-todo)
19211 ("," . (org-priority))
19212 ("0" . (org-priority ?\ ))
19213 ("1" . (org-priority ?A))
19214 ("2" . (org-priority ?B))
19215 ("3" . (org-priority ?C))
19216 (":" . org-set-tags-command)
19217 ("e" . org-set-effort)
19218 ("E" . org-inc-effort)
19219 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19220 (org-entry-put (point) "APPT_WARNTIME" m)))
19221 ("Agenda Views etc")
19222 ("v" . org-agenda)
19223 ("/" . org-sparse-tree)
19224 ("Misc")
19225 ("o" . org-open-at-point)
19226 ("?" . org-speed-command-help)
19227 ("<" . (org-agenda-set-restriction-lock 'subtree))
19228 (">" . (org-agenda-remove-restriction-lock))
19230 "The default speed commands.")
19232 (defun org-print-speed-command (e)
19233 (if (> (length (car e)) 1)
19234 (progn
19235 (princ "\n")
19236 (princ (car e))
19237 (princ "\n")
19238 (princ (make-string (length (car e)) ?-))
19239 (princ "\n"))
19240 (princ (car e))
19241 (princ " ")
19242 (if (symbolp (cdr e))
19243 (princ (symbol-name (cdr e)))
19244 (prin1 (cdr e)))
19245 (princ "\n")))
19247 (defun org-speed-command-help ()
19248 "Show the available speed commands."
19249 (interactive)
19250 (if (not org-use-speed-commands)
19251 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19252 (with-output-to-temp-buffer "*Help*"
19253 (princ "User-defined Speed commands\n===========================\n")
19254 (mapc #'org-print-speed-command org-speed-commands-user)
19255 (princ "\n")
19256 (princ "Built-in Speed commands\n=======================\n")
19257 (mapc #'org-print-speed-command org-speed-commands-default))
19258 (with-current-buffer "*Help*"
19259 (setq truncate-lines t))))
19261 (defun org-speed-move-safe (cmd)
19262 "Execute CMD, but make sure that the cursor always ends up in a headline.
19263 If not, return to the original position and throw an error."
19264 (interactive)
19265 (let ((pos (point)))
19266 (call-interactively cmd)
19267 (unless (and (bolp) (org-at-heading-p))
19268 (goto-char pos)
19269 (error "Boundary reached while executing %s" cmd))))
19271 (defvar org-self-insert-command-undo-counter 0)
19273 (defvar org-table-auto-blank-field) ; defined in org-table.el
19274 (defvar org-speed-command nil)
19276 (defun org-speed-command-activate (keys)
19277 "Hook for activating single-letter speed commands.
19278 `org-speed-commands-default' specifies a minimal command set.
19279 Use `org-speed-commands-user' for further customization."
19280 (when (or (and (bolp) (looking-at org-outline-regexp))
19281 (and (functionp org-use-speed-commands)
19282 (funcall org-use-speed-commands)))
19283 (cdr (assoc keys (append org-speed-commands-user
19284 org-speed-commands-default)))))
19286 (defun org-babel-speed-command-activate (keys)
19287 "Hook for activating single-letter code block commands."
19288 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19289 (cdr (assoc keys org-babel-key-bindings))))
19291 (defcustom org-speed-command-hook
19292 '(org-speed-command-activate org-babel-speed-command-activate)
19293 "Hook for activating speed commands at strategic locations.
19294 Hook functions are called in sequence until a valid handler is
19295 found.
19297 Each hook takes a single argument, a user-pressed command key
19298 which is also a `self-insert-command' from the global map.
19300 Within the hook, examine the cursor position and the command key
19301 and return nil or a valid handler as appropriate. Handler could
19302 be one of an interactive command, a function, or a form.
19304 Set `org-use-speed-commands' to non-nil value to enable this
19305 hook. The default setting is `org-speed-command-activate'."
19306 :group 'org-structure
19307 :version "24.1"
19308 :type 'hook)
19310 (defun org-self-insert-command (N)
19311 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19312 If the cursor is in a table looking at whitespace, the whitespace is
19313 overwritten, and the table is not marked as requiring realignment."
19314 (interactive "p")
19315 (org-check-before-invisible-edit 'insert)
19316 (cond
19317 ((and org-use-speed-commands
19318 (let ((kv (this-command-keys-vector)))
19319 (setq org-speed-command
19320 (run-hook-with-args-until-success
19321 'org-speed-command-hook
19322 (make-string 1 (aref kv (1- (length kv))))))))
19323 (cond
19324 ((commandp org-speed-command)
19325 (setq this-command org-speed-command)
19326 (call-interactively org-speed-command))
19327 ((functionp org-speed-command)
19328 (funcall org-speed-command))
19329 ((and org-speed-command (listp org-speed-command))
19330 (eval org-speed-command))
19331 (t (let (org-use-speed-commands)
19332 (call-interactively 'org-self-insert-command)))))
19333 ((and
19334 (= N 1)
19335 (not (org-region-active-p))
19336 (org-at-table-p)
19337 (progn
19338 ;; Check if we blank the field, and if that triggers align.
19339 (and (featurep 'org-table)
19340 org-table-auto-blank-field
19341 (memq last-command
19342 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19343 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19344 ;; Got extra space, this field does not determine
19345 ;; column width.
19346 (let (org-table-may-need-update) (org-table-blank-field))
19347 ;; No extra space, this field may determine column
19348 ;; width.
19349 (org-table-blank-field)))
19351 (looking-at "[^|\n]* |"))
19352 ;; There is room for insertion without re-aligning the table.
19353 (self-insert-command N)
19354 (org-table-with-shrunk-field
19355 (save-excursion
19356 (skip-chars-forward "^|")
19357 ;; Do not delete last space, which is
19358 ;; `org-table-separator-space', but the regular space before
19359 ;; it.
19360 (delete-region (- (point) 2) (1- (point))))))
19362 (setq org-table-may-need-update t)
19363 (self-insert-command N)
19364 (org-fix-tags-on-the-fly)
19365 (when org-self-insert-cluster-for-undo
19366 (if (not (eq last-command 'org-self-insert-command))
19367 (setq org-self-insert-command-undo-counter 1)
19368 (if (>= org-self-insert-command-undo-counter 20)
19369 (setq org-self-insert-command-undo-counter 1)
19370 (and (> org-self-insert-command-undo-counter 0)
19371 buffer-undo-list (listp buffer-undo-list)
19372 (not (cadr buffer-undo-list)) ; remove nil entry
19373 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19374 (setq org-self-insert-command-undo-counter
19375 (1+ org-self-insert-command-undo-counter))))))))
19377 (defun org-check-before-invisible-edit (kind)
19378 "Check is editing if kind KIND would be dangerous with invisible text around.
19379 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19380 ;; First, try to get out of here as quickly as possible, to reduce overhead
19381 (when (and org-catch-invisible-edits
19382 (or (not (boundp 'visible-mode)) (not visible-mode))
19383 (or (get-char-property (point) 'invisible)
19384 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19385 ;; OK, we need to take a closer look. Do not consider
19386 ;; invisibility obtained through text properties (e.g., link
19387 ;; fontification), as it cannot be toggled.
19388 (let* ((invisible-at-point
19389 (pcase (get-char-property-and-overlay (point) 'invisible)
19390 (`(,_ . ,(and (pred overlayp) o)) o)))
19391 ;; Assume that point cannot land in the middle of an
19392 ;; overlay, or between two overlays.
19393 (invisible-before-point
19394 (and (not invisible-at-point)
19395 (not (bobp))
19396 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19397 (`(,_ . ,(and (pred overlayp) o)) o))))
19398 (border-and-ok-direction
19400 ;; Check if we are acting predictably before invisible
19401 ;; text.
19402 (and invisible-at-point
19403 (memq kind '(insert delete-backward)))
19404 ;; Check if we are acting predictably after invisible text
19405 ;; This works not well, and I have turned it off. It seems
19406 ;; better to always show and stop after invisible text.
19407 ;; (and (not invisible-at-point) invisible-before-point
19408 ;; (memq kind '(insert delete)))
19410 (when (or invisible-at-point invisible-before-point)
19411 (when (eq org-catch-invisible-edits 'error)
19412 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19413 (if (and org-custom-properties-overlays
19414 (y-or-n-p "Display invisible properties in this buffer? "))
19415 (org-toggle-custom-properties-visibility)
19416 ;; Make the area visible
19417 (save-excursion
19418 (when invisible-before-point
19419 (goto-char
19420 (previous-single-char-property-change (point) 'invisible)))
19421 ;; Remove whatever overlay is currently making yet-to-be
19422 ;; edited text invisible. Also remove nested invisibility
19423 ;; related overlays.
19424 (delete-overlay (or invisible-at-point invisible-before-point))
19425 (let ((origin (if invisible-at-point (point) (1- (point)))))
19426 (while (pcase (get-char-property-and-overlay origin 'invisible)
19427 (`(,_ . ,(and (pred overlayp) o))
19428 (delete-overlay o)
19429 t)))))
19430 (cond
19431 ((eq org-catch-invisible-edits 'show)
19432 ;; That's it, we do the edit after showing
19433 (message
19434 "Unfolding invisible region around point before editing")
19435 (sit-for 1))
19436 ((and (eq org-catch-invisible-edits 'smart)
19437 border-and-ok-direction)
19438 (message "Unfolding invisible region around point before editing"))
19440 ;; Don't do the edit, make the user repeat it in full visibility
19441 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19443 (defun org-fix-tags-on-the-fly ()
19444 "Align tags in headline at point.
19445 Unlike to `org-set-tags', it ignores region and sorting."
19446 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19447 (org-at-heading-p))
19448 (let ((org-ignore-region t)
19449 (org-tags-sort-function nil))
19450 (org-set-tags nil t))))
19452 (defun org-delete-backward-char (N)
19453 "Like `delete-backward-char', insert whitespace at field end in tables.
19454 When deleting backwards, in tables this function will insert whitespace in
19455 front of the next \"|\" separator, to keep the table aligned. The table will
19456 still be marked for re-alignment if the field did fill the entire column,
19457 because, in this case the deletion might narrow the column."
19458 (interactive "p")
19459 (save-match-data
19460 (org-check-before-invisible-edit 'delete-backward)
19461 (if (and (= N 1)
19462 (not overwrite-mode)
19463 (not (org-region-active-p))
19464 (not (eq (char-before) ?|))
19465 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19466 (looking-at-p ".*?|")
19467 (org-at-table-p))
19468 (progn (forward-char -1) (org-delete-char 1))
19469 (backward-delete-char N)
19470 (org-fix-tags-on-the-fly))))
19472 (defun org-delete-char (N)
19473 "Like `delete-char', but insert whitespace at field end in tables.
19474 When deleting characters, in tables this function will insert whitespace in
19475 front of the next \"|\" separator, to keep the table aligned. The table will
19476 still be marked for re-alignment if the field did fill the entire column,
19477 because, in this case the deletion might narrow the column."
19478 (interactive "p")
19479 (save-match-data
19480 (org-check-before-invisible-edit 'delete)
19481 (cond
19482 ((or (/= N 1)
19483 (eq (char-after) ?|)
19484 (save-excursion (skip-chars-backward " \t") (bolp))
19485 (not (org-at-table-p)))
19486 (delete-char N)
19487 (org-fix-tags-on-the-fly))
19488 ((looking-at ".\\(.*?\\)|")
19489 (let* ((update? org-table-may-need-update)
19490 (noalign (looking-at-p ".*? |")))
19491 (delete-char 1)
19492 (org-table-with-shrunk-field
19493 (save-excursion
19494 ;; Last space is `org-table-separator-space', so insert
19495 ;; a regular one before it instead.
19496 (goto-char (- (match-end 0) 2))
19497 (insert " ")))
19498 ;; If there were two spaces at the end, this field does not
19499 ;; determine the width of the column.
19500 (when noalign (setq org-table-may-need-update update?))))
19502 (delete-char N)))))
19504 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19505 (put 'org-self-insert-command 'delete-selection
19506 (lambda ()
19507 (not (run-hook-with-args-until-success
19508 'self-insert-uses-region-functions))))
19509 (put 'orgtbl-self-insert-command 'delete-selection
19510 (lambda ()
19511 (not (run-hook-with-args-until-success
19512 'self-insert-uses-region-functions))))
19513 (put 'org-delete-char 'delete-selection 'supersede)
19514 (put 'org-delete-backward-char 'delete-selection 'supersede)
19515 (put 'org-yank 'delete-selection 'yank)
19517 ;; Make `flyspell-mode' delay after some commands
19518 (put 'org-self-insert-command 'flyspell-delayed t)
19519 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19520 (put 'org-delete-char 'flyspell-delayed t)
19521 (put 'org-delete-backward-char 'flyspell-delayed t)
19523 ;; Make pabbrev-mode expand after Org mode commands
19524 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19525 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19527 (defun org-transpose-words ()
19528 "Transpose words for Org.
19529 This uses the `org-mode-transpose-word-syntax-table' syntax
19530 table, which interprets characters in `org-emphasis-alist' as
19531 word constituents."
19532 (interactive)
19533 (with-syntax-table org-mode-transpose-word-syntax-table
19534 (call-interactively 'transpose-words)))
19536 (defvar org-ctrl-c-ctrl-c-hook nil
19537 "Hook for functions attaching themselves to `C-c C-c'.
19539 This can be used to add additional functionality to the C-c C-c
19540 key which executes context-dependent commands. This hook is run
19541 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19542 run after the last test.
19544 Each function will be called with no arguments. The function
19545 must check if the context is appropriate for it to act. If yes,
19546 it should do its thing and then return a non-nil value. If the
19547 context is wrong, just do nothing and return nil.")
19549 (defvar org-ctrl-c-ctrl-c-final-hook nil
19550 "Hook for functions attaching themselves to `C-c C-c'.
19552 This can be used to add additional functionality to the C-c C-c
19553 key which executes context-dependent commands. This hook is run
19554 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19555 before the first test.
19557 Each function will be called with no arguments. The function
19558 must check if the context is appropriate for it to act. If yes,
19559 it should do its thing and then return a non-nil value. If the
19560 context is wrong, just do nothing and return nil.")
19562 (defvar org-tab-first-hook nil
19563 "Hook for functions to attach themselves to TAB.
19564 See `org-ctrl-c-ctrl-c-hook' for more information.
19565 This hook runs as the first action when TAB is pressed, even before
19566 `org-cycle' messes around with the `outline-regexp' to cater for
19567 inline tasks and plain list item folding.
19568 If any function in this hook returns t, any other actions that
19569 would have been caused by TAB (such as table field motion or visibility
19570 cycling) will not occur.")
19572 (defvar org-tab-after-check-for-table-hook nil
19573 "Hook for functions to attach themselves to TAB.
19574 See `org-ctrl-c-ctrl-c-hook' for more information.
19575 This hook runs after it has been established that the cursor is not in a
19576 table, but before checking if the cursor is in a headline or if global cycling
19577 should be done.
19578 If any function in this hook returns t, not other actions like visibility
19579 cycling will be done.")
19581 (defvar org-tab-after-check-for-cycling-hook nil
19582 "Hook for functions to attach themselves to TAB.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.
19584 This hook runs after it has been established that not table field motion and
19585 not visibility should be done because of current context. This is probably
19586 the place where a package like yasnippets can hook in.")
19588 (defvar org-tab-before-tab-emulation-hook nil
19589 "Hook for functions to attach themselves to TAB.
19590 See `org-ctrl-c-ctrl-c-hook' for more information.
19591 This hook runs after every other options for TAB have been exhausted, but
19592 before indentation and \t insertion takes place.")
19594 (defvar org-metaleft-hook nil
19595 "Hook for functions attaching themselves to `M-left'.
19596 See `org-ctrl-c-ctrl-c-hook' for more information.")
19597 (defvar org-metaright-hook nil
19598 "Hook for functions attaching themselves to `M-right'.
19599 See `org-ctrl-c-ctrl-c-hook' for more information.")
19600 (defvar org-metaup-hook nil
19601 "Hook for functions attaching themselves to `M-up'.
19602 See `org-ctrl-c-ctrl-c-hook' for more information.")
19603 (defvar org-metadown-hook nil
19604 "Hook for functions attaching themselves to `M-down'.
19605 See `org-ctrl-c-ctrl-c-hook' for more information.")
19606 (defvar org-shiftmetaleft-hook nil
19607 "Hook for functions attaching themselves to `M-S-left'.
19608 See `org-ctrl-c-ctrl-c-hook' for more information.")
19609 (defvar org-shiftmetaright-hook nil
19610 "Hook for functions attaching themselves to `M-S-right'.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.")
19612 (defvar org-shiftmetaup-hook nil
19613 "Hook for functions attaching themselves to `M-S-up'.
19614 See `org-ctrl-c-ctrl-c-hook' for more information.")
19615 (defvar org-shiftmetadown-hook nil
19616 "Hook for functions attaching themselves to `M-S-down'.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19618 (defvar org-metareturn-hook nil
19619 "Hook for functions attaching themselves to `M-RET'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-shiftup-hook nil
19622 "Hook for functions attaching themselves to `S-up'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-shiftup-final-hook nil
19625 "Hook for functions attaching themselves to `S-up'.
19626 This one runs after all other options except shift-select have been excluded.
19627 See `org-ctrl-c-ctrl-c-hook' for more information.")
19628 (defvar org-shiftdown-hook nil
19629 "Hook for functions attaching themselves to `S-down'.
19630 See `org-ctrl-c-ctrl-c-hook' for more information.")
19631 (defvar org-shiftdown-final-hook nil
19632 "Hook for functions attaching themselves to `S-down'.
19633 This one runs after all other options except shift-select have been excluded.
19634 See `org-ctrl-c-ctrl-c-hook' for more information.")
19635 (defvar org-shiftleft-hook nil
19636 "Hook for functions attaching themselves to `S-left'.
19637 See `org-ctrl-c-ctrl-c-hook' for more information.")
19638 (defvar org-shiftleft-final-hook nil
19639 "Hook for functions attaching themselves to `S-left'.
19640 This one runs after all other options except shift-select have been excluded.
19641 See `org-ctrl-c-ctrl-c-hook' for more information.")
19642 (defvar org-shiftright-hook nil
19643 "Hook for functions attaching themselves to `S-right'.
19644 See `org-ctrl-c-ctrl-c-hook' for more information.")
19645 (defvar org-shiftright-final-hook nil
19646 "Hook for functions attaching themselves to `S-right'.
19647 This one runs after all other options except shift-select have been excluded.
19648 See `org-ctrl-c-ctrl-c-hook' for more information.")
19650 (defun org-modifier-cursor-error ()
19651 "Throw an error, a modified cursor command was applied in wrong context."
19652 (user-error "This command is active in special context like tables, headlines or items"))
19654 (defun org-shiftselect-error ()
19655 "Throw an error because Shift-Cursor command was applied in wrong context."
19656 (if (and (boundp 'shift-select-mode) shift-select-mode)
19657 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19658 (user-error "This command works only in special context like headlines or timestamps")))
19660 (defun org-call-for-shift-select (cmd)
19661 (let ((this-command-keys-shift-translated t))
19662 (call-interactively cmd)))
19664 (defun org-shifttab (&optional arg)
19665 "Global visibility cycling or move to previous table field.
19666 Call `org-table-previous-field' within a table.
19667 When ARG is nil, cycle globally through visibility states.
19668 When ARG is a numeric prefix, show contents of this level."
19669 (interactive "P")
19670 (cond
19671 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19672 ((integerp arg)
19673 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19674 (message "Content view to level: %d" arg)
19675 (org-content (prefix-numeric-value arg2))
19676 (org-cycle-show-empty-lines t)
19677 (setq org-cycle-global-status 'overview)))
19678 (t (call-interactively 'org-global-cycle))))
19680 (defun org-shiftmetaleft ()
19681 "Promote subtree or delete table column.
19682 Calls `org-promote-subtree', `org-outdent-item-tree', or
19683 `org-table-delete-column', depending on context. See the
19684 individual commands for more information."
19685 (interactive)
19686 (cond
19687 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19688 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19689 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19690 ((if (not (org-region-active-p)) (org-at-item-p)
19691 (save-excursion (goto-char (region-beginning))
19692 (org-at-item-p)))
19693 (call-interactively 'org-outdent-item-tree))
19694 (t (org-modifier-cursor-error))))
19696 (defun org-shiftmetaright ()
19697 "Demote subtree or insert table column.
19698 Calls `org-demote-subtree', `org-indent-item-tree', or
19699 `org-table-insert-column', depending on context. See the
19700 individual commands for more information."
19701 (interactive)
19702 (cond
19703 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19704 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19705 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19706 ((if (not (org-region-active-p)) (org-at-item-p)
19707 (save-excursion (goto-char (region-beginning))
19708 (org-at-item-p)))
19709 (call-interactively 'org-indent-item-tree))
19710 (t (org-modifier-cursor-error))))
19712 (defun org-shiftmetaup (&optional _arg)
19713 "Drag the line at point up.
19714 In a table, kill the current row.
19715 On a clock timestamp, update the value of the timestamp like `S-<up>'
19716 but also adjust the previous clocked item in the clock history.
19717 Everywhere else, drag the line at point up."
19718 (interactive "P")
19719 (cond
19720 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19721 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19722 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19723 (call-interactively 'org-timestamp-up)))
19724 (t (call-interactively 'org-drag-line-backward))))
19726 (defun org-shiftmetadown (&optional _arg)
19727 "Drag the line at point down.
19728 In a table, insert an empty row at the current line.
19729 On a clock timestamp, update the value of the timestamp like `S-<down>'
19730 but also adjust the previous clocked item in the clock history.
19731 Everywhere else, drag the line at point down."
19732 (interactive "P")
19733 (cond
19734 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19735 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19736 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19737 (call-interactively 'org-timestamp-down)))
19738 (t (call-interactively 'org-drag-line-forward))))
19740 (defsubst org-hidden-tree-error ()
19741 (user-error
19742 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19744 (defun org-metaleft (&optional _arg)
19745 "Promote heading, list item at point or move table column left.
19747 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19748 depending on context. With no specific context, calls the Emacs
19749 default `backward-word'. See the individual commands for more
19750 information.
19752 This function runs the hook `org-metaleft-hook' as a first step,
19753 and returns at first non-nil value."
19754 (interactive "P")
19755 (cond
19756 ((run-hook-with-args-until-success 'org-metaleft-hook))
19757 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19758 ((org-with-limited-levels
19759 (or (org-at-heading-p)
19760 (and (org-region-active-p)
19761 (save-excursion
19762 (goto-char (region-beginning))
19763 (org-at-heading-p)))))
19764 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19765 (call-interactively 'org-do-promote))
19766 ;; At an inline task.
19767 ((org-at-heading-p)
19768 (call-interactively 'org-inlinetask-promote))
19769 ((or (org-at-item-p)
19770 (and (org-region-active-p)
19771 (save-excursion
19772 (goto-char (region-beginning))
19773 (org-at-item-p))))
19774 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19775 (call-interactively 'org-outdent-item))
19776 (t (call-interactively 'backward-word))))
19778 (defun org-metaright (&optional _arg)
19779 "Demote heading, list item at point or move table column right.
19781 In front of a drawer or a block keyword, indent it correctly.
19783 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19784 `org-indent-drawer' or `org-indent-block' depending on context.
19785 With no specific context, calls the Emacs default `forward-word'.
19786 See the individual commands for more information.
19788 This function runs the hook `org-metaright-hook' as a first step,
19789 and returns at first non-nil value."
19790 (interactive "P")
19791 (cond
19792 ((run-hook-with-args-until-success 'org-metaright-hook))
19793 ((org-at-table-p) (call-interactively 'org-table-move-column))
19794 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19795 ((org-at-block-p) (call-interactively 'org-indent-block))
19796 ((org-with-limited-levels
19797 (or (org-at-heading-p)
19798 (and (org-region-active-p)
19799 (save-excursion
19800 (goto-char (region-beginning))
19801 (org-at-heading-p)))))
19802 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19803 (call-interactively 'org-do-demote))
19804 ;; At an inline task.
19805 ((org-at-heading-p)
19806 (call-interactively 'org-inlinetask-demote))
19807 ((or (org-at-item-p)
19808 (and (org-region-active-p)
19809 (save-excursion
19810 (goto-char (region-beginning))
19811 (org-at-item-p))))
19812 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19813 (call-interactively 'org-indent-item))
19814 (t (call-interactively 'forward-word))))
19816 (defun org-check-for-hidden (what)
19817 "Check if there are hidden headlines/items in the current visual line.
19818 WHAT can be either `headlines' or `items'. If the current line is
19819 an outline or item heading and it has a folded subtree below it,
19820 this function returns t, nil otherwise."
19821 (let ((re (cond
19822 ((eq what 'headlines) org-outline-regexp-bol)
19823 ((eq what 'items) (org-item-beginning-re))
19824 (t (error "This should not happen"))))
19825 beg end)
19826 (save-excursion
19827 (catch 'exit
19828 (unless (org-region-active-p)
19829 (setq beg (point-at-bol))
19830 (beginning-of-line 2)
19831 (while (and (not (eobp)) ;; this is like `next-line'
19832 (get-char-property (1- (point)) 'invisible))
19833 (beginning-of-line 2))
19834 (setq end (point))
19835 (goto-char beg)
19836 (goto-char (point-at-eol))
19837 (setq end (max end (point)))
19838 (while (re-search-forward re end t)
19839 (when (get-char-property (match-beginning 0) 'invisible)
19840 (throw 'exit t))))
19841 nil))))
19843 (defun org-metaup (&optional _arg)
19844 "Move subtree up or move table row up.
19845 Calls `org-move-subtree-up' or `org-table-move-row' or
19846 `org-move-item-up', depending on context. See the individual commands
19847 for more information."
19848 (interactive "P")
19849 (cond
19850 ((run-hook-with-args-until-success 'org-metaup-hook))
19851 ((org-region-active-p)
19852 (let* ((a (min (region-beginning) (region-end)))
19853 (b (1- (max (region-beginning) (region-end))))
19854 (c (save-excursion (goto-char a)
19855 (move-beginning-of-line 0)))
19856 (d (save-excursion (goto-char a)
19857 (move-end-of-line 0) (point))))
19858 (transpose-regions a b c d)
19859 (goto-char c)))
19860 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19861 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19862 ((org-at-item-p) (call-interactively 'org-move-item-up))
19863 (t (org-drag-element-backward))))
19865 (defun org-metadown (&optional _arg)
19866 "Move subtree down or move table row down.
19867 Calls `org-move-subtree-down' or `org-table-move-row' or
19868 `org-move-item-down', depending on context. See the individual
19869 commands for more information."
19870 (interactive "P")
19871 (cond
19872 ((run-hook-with-args-until-success 'org-metadown-hook))
19873 ((org-region-active-p)
19874 (let* ((a (min (region-beginning) (region-end)))
19875 (b (max (region-beginning) (region-end)))
19876 (c (save-excursion (goto-char b)
19877 (move-beginning-of-line 1)))
19878 (d (save-excursion (goto-char b)
19879 (move-end-of-line 1) (1+ (point)))))
19880 (transpose-regions a b c d)
19881 (goto-char d)))
19882 ((org-at-table-p) (call-interactively 'org-table-move-row))
19883 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19884 ((org-at-item-p) (call-interactively 'org-move-item-down))
19885 (t (org-drag-element-forward))))
19887 (defun org-shiftup (&optional arg)
19888 "Increase item in timestamp or increase priority of current headline.
19889 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19890 depending on context. See the individual commands for more information."
19891 (interactive "P")
19892 (cond
19893 ((run-hook-with-args-until-success 'org-shiftup-hook))
19894 ((and org-support-shift-select (org-region-active-p))
19895 (org-call-for-shift-select 'previous-line))
19896 ((org-at-timestamp-p 'lax)
19897 (call-interactively (if org-edit-timestamp-down-means-later
19898 'org-timestamp-down 'org-timestamp-up)))
19899 ((and (not (eq org-support-shift-select 'always))
19900 org-enable-priority-commands
19901 (org-at-heading-p))
19902 (call-interactively 'org-priority-up))
19903 ((and (not org-support-shift-select) (org-at-item-p))
19904 (call-interactively 'org-previous-item))
19905 ((org-clocktable-try-shift 'up arg))
19906 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19907 (org-support-shift-select
19908 (org-call-for-shift-select 'previous-line))
19909 (t (org-shiftselect-error))))
19911 (defun org-shiftdown (&optional arg)
19912 "Decrease item in timestamp or decrease priority of current headline.
19913 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19914 depending on context. See the individual commands for more information."
19915 (interactive "P")
19916 (cond
19917 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19918 ((and org-support-shift-select (org-region-active-p))
19919 (org-call-for-shift-select 'next-line))
19920 ((org-at-timestamp-p 'lax)
19921 (call-interactively (if org-edit-timestamp-down-means-later
19922 'org-timestamp-up 'org-timestamp-down)))
19923 ((and (not (eq org-support-shift-select 'always))
19924 org-enable-priority-commands
19925 (org-at-heading-p))
19926 (call-interactively 'org-priority-down))
19927 ((and (not org-support-shift-select) (org-at-item-p))
19928 (call-interactively 'org-next-item))
19929 ((org-clocktable-try-shift 'down arg))
19930 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19931 (org-support-shift-select
19932 (org-call-for-shift-select 'next-line))
19933 (t (org-shiftselect-error))))
19935 (defun org-shiftright (&optional arg)
19936 "Cycle the thing at point or in the current line, depending on context.
19937 Depending on context, this does one of the following:
19939 - switch a timestamp at point one day into the future
19940 - on a headline, switch to the next TODO keyword.
19941 - on an item, switch entire list to the next bullet type
19942 - on a property line, switch to the next allowed value
19943 - on a clocktable definition line, move time block into the future"
19944 (interactive "P")
19945 (cond
19946 ((run-hook-with-args-until-success 'org-shiftright-hook))
19947 ((and org-support-shift-select (org-region-active-p))
19948 (org-call-for-shift-select 'forward-char))
19949 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19950 ((and (not (eq org-support-shift-select 'always))
19951 (org-at-heading-p))
19952 (let ((org-inhibit-logging
19953 (not org-treat-S-cursor-todo-selection-as-state-change))
19954 (org-inhibit-blocking
19955 (not org-treat-S-cursor-todo-selection-as-state-change)))
19956 (org-call-with-arg 'org-todo 'right)))
19957 ((or (and org-support-shift-select
19958 (not (eq org-support-shift-select 'always))
19959 (org-at-item-bullet-p))
19960 (and (not org-support-shift-select) (org-at-item-p)))
19961 (org-call-with-arg 'org-cycle-list-bullet nil))
19962 ((and (not (eq org-support-shift-select 'always))
19963 (org-at-property-p))
19964 (call-interactively 'org-property-next-allowed-value))
19965 ((org-clocktable-try-shift 'right arg))
19966 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19967 (org-support-shift-select
19968 (org-call-for-shift-select 'forward-char))
19969 (t (org-shiftselect-error))))
19971 (defun org-shiftleft (&optional arg)
19972 "Cycle the thing at point or in the current line, depending on context.
19973 Depending on context, this does one of the following:
19975 - switch a timestamp at point one day into the past
19976 - on a headline, switch to the previous TODO keyword.
19977 - on an item, switch entire list to the previous bullet type
19978 - on a property line, switch to the previous allowed value
19979 - on a clocktable definition line, move time block into the past"
19980 (interactive "P")
19981 (cond
19982 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19983 ((and org-support-shift-select (org-region-active-p))
19984 (org-call-for-shift-select 'backward-char))
19985 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19986 ((and (not (eq org-support-shift-select 'always))
19987 (org-at-heading-p))
19988 (let ((org-inhibit-logging
19989 (not org-treat-S-cursor-todo-selection-as-state-change))
19990 (org-inhibit-blocking
19991 (not org-treat-S-cursor-todo-selection-as-state-change)))
19992 (org-call-with-arg 'org-todo 'left)))
19993 ((or (and org-support-shift-select
19994 (not (eq org-support-shift-select 'always))
19995 (org-at-item-bullet-p))
19996 (and (not org-support-shift-select) (org-at-item-p)))
19997 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19998 ((and (not (eq org-support-shift-select 'always))
19999 (org-at-property-p))
20000 (call-interactively 'org-property-previous-allowed-value))
20001 ((org-clocktable-try-shift 'left arg))
20002 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20003 (org-support-shift-select
20004 (org-call-for-shift-select 'backward-char))
20005 (t (org-shiftselect-error))))
20007 (defun org-shiftcontrolright ()
20008 "Switch to next TODO set."
20009 (interactive)
20010 (cond
20011 ((and org-support-shift-select (org-region-active-p))
20012 (org-call-for-shift-select 'forward-word))
20013 ((and (not (eq org-support-shift-select 'always))
20014 (org-at-heading-p))
20015 (org-call-with-arg 'org-todo 'nextset))
20016 (org-support-shift-select
20017 (org-call-for-shift-select 'forward-word))
20018 (t (org-shiftselect-error))))
20020 (defun org-shiftcontrolleft ()
20021 "Switch to previous TODO set."
20022 (interactive)
20023 (cond
20024 ((and org-support-shift-select (org-region-active-p))
20025 (org-call-for-shift-select 'backward-word))
20026 ((and (not (eq org-support-shift-select 'always))
20027 (org-at-heading-p))
20028 (org-call-with-arg 'org-todo 'previousset))
20029 (org-support-shift-select
20030 (org-call-for-shift-select 'backward-word))
20031 (t (org-shiftselect-error))))
20033 (defun org-shiftcontrolup (&optional n)
20034 "Change timestamps synchronously up in CLOCK log lines.
20035 Optional argument N tells to change by that many units."
20036 (interactive "P")
20037 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20038 (let (org-support-shift-select)
20039 (org-clock-timestamps-up n))
20040 (user-error "Not at a clock log")))
20042 (defun org-shiftcontroldown (&optional n)
20043 "Change timestamps synchronously down in CLOCK log lines.
20044 Optional argument N tells to change by that many units."
20045 (interactive "P")
20046 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20047 (let (org-support-shift-select)
20048 (org-clock-timestamps-down n))
20049 (user-error "Not at a clock log")))
20051 (defun org-increase-number-at-point (&optional inc)
20052 "Increment the number at point.
20053 With an optional prefix numeric argument INC, increment using
20054 this numeric value."
20055 (interactive "p")
20056 (if (not (number-at-point))
20057 (user-error "Not on a number")
20058 (unless inc (setq inc 1))
20059 (let ((pos (point))
20060 (beg (skip-chars-backward "-+^/*0-9eE."))
20061 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20062 (setq nap (buffer-substring-no-properties
20063 (+ pos beg) (+ pos beg end)))
20064 (delete-region (+ pos beg) (+ pos beg end))
20065 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20066 (when (org-at-table-p)
20067 (org-table-align)
20068 (org-table-end-of-field 1))))
20070 (defun org-decrease-number-at-point (&optional inc)
20071 "Decrement the number at point.
20072 With an optional prefix numeric argument INC, decrement using
20073 this numeric value."
20074 (interactive "p")
20075 (org-increase-number-at-point (- (or inc 1))))
20077 (defun org-ctrl-c-ret ()
20078 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20079 (interactive)
20080 (cond
20081 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20082 (t (call-interactively 'org-insert-heading))))
20084 (defun org-find-visible ()
20085 (let ((s (point)))
20086 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20087 (get-char-property s 'invisible)))
20089 (defun org-find-invisible ()
20090 (let ((s (point)))
20091 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20092 (not (get-char-property s 'invisible))))
20095 (defun org-copy-visible (beg end)
20096 "Copy the visible parts of the region."
20097 (interactive "r")
20098 (let ((result ""))
20099 (while (/= beg end)
20100 (when (get-char-property beg 'invisible)
20101 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20102 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20103 (setq result (concat result (buffer-substring beg next)))
20104 (setq beg next)))
20105 (kill-new result)))
20107 (defun org-copy-special ()
20108 "Copy region in table or copy current subtree.
20109 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20110 context. See the individual commands for more information."
20111 (interactive)
20112 (call-interactively
20113 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20115 (defun org-cut-special ()
20116 "Cut region in table or cut current subtree.
20117 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20118 context. See the individual commands for more information."
20119 (interactive)
20120 (call-interactively
20121 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20123 (defun org-paste-special (arg)
20124 "Paste rectangular region into table, or past subtree relative to level.
20125 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20126 See the individual commands for more information."
20127 (interactive "P")
20128 (if (org-at-table-p)
20129 (org-table-paste-rectangle)
20130 (org-paste-subtree arg)))
20132 (defun org-edit-special (&optional arg)
20133 "Call a special editor for the element at point.
20134 When at a table, call the formula editor with `org-table-edit-formulas'.
20135 When in a source code block, call `org-edit-src-code'.
20136 When in a fixed-width region, call `org-edit-fixed-width-region'.
20137 When in an export block, call `org-edit-export-block'.
20138 When in a LaTeX environment, call `org-edit-latex-environment'.
20139 When at an #+INCLUDE keyword, visit the included file.
20140 When at a footnote reference, call `org-edit-footnote-reference'
20141 On a link, call `ffap' to visit the link at point.
20142 Otherwise, return a user error."
20143 (interactive "P")
20144 (let ((element (org-element-at-point)))
20145 (barf-if-buffer-read-only)
20146 (pcase (org-element-type element)
20147 (`src-block
20148 (if (not arg) (org-edit-src-code)
20149 (let* ((info (org-babel-get-src-block-info))
20150 (lang (nth 0 info))
20151 (params (nth 2 info))
20152 (session (cdr (assq :session params))))
20153 (if (not session) (org-edit-src-code)
20154 ;; At a src-block with a session and function called with
20155 ;; an ARG: switch to the buffer related to the inferior
20156 ;; process.
20157 (switch-to-buffer
20158 (funcall (intern (concat "org-babel-prep-session:" lang))
20159 session params))))))
20160 (`keyword
20161 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20162 (org-open-link-from-string
20163 (format "[[%s]]"
20164 (expand-file-name
20165 (let ((value (org-element-property :value element)))
20166 (cond ((org-file-url-p value)
20167 (user-error "The file is specified as a URL, cannot be edited"))
20168 ((not (org-string-nw-p value))
20169 (user-error "No file to edit"))
20170 ((string-match "\\`\"\\(.*?\\)\"" value)
20171 (match-string 1 value))
20172 ((string-match "\\`[^ \t\"]\\S-*" value)
20173 (match-string 0 value))
20174 (t (user-error "No valid file specified")))))))
20175 (user-error "No special environment to edit here")))
20176 (`table
20177 (if (eq (org-element-property :type element) 'table.el)
20178 (org-edit-table.el)
20179 (call-interactively 'org-table-edit-formulas)))
20180 ;; Only Org tables contain `table-row' type elements.
20181 (`table-row (call-interactively 'org-table-edit-formulas))
20182 (`example-block (org-edit-src-code))
20183 (`export-block (org-edit-export-block))
20184 (`fixed-width (org-edit-fixed-width-region))
20185 (`latex-environment (org-edit-latex-environment))
20187 ;; No notable element at point. Though, we may be at a link or
20188 ;; a footnote reference, which are objects. Thus, scan deeper.
20189 (let ((context (org-element-context element)))
20190 (pcase (org-element-type context)
20191 (`footnote-reference (org-edit-footnote-reference))
20192 (`inline-src-block (org-edit-inline-src-code))
20193 (`link (call-interactively #'ffap))
20194 (_ (user-error "No special environment to edit here"))))))))
20196 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20197 (defun org-ctrl-c-ctrl-c (&optional arg)
20198 "Set tags in headline, or update according to changed information at point.
20200 This command does many different things, depending on context:
20202 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20203 this is what we do.
20205 - If the cursor is on a statistics cookie, update it.
20207 - If the cursor is in a headline, prompt for tags and insert them
20208 into the current line, aligned to `org-tags-column'. When called
20209 with prefix arg, realign all tags in the current buffer.
20211 - If the cursor is in one of the special #+KEYWORD lines, this
20212 triggers scanning the buffer for these lines and updating the
20213 information.
20215 - If the cursor is inside a table, realign the table. This command
20216 works even if the automatic table editor has been turned off.
20218 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20219 the entire table.
20221 - If the cursor is at a footnote reference or definition, jump to
20222 the corresponding definition or references, respectively.
20224 - If the cursor is a the beginning of a dynamic block, update it.
20226 - If the current buffer is a capture buffer, close note and file it.
20228 - If the cursor is on a <<<target>>>, update radio targets and
20229 corresponding links in this buffer.
20231 - If the cursor is on a numbered item in a plain list, renumber the
20232 ordered list.
20234 - If the cursor is on a checkbox, toggle it.
20236 - If the cursor is on a code block, evaluate it. The variable
20237 `org-confirm-babel-evaluate' can be used to control prompting
20238 before code block evaluation, by default every code block
20239 evaluation requires confirmation. Code block evaluation can be
20240 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20241 (interactive "P")
20242 (cond
20243 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20244 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20245 (org-remove-occur-highlights)
20246 (message "Temporary highlights/overlays removed from current buffer"))
20247 ((and (local-variable-p 'org-finish-function)
20248 (fboundp org-finish-function))
20249 (funcall org-finish-function))
20250 ((org-babel-hash-at-point))
20251 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20253 (let* ((context
20254 (org-element-lineage
20255 (org-element-context)
20256 ;; Limit to supported contexts.
20257 '(babel-call clock dynamic-block footnote-definition
20258 footnote-reference inline-babel-call inline-src-block
20259 inlinetask item keyword node-property paragraph
20260 plain-list planning property-drawer radio-target
20261 src-block statistics-cookie table table-cell table-row
20262 timestamp)
20264 (type (org-element-type context)))
20265 ;; For convenience: at the first line of a paragraph on the same
20266 ;; line as an item, apply function on that item instead.
20267 (when (eq type 'paragraph)
20268 (let ((parent (org-element-property :parent context)))
20269 (when (and (eq (org-element-type parent) 'item)
20270 (= (line-beginning-position)
20271 (org-element-property :begin parent)))
20272 (setq context parent)
20273 (setq type 'item))))
20274 ;; Act according to type of element or object at point.
20276 ;; Do nothing on a blank line, except if it is contained in
20277 ;; a src block. Hence, we first check if point is in such
20278 ;; a block and then if it is at a blank line.
20279 (pcase type
20280 ((or `inline-src-block `src-block)
20281 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20282 (org-babel-eval-wipe-error-buffer)
20283 (org-babel-execute-src-block
20284 current-prefix-arg (org-babel-get-src-block-info nil context))))
20285 ((guard (org-match-line "[ \t]*$"))
20286 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20287 (user-error
20288 (substitute-command-keys
20289 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20290 ((or `babel-call `inline-babel-call)
20291 (let ((info (org-babel-lob-get-info context)))
20292 (when info (org-babel-execute-src-block nil info))))
20293 (`clock (org-clock-update-time-maybe))
20294 (`dynamic-block
20295 (save-excursion
20296 (goto-char (org-element-property :post-affiliated context))
20297 (org-update-dblock)))
20298 (`footnote-definition
20299 (goto-char (org-element-property :post-affiliated context))
20300 (call-interactively 'org-footnote-action))
20301 (`footnote-reference (call-interactively #'org-footnote-action))
20302 ((or `headline `inlinetask)
20303 (save-excursion (goto-char (org-element-property :begin context))
20304 (call-interactively #'org-set-tags)))
20305 (`item
20306 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20307 ;; unconditionally, whereas `C-u' will toggle its presence.
20308 ;; Without a universal argument, if the item has a checkbox,
20309 ;; toggle it. Otherwise repair the list.
20310 (let* ((box (org-element-property :checkbox context))
20311 (struct (org-element-property :structure context))
20312 (old-struct (copy-tree struct))
20313 (parents (org-list-parents-alist struct))
20314 (prevs (org-list-prevs-alist struct))
20315 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20316 (org-list-set-checkbox
20317 (org-element-property :begin context) struct
20318 (cond ((equal arg '(16)) "[-]")
20319 ((and (not box) (equal arg '(4))) "[ ]")
20320 ((or (not box) (equal arg '(4))) nil)
20321 ((eq box 'on) "[ ]")
20322 (t "[X]")))
20323 ;; Mimic `org-list-write-struct' but with grabbing a return
20324 ;; value from `org-list-struct-fix-box'.
20325 (org-list-struct-fix-ind struct parents 2)
20326 (org-list-struct-fix-item-end struct)
20327 (org-list-struct-fix-bul struct prevs)
20328 (org-list-struct-fix-ind struct parents)
20329 (let ((block-item
20330 (org-list-struct-fix-box struct parents prevs orderedp)))
20331 (if (and box (equal struct old-struct))
20332 (if (equal arg '(16))
20333 (message "Checkboxes already reset")
20334 (user-error "Cannot toggle this checkbox: %s"
20335 (if (eq box 'on)
20336 "all subitems checked"
20337 "unchecked subitems")))
20338 (org-list-struct-apply-struct struct old-struct)
20339 (org-update-checkbox-count-maybe))
20340 (when block-item
20341 (message "Checkboxes were removed due to empty box at line %d"
20342 (org-current-line block-item))))))
20343 (`keyword
20344 (let ((org-inhibit-startup-visibility-stuff t)
20345 (org-startup-align-all-tables nil))
20346 (when (boundp 'org-table-coordinate-overlays)
20347 (mapc #'delete-overlay org-table-coordinate-overlays)
20348 (setq org-table-coordinate-overlays nil))
20349 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20350 (message "Local setup has been refreshed"))
20351 (`plain-list
20352 ;; At a plain list, with a double C-u argument, set
20353 ;; checkboxes of each item to "[-]", whereas a single one
20354 ;; will toggle their presence according to the state of the
20355 ;; first item in the list. Without an argument, repair the
20356 ;; list.
20357 (let* ((begin (org-element-property :contents-begin context))
20358 (struct (org-element-property :structure context))
20359 (old-struct (copy-tree struct))
20360 (first-box (save-excursion
20361 (goto-char begin)
20362 (looking-at org-list-full-item-re)
20363 (match-string-no-properties 3)))
20364 (new-box (cond ((equal arg '(16)) "[-]")
20365 ((equal arg '(4)) (unless first-box "[ ]"))
20366 ((equal first-box "[X]") "[ ]")
20367 (t "[X]"))))
20368 (cond
20369 (arg
20370 (dolist (pos
20371 (org-list-get-all-items
20372 begin struct (org-list-prevs-alist struct)))
20373 (org-list-set-checkbox pos struct new-box)))
20374 ((and first-box (eq (point) begin))
20375 ;; For convenience, when point is at bol on the first
20376 ;; item of the list and no argument is provided, simply
20377 ;; toggle checkbox of that item, if any.
20378 (org-list-set-checkbox begin struct new-box)))
20379 (org-list-write-struct
20380 struct (org-list-parents-alist struct) old-struct)
20381 (org-update-checkbox-count-maybe)))
20382 ((or `property-drawer `node-property)
20383 (call-interactively #'org-property-action))
20384 (`radio-target
20385 (call-interactively #'org-update-radio-target-regexp))
20386 (`statistics-cookie
20387 (call-interactively #'org-update-statistics-cookies))
20388 ((or `table `table-cell `table-row)
20389 ;; At a table, recalculate every field and align it. Also
20390 ;; send the table if necessary. If the table has
20391 ;; a `table.el' type, just give up. At a table row or cell,
20392 ;; maybe recalculate line but always align table.
20393 (if (eq (org-element-property :type context) 'table.el)
20394 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20395 Use `\\[org-edit-special]' to edit table.el tables"))
20396 (if (or (eq type 'table)
20397 ;; Check if point is at a TBLFM line.
20398 (and (eq type 'table-row)
20399 (= (point) (org-element-property :end context))))
20400 (save-excursion
20401 (if (org-at-TBLFM-p)
20402 (progn (require 'org-table)
20403 (org-table-calc-current-TBLFM))
20404 (goto-char (org-element-property :contents-begin context))
20405 (org-call-with-arg 'org-table-recalculate (or arg t))
20406 (orgtbl-send-table 'maybe)))
20407 (org-table-maybe-eval-formula)
20408 (cond (arg (call-interactively #'org-table-recalculate))
20409 ((org-table-maybe-recalculate-line))
20410 (t (org-table-align))))))
20411 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20412 (org-timestamp-change 0 'day))
20413 ((and `nil (guard (org-at-heading-p)))
20414 ;; When point is on an unsupported object type, we can miss
20415 ;; the fact that it also is at a heading. Handle it here.
20416 (call-interactively #'org-set-tags))
20417 ((guard
20418 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20420 (user-error
20421 (substitute-command-keys
20422 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20424 (defun org-mode-restart ()
20425 (interactive)
20426 (let ((indent-status (bound-and-true-p org-indent-mode)))
20427 (funcall major-mode)
20428 (hack-local-variables)
20429 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20430 (org-indent-mode -1))
20431 (org-reset-file-cache))
20432 (message "%s restarted" major-mode))
20434 (defun org-kill-note-or-show-branches ()
20435 "Abort storing current note, or call `outline-show-branches'."
20436 (interactive)
20437 (if (not org-finish-function)
20438 (save-excursion
20439 (save-restriction
20440 (org-narrow-to-subtree)
20441 (org-flag-subtree t)
20442 (call-interactively 'outline-show-branches)
20443 (org-hide-archived-subtrees (point-min) (point-max))))
20444 (let ((org-note-abort t))
20445 (funcall org-finish-function))))
20447 (defun org-delete-indentation (&optional arg)
20448 "Join current line to previous and fix whitespace at join.
20450 If previous line is a headline add to headline title. Otherwise
20451 the function calls `delete-indentation'.
20453 With a non-nil optional argument, join it to the following one."
20454 (interactive "*P")
20455 (if (save-excursion
20456 (beginning-of-line (if arg 1 0))
20457 (let ((case-fold-search nil))
20458 (looking-at org-complex-heading-regexp)))
20459 ;; At headline.
20460 (let ((tags-column (when (match-beginning 5)
20461 (save-excursion (goto-char (match-beginning 5))
20462 (current-column))))
20463 (string (concat " " (progn (when arg (forward-line 1))
20464 (org-trim (delete-and-extract-region
20465 (line-beginning-position)
20466 (line-end-position)))))))
20467 (unless (bobp) (delete-region (point) (1- (point))))
20468 (goto-char (or (match-end 4)
20469 (match-beginning 5)
20470 (match-end 0)))
20471 (skip-chars-backward " \t")
20472 (save-excursion (insert string))
20473 ;; Adjust alignment of tags.
20474 (cond
20475 ((not tags-column)) ;no tags
20476 (org-auto-align-tags (org-set-tags nil t))
20477 (t (org--align-tags-here tags-column)))) ;preserve tags column
20478 (delete-indentation arg)))
20480 (defun org-open-line (n)
20481 "Insert a new row in tables, call `open-line' elsewhere.
20482 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20483 As a special case, when a document starts with a table, allow to
20484 call `open-line' on the very first character."
20485 (interactive "*p")
20486 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20487 (org-table-insert-row)
20488 (open-line n)))
20490 (defun org-return (&optional indent)
20491 "Goto next table row or insert a newline.
20493 Calls `org-table-next-row' or `newline', depending on context.
20495 When optional INDENT argument is non-nil, call
20496 `newline-and-indent' instead of `newline'.
20498 When `org-return-follows-link' is non-nil and point is on
20499 a timestamp or a link, call `org-open-at-point'. However, it
20500 will not happen if point is in a table or on a \"dead\"
20501 object (e.g., within a comment). In these case, you need to use
20502 `org-open-at-point' directly."
20503 (interactive)
20504 (let ((context (if org-return-follows-link (org-element-context)
20505 (org-element-at-point))))
20506 (cond
20507 ;; In a table, call `org-table-next-row'. However, before first
20508 ;; column or after last one, split the table.
20509 ((or (and (eq (org-element-type context) 'table)
20510 (>= (point) (org-element-property :contents-begin context))
20511 (< (point) (org-element-property :contents-end context)))
20512 (org-element-lineage context '(table-row table-cell) t))
20513 (if (or (looking-at-p "[ \t]*$")
20514 (save-excursion (skip-chars-backward " \t") (bolp)))
20515 (insert "\n")
20516 (org-table-justify-field-maybe)
20517 (call-interactively #'org-table-next-row)))
20518 ;; On a link or a timestamp, call `org-open-at-point' if
20519 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20520 ;; locations, e.g., in a comment, as `org-open-at-point'.
20521 ((and org-return-follows-link
20522 (or (and (eq 'link (org-element-type context))
20523 ;; Ensure point is not on the white spaces after
20524 ;; the link.
20525 (let ((origin (point)))
20526 (org-with-point-at (org-element-property :end context)
20527 (skip-chars-backward " \t")
20528 (> (point) origin))))
20529 (org-in-regexp org-ts-regexp-both nil t)
20530 (org-in-regexp org-tsr-regexp-both nil t)
20531 (org-in-regexp org-any-link-re nil t)))
20532 (call-interactively #'org-open-at-point))
20533 ;; Insert newline in heading, but preserve tags.
20534 ((and (not (bolp))
20535 (save-excursion (beginning-of-line)
20536 (let ((case-fold-search nil))
20537 (looking-at org-complex-heading-regexp))))
20538 ;; At headline. Split line. However, if point is on keyword,
20539 ;; priority cookie or tags, do not break any of them: add
20540 ;; a newline after the headline instead.
20541 (let ((tags-column (and (match-beginning 5)
20542 (save-excursion (goto-char (match-beginning 5))
20543 (current-column))))
20544 (string
20545 (when (and (match-end 4) (org-point-in-group (point) 4))
20546 (delete-and-extract-region (point) (match-end 4)))))
20547 ;; Adjust tag alignment.
20548 (cond
20549 ((not (and tags-column string)))
20550 (org-auto-align-tags (org-set-tags nil t))
20551 (t (org--align-tags-here tags-column))) ;preserve tags column
20552 (end-of-line)
20553 (org-show-entry)
20554 (if indent (newline-and-indent) (newline))
20555 (when string (save-excursion (insert (org-trim string))))))
20556 ;; In a list, make sure indenting keeps trailing text within.
20557 ((and indent
20558 (not (eolp))
20559 (org-element-lineage context '(item)))
20560 (let ((trailing-data
20561 (delete-and-extract-region (point) (line-end-position))))
20562 (newline-and-indent)
20563 (save-excursion (insert trailing-data))))
20565 ;; Do not auto-fill when point is in an Org property drawer.
20566 (let ((auto-fill-function (and (not (org-at-property-p))
20567 auto-fill-function)))
20568 (if indent
20569 (newline-and-indent)
20570 (newline)))))))
20572 (defun org-return-indent ()
20573 "Goto next table row or insert a newline and indent.
20574 Calls `org-table-next-row' or `newline-and-indent', depending on
20575 context. See the individual commands for more information."
20576 (interactive)
20577 (org-return t))
20579 (defun org-ctrl-c-tab (&optional _arg)
20580 "Toggle columns width in a table, or show children.
20581 Call `org-table-toggle-column-width' if point is in a table.
20582 Otherwise, call `org-show-children'."
20583 (interactive "p")
20584 (call-interactively
20585 (if (org-at-table-p) #'org-table-toggle-column-width
20586 #'org-show-children)))
20588 (defun org-ctrl-c-star ()
20589 "Compute table, or change heading status of lines.
20590 Calls `org-table-recalculate' or `org-toggle-heading',
20591 depending on context."
20592 (interactive)
20593 (cond
20594 ((org-at-table-p)
20595 (call-interactively 'org-table-recalculate))
20597 ;; Convert all lines in region to list items
20598 (call-interactively 'org-toggle-heading))))
20600 (defun org-ctrl-c-minus ()
20601 "Insert separator line in table or modify bullet status of line.
20602 Also turns a plain line or a region of lines into list items.
20603 Calls `org-table-insert-hline', `org-toggle-item', or
20604 `org-cycle-list-bullet', depending on context."
20605 (interactive)
20606 (cond
20607 ((org-at-table-p)
20608 (call-interactively 'org-table-insert-hline))
20609 ((org-region-active-p)
20610 (call-interactively 'org-toggle-item))
20611 ((org-in-item-p)
20612 (call-interactively 'org-cycle-list-bullet))
20614 (call-interactively 'org-toggle-item))))
20616 (defun org-toggle-heading (&optional nstars)
20617 "Convert headings to normal text, or items or text to headings.
20618 If there is no active region, only convert the current line.
20620 With a `\\[universal-argument]' prefix, convert the whole list at
20621 point into heading.
20623 In a region:
20625 - If the first non blank line is a headline, remove the stars
20626 from all headlines in the region.
20628 - If it is a normal line, turn each and every normal line (i.e.,
20629 not an heading or an item) in the region into headings. If you
20630 want to convert only the first line of this region, use one
20631 universal prefix argument.
20633 - If it is a plain list item, turn all plain list items into headings.
20635 When converting a line into a heading, the number of stars is chosen
20636 such that the lines become children of the current entry. However,
20637 when a numeric prefix argument is given, its value determines the
20638 number of stars to add."
20639 (interactive "P")
20640 (let ((skip-blanks
20641 (function
20642 ;; Return beginning of first non-blank line, starting from
20643 ;; line at POS.
20644 (lambda (pos)
20645 (save-excursion
20646 (goto-char pos)
20647 (while (org-at-comment-p) (forward-line))
20648 (skip-chars-forward " \r\t\n")
20649 (point-at-bol)))))
20650 beg end toggled)
20651 ;; Determine boundaries of changes. If a universal prefix has
20652 ;; been given, put the list in a region. If region ends at a bol,
20653 ;; do not consider the last line to be in the region.
20655 (when (and current-prefix-arg (org-at-item-p))
20656 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20657 (org-mark-element))
20659 (if (org-region-active-p)
20660 (setq beg (funcall skip-blanks (region-beginning))
20661 end (copy-marker (save-excursion
20662 (goto-char (region-end))
20663 (if (bolp) (point) (point-at-eol)))))
20664 (setq beg (funcall skip-blanks (point-at-bol))
20665 end (copy-marker (point-at-eol))))
20666 ;; Ensure inline tasks don't count as headings.
20667 (org-with-limited-levels
20668 (save-excursion
20669 (goto-char beg)
20670 (cond
20671 ;; Case 1. Started at an heading: de-star headings.
20672 ((org-at-heading-p)
20673 (while (< (point) end)
20674 (when (org-at-heading-p t)
20675 (looking-at org-outline-regexp) (replace-match "")
20676 (setq toggled t))
20677 (forward-line)))
20678 ;; Case 2. Started at an item: change items into headlines.
20679 ;; One star will be added by `org-list-to-subtree'.
20680 ((org-at-item-p)
20681 (while (< (point) end)
20682 (when (org-at-item-p)
20683 ;; Pay attention to cases when region ends before list.
20684 (let* ((struct (org-list-struct))
20685 (list-end
20686 (min (org-list-get-bottom-point struct) (1+ end))))
20687 (save-restriction
20688 (narrow-to-region (point) list-end)
20689 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20690 (setq toggled t))
20691 (forward-line)))
20692 ;; Case 3. Started at normal text: make every line an heading,
20693 ;; skipping headlines and items.
20694 (t (let* ((stars
20695 (make-string
20696 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20697 (add-stars
20698 (cond (nstars "") ; stars from prefix only
20699 ((equal stars "") "*") ; before first heading
20700 (org-odd-levels-only "**") ; inside heading, odd
20701 (t "*"))) ; inside heading, oddeven
20702 (rpl (concat stars add-stars " "))
20703 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20704 (while (< (point) (if (equal nstars '(4)) lend end))
20705 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20706 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20707 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20708 (forward-line)))))))
20709 (unless toggled (message "Cannot toggle heading from here"))))
20711 (defun org-meta-return (&optional arg)
20712 "Insert a new heading or wrap a region in a table.
20713 Calls `org-insert-heading', `org-insert-item' or
20714 `org-table-wrap-region', depending on context. When called with
20715 an argument, unconditionally call `org-insert-heading'."
20716 (interactive "P")
20717 (org-check-before-invisible-edit 'insert)
20718 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20719 (call-interactively (cond (arg #'org-insert-heading)
20720 ((org-at-table-p) #'org-table-wrap-region)
20721 ((org-in-item-p) #'org-insert-item)
20722 (t #'org-insert-heading)))))
20724 ;;; Menu entries
20726 (defsubst org-in-subtree-not-table-p ()
20727 "Are we in a subtree and not in a table?"
20728 (and (not (org-before-first-heading-p))
20729 (not (org-at-table-p))))
20731 ;; Define the Org mode menus
20732 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20733 '("Tbl"
20734 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20735 ["Next Field" org-cycle (org-at-table-p)]
20736 ["Previous Field" org-shifttab (org-at-table-p)]
20737 ["Next Row" org-return (org-at-table-p)]
20738 "--"
20739 ["Blank Field" org-table-blank-field (org-at-table-p)]
20740 ["Edit Field" org-table-edit-field (org-at-table-p)]
20741 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20742 "--"
20743 ("Column"
20744 ["Move Column Left" org-metaleft (org-at-table-p)]
20745 ["Move Column Right" org-metaright (org-at-table-p)]
20746 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20747 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20748 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20749 ("Row"
20750 ["Move Row Up" org-metaup (org-at-table-p)]
20751 ["Move Row Down" org-metadown (org-at-table-p)]
20752 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20753 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20754 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20755 "--"
20756 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20757 ("Rectangle"
20758 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20759 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20760 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20761 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20762 "--"
20763 ("Calculate"
20764 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20765 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20766 ["Edit Formulas" org-edit-special (org-at-table-p)]
20767 "--"
20768 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20769 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20770 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20771 "--"
20772 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20773 "--"
20774 ["Sum Column/Rectangle" org-table-sum
20775 (or (org-at-table-p) (org-region-active-p))]
20776 ["Which Column?" org-table-current-column (org-at-table-p)])
20777 ["Debug Formulas"
20778 org-table-toggle-formula-debugger
20779 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20780 ["Show Col/Row Numbers"
20781 org-table-toggle-coordinate-overlays
20782 :style toggle
20783 :selected (bound-and-true-p org-table-overlay-coordinates)]
20784 "--"
20785 ["Create" org-table-create (not (org-at-table-p))]
20786 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20787 ["Import from File" org-table-import (not (org-at-table-p))]
20788 ["Export to File" org-table-export (org-at-table-p)]
20789 "--"
20790 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20791 "--"
20792 ("Plot"
20793 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20794 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20796 (easy-menu-define org-org-menu org-mode-map "Org menu"
20797 '("Org"
20798 ("Show/Hide"
20799 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20800 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20801 ["Sparse Tree..." org-sparse-tree t]
20802 ["Reveal Context" org-reveal t]
20803 ["Show All" org-show-all t]
20804 "--"
20805 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20806 "--"
20807 ["New Heading" org-insert-heading t]
20808 ("Navigate Headings"
20809 ["Up" outline-up-heading t]
20810 ["Next" outline-next-visible-heading t]
20811 ["Previous" outline-previous-visible-heading t]
20812 ["Next Same Level" outline-forward-same-level t]
20813 ["Previous Same Level" outline-backward-same-level t]
20814 "--"
20815 ["Jump" org-goto t])
20816 ("Edit Structure"
20817 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20818 "--"
20819 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20820 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20821 "--"
20822 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20823 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20824 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20825 "--"
20826 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20827 "--"
20828 ["Copy visible text" org-copy-visible t]
20829 "--"
20830 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20831 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20832 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20833 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20834 "--"
20835 ["Sort Region/Children" org-sort t]
20836 "--"
20837 ["Convert to odd levels" org-convert-to-odd-levels t]
20838 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20839 ("Editing"
20840 ["Emphasis..." org-emphasize t]
20841 ["Edit Source Example" org-edit-special t]
20842 "--"
20843 ["Footnote new/jump" org-footnote-action t]
20844 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20845 ("Archive"
20846 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20847 "--"
20848 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20849 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20850 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20852 "--"
20853 ("Hyperlinks"
20854 ["Store Link (Global)" org-store-link t]
20855 ["Find existing link to here" org-occur-link-in-agenda-files t]
20856 ["Insert Link" org-insert-link t]
20857 ["Follow Link" org-open-at-point t]
20858 "--"
20859 ["Next link" org-next-link t]
20860 ["Previous link" org-previous-link t]
20861 "--"
20862 ["Descriptive Links"
20863 org-toggle-link-display
20864 :style radio
20865 :selected org-descriptive-links
20867 ["Literal Links"
20868 org-toggle-link-display
20869 :style radio
20870 :selected (not org-descriptive-links)])
20871 "--"
20872 ("TODO Lists"
20873 ["TODO/DONE/-" org-todo t]
20874 ("Select keyword"
20875 ["Next keyword" org-shiftright (org-at-heading-p)]
20876 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20877 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20878 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20879 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20880 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20881 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20882 "--"
20883 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20884 :selected org-enforce-todo-dependencies :style toggle :active t]
20885 "Settings for tree at point"
20886 ["Do Children sequentially" org-toggle-ordered-property :style radio
20887 :selected (org-entry-get nil "ORDERED")
20888 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20889 ["Do Children parallel" org-toggle-ordered-property :style radio
20890 :selected (not (org-entry-get nil "ORDERED"))
20891 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20892 "--"
20893 ["Set Priority" org-priority t]
20894 ["Priority Up" org-shiftup t]
20895 ["Priority Down" org-shiftdown t]
20896 "--"
20897 ["Get news from all feeds" org-feed-update-all t]
20898 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20899 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20900 ("TAGS and Properties"
20901 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20902 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20903 "--"
20904 ["Set property" org-set-property (not (org-before-first-heading-p))]
20905 ["Column view of properties" org-columns t]
20906 ["Insert Column View DBlock" org-columns-insert-dblock t])
20907 ("Dates and Scheduling"
20908 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20909 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20910 ("Change Date"
20911 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20912 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20913 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20914 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20915 ["Compute Time Range" org-evaluate-time-range t]
20916 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20917 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20918 "--"
20919 ["Custom time format" org-toggle-time-stamp-overlays
20920 :style radio :selected org-display-custom-times]
20921 "--"
20922 ["Goto Calendar" org-goto-calendar t]
20923 ["Date from Calendar" org-date-from-calendar t]
20924 "--"
20925 ["Start/Restart Timer" org-timer-start t]
20926 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20927 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20928 ["Insert Timer String" org-timer t]
20929 ["Insert Timer Item" org-timer-item t])
20930 ("Logging work"
20931 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20932 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20933 ["Clock out" org-clock-out t]
20934 ["Clock cancel" org-clock-cancel t]
20935 "--"
20936 ["Mark as default task" org-clock-mark-default-task t]
20937 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20938 ["Goto running clock" org-clock-goto t]
20939 "--"
20940 ["Display times" org-clock-display t]
20941 ["Create clock table" org-clock-report t]
20942 "--"
20943 ["Record DONE time"
20944 (progn (setq org-log-done (not org-log-done))
20945 (message "Switching to %s will %s record a timestamp"
20946 (car org-done-keywords)
20947 (if org-log-done "automatically" "not")))
20948 :style toggle :selected org-log-done])
20949 "--"
20950 ["Agenda Command..." org-agenda t]
20951 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20952 ("File List for Agenda")
20953 ("Special views current file"
20954 ["TODO Tree" org-show-todo-tree t]
20955 ["Check Deadlines" org-check-deadlines t]
20956 ["Tags/Property tree" org-match-sparse-tree t])
20957 "--"
20958 ["Export/Publish..." org-export-dispatch t]
20959 ("LaTeX"
20960 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20961 :style toggle :selected org-cdlatex-mode]
20962 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20963 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20964 ["Modify math symbol" org-cdlatex-math-modify
20965 (org-inside-LaTeX-fragment-p)]
20966 ["Insert citation" org-reftex-citation t])
20967 "--"
20968 ("MobileOrg"
20969 ["Push Files and Views" org-mobile-push t]
20970 ["Get Captured and Flagged" org-mobile-pull t]
20971 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20972 "--"
20973 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20974 "--"
20975 ("Documentation"
20976 ["Show Version" org-version t]
20977 ["Info Documentation" org-info t])
20978 ("Customize"
20979 ["Browse Org Group" org-customize t]
20980 "--"
20981 ["Expand This Menu" org-create-customize-menu
20982 (fboundp 'customize-menu-create)])
20983 ["Send bug report" org-submit-bug-report t]
20984 "--"
20985 ("Refresh/Reload"
20986 ["Refresh setup current buffer" org-mode-restart t]
20987 ["Reload Org (after update)" org-reload t]
20988 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20991 (defun org-info (&optional node)
20992 "Read documentation for Org in the info system.
20993 With optional NODE, go directly to that node."
20994 (interactive)
20995 (info (format "(org)%s" (or node ""))))
20997 ;;;###autoload
20998 (defun org-submit-bug-report ()
20999 "Submit a bug report on Org via mail.
21001 Don't hesitate to report any problems or inaccurate documentation.
21003 If you don't have setup sending mail from (X)Emacs, please copy the
21004 output buffer into your mail program, as it gives us important
21005 information about your Org version and configuration."
21006 (interactive)
21007 (require 'reporter)
21008 (defvar reporter-prompt-for-summary-p)
21009 (org-load-modules-maybe)
21010 (org-require-autoloaded-modules)
21011 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21012 (reporter-submit-bug-report
21013 "emacs-orgmode@gnu.org"
21014 (org-version nil 'full)
21015 (let (list)
21016 (save-window-excursion
21017 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21018 (delete-other-windows)
21019 (erase-buffer)
21020 (insert "You are about to submit a bug report to the Org mailing list.
21022 We would like to add your full Org and Outline configuration to the
21023 bug report. This greatly simplifies the work of the maintainer and
21024 other experts on the mailing list.
21026 HOWEVER, some variables you have customized may contain private
21027 information. The names of customers, colleagues, or friends, might
21028 appear in the form of file names, tags, todo states, or search strings.
21029 If you answer yes to the prompt, you might want to check and remove
21030 such private information before sending the email.")
21031 (add-text-properties (point-min) (point-max) '(face org-warning))
21032 (when (yes-or-no-p "Include your Org configuration ")
21033 (mapatoms
21034 (lambda (v)
21035 (and (boundp v)
21036 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21037 (or (and (symbol-value v)
21038 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21039 (and
21040 (get v 'custom-type) (get v 'standard-value)
21041 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21042 (push v list)))))
21043 (kill-buffer (get-buffer "*Warn about privacy*"))
21044 list))
21045 nil nil
21046 "Remember to cover the basics, that is, what you expected to happen and
21047 what in fact did happen. You don't know how to make a good report? See
21049 https://orgmode.org/manual/Feedback.html#Feedback
21051 Your bug report will be posted to the Org mailing list.
21052 ------------------------------------------------------------------------")
21053 (save-excursion
21054 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21055 (replace-match "\\1Bug: \\3 [\\2]")))))
21058 (defun org-install-agenda-files-menu ()
21059 (let ((bl (buffer-list)))
21060 (save-excursion
21061 (while bl
21062 (set-buffer (pop bl))
21063 (when (derived-mode-p 'org-mode) (setq bl nil)))
21064 (when (derived-mode-p 'org-mode)
21065 (easy-menu-change
21066 '("Org") "File List for Agenda"
21067 (append
21068 (list
21069 ["Edit File List" (org-edit-agenda-file-list) t]
21070 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21071 ["Remove Current File from List" org-remove-file t]
21072 ["Cycle through agenda files" org-cycle-agenda-files t]
21073 ["Occur in all agenda files" org-occur-in-agenda-files t]
21074 "--")
21075 (mapcar 'org-file-menu-entry
21076 ;; Prevent initialization from failing.
21077 (ignore-errors (org-agenda-files t)))))))))
21079 ;;;; Documentation
21081 (defun org-require-autoloaded-modules ()
21082 (interactive)
21083 (mapc #'require
21084 '(org-agenda org-archive org-attach org-clock org-colview org-id
21085 org-table org-timer)))
21087 ;;;###autoload
21088 (defun org-reload (&optional uncompiled)
21089 "Reload all Org Lisp files.
21090 With prefix arg UNCOMPILED, load the uncompiled versions."
21091 (interactive "P")
21092 (require 'loadhist)
21093 (let* ((org-dir (org-find-library-dir "org"))
21094 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21095 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21096 (remove-re (format "\\`%s\\'"
21097 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21098 (feats (delete-dups
21099 (mapcar 'file-name-sans-extension
21100 (mapcar 'file-name-nondirectory
21101 (delq nil
21102 (mapcar 'feature-file
21103 features))))))
21104 (lfeat (append
21105 (sort
21106 (setq feats
21107 (delq nil (mapcar
21108 (lambda (f)
21109 (if (and (string-match feature-re f)
21110 (not (string-match remove-re f)))
21111 f nil))
21112 feats)))
21113 'string-lessp)
21114 (list "org-version" "org")))
21115 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21116 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21117 load-uncore load-misses)
21118 (setq load-misses
21119 (delq 't
21120 (mapcar (lambda (f)
21121 (or (org-load-noerror-mustsuffix (concat org-dir f))
21122 (and (string= org-dir contrib-dir)
21123 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21124 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21125 (add-to-list 'load-uncore f 'append)
21128 lfeat)))
21129 (when load-uncore
21130 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21131 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21132 (if load-misses
21133 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21134 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21135 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21137 ;;;###autoload
21138 (defun org-customize ()
21139 "Call the customize function with org as argument."
21140 (interactive)
21141 (org-load-modules-maybe)
21142 (org-require-autoloaded-modules)
21143 (customize-browse 'org))
21145 (defun org-create-customize-menu ()
21146 "Create a full customization menu for Org mode, insert it into the menu."
21147 (interactive)
21148 (org-load-modules-maybe)
21149 (org-require-autoloaded-modules)
21150 (if (fboundp 'customize-menu-create)
21151 (progn
21152 (easy-menu-change
21153 '("Org") "Customize"
21154 `(["Browse Org group" org-customize t]
21155 "--"
21156 ,(customize-menu-create 'org)
21157 ["Set" Custom-set t]
21158 ["Save" Custom-save t]
21159 ["Reset to Current" Custom-reset-current t]
21160 ["Reset to Saved" Custom-reset-saved t]
21161 ["Reset to Standard Settings" Custom-reset-standard t]))
21162 (message "\"Org\"-menu now contains full customization menu"))
21163 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21165 ;;;; Miscellaneous stuff
21167 ;;; Generally useful functions
21169 (defun org-link-display-format (s)
21170 "Replace links in string S with their description.
21171 If there is no description, use the link target."
21172 (save-match-data
21173 (replace-regexp-in-string
21174 org-bracket-link-analytic-regexp
21175 (lambda (m)
21176 (if (match-end 5) (match-string 5 m)
21177 (concat (match-string 1 m) (match-string 3 m))))
21178 s nil t)))
21180 (defun org-toggle-link-display ()
21181 "Toggle the literal or descriptive display of links."
21182 (interactive)
21183 (if org-descriptive-links
21184 (progn (org-remove-from-invisibility-spec '(org-link))
21185 (org-restart-font-lock)
21186 (setq org-descriptive-links nil))
21187 (progn (add-to-invisibility-spec '(org-link))
21188 (org-restart-font-lock)
21189 (setq org-descriptive-links t))))
21191 (defun org-in-clocktable-p ()
21192 "Check if the cursor is in a clocktable."
21193 (let ((pos (point)) start)
21194 (save-excursion
21195 (end-of-line 1)
21196 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21197 (setq start (match-beginning 0))
21198 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21199 (>= (match-end 0) pos)
21200 start))))
21202 (defun org-in-verbatim-emphasis ()
21203 (save-match-data
21204 (and (org-in-regexp org-verbatim-re 2)
21205 (>= (point) (match-beginning 3))
21206 (<= (point) (match-end 4)))))
21208 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21209 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21210 (if (and marker (marker-buffer marker)
21211 (buffer-live-p (marker-buffer marker)))
21212 (progn
21213 (pop-to-buffer-same-window (marker-buffer marker))
21214 (when (or (> marker (point-max)) (< marker (point-min)))
21215 (widen))
21216 (goto-char marker)
21217 (org-show-context 'org-goto))
21218 (if bookmark
21219 (bookmark-jump bookmark)
21220 (error "Cannot find location"))))
21222 (defun org-quote-csv-field (s)
21223 "Quote field for inclusion in CSV material."
21224 (if (string-match "[\",]" s)
21225 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21228 (defun org-force-self-insert (N)
21229 "Needed to enforce self-insert under remapping."
21230 (interactive "p")
21231 (self-insert-command N))
21233 (defun org-fill-template (template alist)
21234 "Find each %key of ALIST in TEMPLATE and replace it."
21235 (let ((case-fold-search nil))
21236 (dolist (entry (sort (copy-sequence alist)
21237 (lambda (a b) (< (length (car a)) (length (car b))))))
21238 (setq template
21239 (replace-regexp-in-string
21240 (concat "%" (regexp-quote (car entry)))
21241 (or (cdr entry) "") template t t)))
21242 template))
21244 (defun org-quote-vert (s)
21245 "Replace \"|\" with \"\\vert\"."
21246 (while (string-match "|" s)
21247 (setq s (replace-match "\\vert" t t s)))
21250 (defun org-uuidgen-p (s)
21251 "Is S an ID created by UUIDGEN?"
21252 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21254 (defun org-in-src-block-p (&optional inside)
21255 "Whether point is in a code source block.
21256 When INSIDE is non-nil, don't consider we are within a src block
21257 when point is at #+BEGIN_SRC or #+END_SRC."
21258 (let ((case-fold-search t))
21259 (or (and (eq (get-char-property (point) 'src-block) t))
21260 (and (not inside)
21261 (save-match-data
21262 (save-excursion
21263 (beginning-of-line)
21264 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21266 (defun org-context ()
21267 "Return a list of contexts of the current cursor position.
21268 If several contexts apply, all are returned.
21269 Each context entry is a list with a symbol naming the context, and
21270 two positions indicating start and end of the context. Possible
21271 contexts are:
21273 :headline anywhere in a headline
21274 :headline-stars on the leading stars in a headline
21275 :todo-keyword on a TODO keyword (including DONE) in a headline
21276 :tags on the TAGS in a headline
21277 :priority on the priority cookie in a headline
21278 :item on the first line of a plain list item
21279 :item-bullet on the bullet/number of a plain list item
21280 :checkbox on the checkbox in a plain list item
21281 :table in an Org table
21282 :table-special on a special filed in a table
21283 :table-table in a table.el table
21284 :clocktable in a clocktable
21285 :src-block in a source block
21286 :link on a hyperlink
21287 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21288 :target on a <<target>>
21289 :radio-target on a <<<radio-target>>>
21290 :latex-fragment on a LaTeX fragment
21291 :latex-preview on a LaTeX fragment with overlaid preview image
21293 This function expects the position to be visible because it uses font-lock
21294 faces as a help to recognize the following contexts: :table-special, :link,
21295 and :keyword."
21296 (let* ((f (get-text-property (point) 'face))
21297 (faces (if (listp f) f (list f)))
21298 (case-fold-search t)
21299 (p (point)) clist o)
21300 ;; First the large context
21301 (cond
21302 ((org-at-heading-p t)
21303 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21304 (when (progn
21305 (beginning-of-line 1)
21306 (looking-at org-todo-line-tags-regexp))
21307 (push (org-point-in-group p 1 :headline-stars) clist)
21308 (push (org-point-in-group p 2 :todo-keyword) clist)
21309 (push (org-point-in-group p 4 :tags) clist))
21310 (goto-char p)
21311 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21312 (when (looking-at "\\[#[A-Z0-9]\\]")
21313 (push (org-point-in-group p 0 :priority) clist)))
21315 ((org-at-item-p)
21316 (push (org-point-in-group p 2 :item-bullet) clist)
21317 (push (list :item (point-at-bol)
21318 (save-excursion (org-end-of-item) (point)))
21319 clist)
21320 (and (org-at-item-checkbox-p)
21321 (push (org-point-in-group p 0 :checkbox) clist)))
21323 ((org-at-table-p)
21324 (push (list :table (org-table-begin) (org-table-end)) clist)
21325 (when (memq 'org-formula faces)
21326 (push (list :table-special
21327 (previous-single-property-change p 'face)
21328 (next-single-property-change p 'face)) clist)))
21329 ((org-at-table-p 'any)
21330 (push (list :table-table) clist)))
21331 (goto-char p)
21333 (let ((case-fold-search t))
21334 ;; New the "medium" contexts: clocktables, source blocks
21335 (cond ((org-in-clocktable-p)
21336 (push (list :clocktable
21337 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21338 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21339 (match-beginning 1))
21340 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21341 (match-end 0))) clist))
21342 ((org-in-src-block-p)
21343 (push (list :src-block
21344 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21345 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21346 (match-beginning 1))
21347 (and (search-forward "#+END_SRC" nil t)
21348 (match-beginning 0))) clist))))
21349 (goto-char p)
21351 ;; Now the small context
21352 (cond
21353 ((org-at-timestamp-p)
21354 (push (org-point-in-group p 0 :timestamp) clist))
21355 ((memq 'org-link faces)
21356 (push (list :link
21357 (previous-single-property-change p 'face)
21358 (next-single-property-change p 'face)) clist))
21359 ((memq 'org-special-keyword faces)
21360 (push (list :keyword
21361 (previous-single-property-change p 'face)
21362 (next-single-property-change p 'face)) clist))
21363 ((org-at-target-p)
21364 (push (org-point-in-group p 0 :target) clist)
21365 (goto-char (1- (match-beginning 0)))
21366 (when (looking-at org-radio-target-regexp)
21367 (push (org-point-in-group p 0 :radio-target) clist))
21368 (goto-char p))
21369 ((setq o (cl-some
21370 (lambda (o)
21371 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21373 (overlays-at (point))))
21374 (push (list :latex-fragment
21375 (overlay-start o) (overlay-end o)) clist)
21376 (push (list :latex-preview
21377 (overlay-start o) (overlay-end o)) clist))
21378 ((org-inside-LaTeX-fragment-p)
21379 ;; FIXME: positions wrong.
21380 (push (list :latex-fragment (point) (point)) clist)))
21382 (setq clist (nreverse (delq nil clist)))
21383 clist))
21385 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21386 "Non-nil when point is between matches of START-RE and END-RE.
21388 Also return a non-nil value when point is on one of the matches.
21390 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21391 buffer positions. Default values are the positions of headlines
21392 surrounding the point.
21394 The functions returns a cons cell whose car (resp. cdr) is the
21395 position before START-RE (resp. after END-RE)."
21396 (save-match-data
21397 (let ((pos (point))
21398 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21399 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21400 beg end)
21401 (save-excursion
21402 ;; Point is on a block when on START-RE or if START-RE can be
21403 ;; found before it...
21404 (and (or (org-in-regexp start-re)
21405 (re-search-backward start-re limit-up t))
21406 (setq beg (match-beginning 0))
21407 ;; ... and END-RE after it...
21408 (goto-char (match-end 0))
21409 (re-search-forward end-re limit-down t)
21410 (> (setq end (match-end 0)) pos)
21411 ;; ... without another START-RE in-between.
21412 (goto-char (match-beginning 0))
21413 (not (re-search-backward start-re (1+ beg) t))
21414 ;; Return value.
21415 (cons beg end))))))
21417 (defun org-in-block-p (names)
21418 "Non-nil when point belongs to a block whose name belongs to NAMES.
21420 NAMES is a list of strings containing names of blocks.
21422 Return first block name matched, or nil. Beware that in case of
21423 nested blocks, the returned name may not belong to the closest
21424 block from point."
21425 (save-match-data
21426 (catch 'exit
21427 (let ((case-fold-search t)
21428 (lim-up (save-excursion (outline-previous-heading)))
21429 (lim-down (save-excursion (outline-next-heading))))
21430 (dolist (name names)
21431 (let ((n (regexp-quote name)))
21432 (when (org-between-regexps-p
21433 (concat "^[ \t]*#\\+begin_" n)
21434 (concat "^[ \t]*#\\+end_" n)
21435 lim-up lim-down)
21436 (throw 'exit n)))))
21437 nil)))
21439 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21440 "Call `multi-occur' with buffers for all agenda files."
21441 (interactive "sOrg-files matching: ")
21442 (let* ((files (org-agenda-files))
21443 (tnames (mapcar #'file-truename files))
21444 (extra org-agenda-text-search-extra-files))
21445 (when (eq (car extra) 'agenda-archives)
21446 (setq extra (cdr extra))
21447 (setq files (org-add-archive-files files)))
21448 (dolist (f extra)
21449 (unless (member (file-truename f) tnames)
21450 (unless (member f files) (setq files (append files (list f))))
21451 (setq tnames (append tnames (list (file-truename f))))))
21452 (multi-occur
21453 (mapcar (lambda (x)
21454 (with-current-buffer
21455 ;; FIXME: Why not just (find-file-noselect x)?
21456 ;; Is it to avoid the "revert buffer" prompt?
21457 (or (get-file-buffer x) (find-file-noselect x))
21458 (widen)
21459 (current-buffer)))
21460 files)
21461 regexp)))
21463 (add-hook 'occur-mode-find-occurrence-hook
21464 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21466 (defun org-occur-link-in-agenda-files ()
21467 "Create a link and search for it in the agendas.
21468 The link is not stored in `org-stored-links', it is just created
21469 for the search purpose."
21470 (interactive)
21471 (let ((link (condition-case nil
21472 (org-store-link nil)
21473 (error "Unable to create a link to here"))))
21474 (org-occur-in-agenda-files (regexp-quote link))))
21476 (defun org-back-over-empty-lines ()
21477 "Move backwards over whitespace, to the beginning of the first empty line.
21478 Returns the number of empty lines passed."
21479 (let ((pos (point)))
21480 (if (cdr (assq 'heading org-blank-before-new-entry))
21481 (skip-chars-backward " \t\n\r")
21482 (unless (eobp)
21483 (forward-line -1)))
21484 (beginning-of-line 2)
21485 (goto-char (min (point) pos))
21486 (count-lines (point) pos)))
21488 (defun org-switch-to-buffer-other-window (&rest args)
21489 "Switch to buffer in a second window on the current frame.
21490 In particular, do not allow pop-up frames.
21491 Returns the newly created buffer."
21492 (org-no-popups
21493 (apply 'switch-to-buffer-other-window args)))
21495 (defun org-replace-escapes (string table)
21496 "Replace %-escapes in STRING with values in TABLE.
21497 TABLE is an association list with keys like \"%a\" and string values.
21498 The sequences in STRING may contain normal field width and padding information,
21499 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21500 so values can contain further %-escapes if they are define later in TABLE."
21501 (let ((tbl (copy-alist table))
21502 (case-fold-search nil)
21503 (pchg 0)
21504 re rpl)
21505 (dolist (e tbl)
21506 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21507 (when (and (cdr e) (string-match re (cdr e)))
21508 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21509 (safe "SREF"))
21510 (add-text-properties 0 3 (list 'sref sref) safe)
21511 (setcdr e (replace-match safe t t (cdr e)))))
21512 (while (string-match re string)
21513 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21514 (cdr e)))
21515 (setq string (replace-match rpl t t string))))
21516 (while (setq pchg (next-property-change pchg string))
21517 (let ((sref (get-text-property pchg 'sref string)))
21518 (when (and sref (string-match "SREF" string pchg))
21519 (setq string (replace-match sref t t string)))))
21520 string))
21522 ;;; TODO: Only called once, from ox-odt which should probably use
21523 ;;; org-export-inline-image-p or something.
21524 (defun org-file-image-p (file)
21525 "Return non-nil if FILE is an image."
21526 (save-match-data
21527 (string-match (image-file-name-regexp) file)))
21529 (defun org-get-cursor-date (&optional with-time)
21530 "Return the date at cursor in as a time.
21531 This works in the calendar and in the agenda, anywhere else it just
21532 returns the current time.
21533 If WITH-TIME is non-nil, returns the time of the event at point (in
21534 the agenda) or the current time of the day."
21535 (let (date day defd tp hod mod)
21536 (when with-time
21537 (setq tp (get-text-property (point) 'time))
21538 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21539 (setq hod (string-to-number (match-string 1 tp))
21540 mod (string-to-number (match-string 2 tp))))
21541 (or tp (let ((now (decode-time)))
21542 (setq hod (nth 2 now)
21543 mod (nth 1 now)))))
21544 (cond
21545 ((eq major-mode 'calendar-mode)
21546 (setq date (calendar-cursor-to-date)
21547 defd (encode-time 0 (or mod 0) (or hod 0)
21548 (nth 1 date) (nth 0 date) (nth 2 date))))
21549 ((eq major-mode 'org-agenda-mode)
21550 (setq day (get-text-property (point) 'day))
21551 (when day
21552 (setq date (calendar-gregorian-from-absolute day)
21553 defd (encode-time 0 (or mod 0) (or hod 0)
21554 (nth 1 date) (nth 0 date) (nth 2 date))))))
21555 (or defd (current-time))))
21557 (defun org-mark-subtree (&optional up)
21558 "Mark the current subtree.
21559 This puts point at the start of the current subtree, and mark at
21560 the end. If a numeric prefix UP is given, move up into the
21561 hierarchy of headlines by UP levels before marking the subtree."
21562 (interactive "P")
21563 (org-with-limited-levels
21564 (cond ((org-at-heading-p) (beginning-of-line))
21565 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21566 (t (outline-previous-visible-heading 1))))
21567 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21568 (if (called-interactively-p 'any)
21569 (call-interactively 'org-mark-element)
21570 (org-mark-element)))
21572 ;;; Indentation
21574 (defvar org-element-greater-elements)
21575 (defun org--get-expected-indentation (element contentsp)
21576 "Expected indentation column for current line, according to ELEMENT.
21577 ELEMENT is an element containing point. CONTENTSP is non-nil
21578 when indentation is to be computed according to contents of
21579 ELEMENT."
21580 (let ((type (org-element-type element))
21581 (start (org-element-property :begin element))
21582 (post-affiliated (org-element-property :post-affiliated element)))
21583 (org-with-wide-buffer
21584 (cond
21585 (contentsp
21586 (cl-case type
21587 ((diary-sexp footnote-definition) 0)
21588 ((headline inlinetask nil)
21589 (if (not org-adapt-indentation) 0
21590 (let ((level (org-current-level)))
21591 (if level (1+ level) 0))))
21592 ((item plain-list) (org-list-item-body-column post-affiliated))
21594 (goto-char start)
21595 (org-get-indentation))))
21596 ((memq type '(headline inlinetask nil))
21597 (if (org-match-line "[ \t]*$")
21598 (org--get-expected-indentation element t)
21600 ((memq type '(diary-sexp footnote-definition)) 0)
21601 ;; First paragraph of a footnote definition or an item.
21602 ;; Indent like parent.
21603 ((< (line-beginning-position) start)
21604 (org--get-expected-indentation
21605 (org-element-property :parent element) t))
21606 ;; At first line: indent according to previous sibling, if any,
21607 ;; ignoring footnote definitions and inline tasks, or parent's
21608 ;; contents.
21609 ((= (line-beginning-position) start)
21610 (catch 'exit
21611 (while t
21612 (if (= (point-min) start) (throw 'exit 0)
21613 (goto-char (1- start))
21614 (let* ((previous (org-element-at-point))
21615 (parent previous))
21616 (while (and parent (<= (org-element-property :end parent) start))
21617 (setq previous parent
21618 parent (org-element-property :parent parent)))
21619 (cond
21620 ((not previous) (throw 'exit 0))
21621 ((> (org-element-property :end previous) start)
21622 (throw 'exit (org--get-expected-indentation previous t)))
21623 ((memq (org-element-type previous)
21624 '(footnote-definition inlinetask))
21625 (setq start (org-element-property :begin previous)))
21626 (t (goto-char (org-element-property :begin previous))
21627 (throw 'exit
21628 (if (bolp) (org-get-indentation)
21629 ;; At first paragraph in an item or
21630 ;; a footnote definition.
21631 (org--get-expected-indentation
21632 (org-element-property :parent previous) t))))))))))
21633 ;; Otherwise, move to the first non-blank line above.
21635 (beginning-of-line)
21636 (let ((pos (point)))
21637 (skip-chars-backward " \r\t\n")
21638 (cond
21639 ;; Two blank lines end a footnote definition or a plain
21640 ;; list. When we indent an empty line after them, the
21641 ;; containing list or footnote definition is over, so it
21642 ;; qualifies as a previous sibling. Therefore, we indent
21643 ;; like its first line.
21644 ((and (memq type '(footnote-definition plain-list))
21645 (> (count-lines (point) pos) 2))
21646 (goto-char start)
21647 (org-get-indentation))
21648 ;; Line above is the first one of a paragraph at the
21649 ;; beginning of an item or a footnote definition. Indent
21650 ;; like parent.
21651 ((< (line-beginning-position) start)
21652 (org--get-expected-indentation
21653 (org-element-property :parent element) t))
21654 ;; Line above is the beginning of an element, i.e., point
21655 ;; was originally on the blank lines between element's start
21656 ;; and contents.
21657 ((= (line-beginning-position) post-affiliated)
21658 (org--get-expected-indentation element t))
21659 ;; POS is after contents in a greater element. Indent like
21660 ;; the beginning of the element.
21661 ((and (memq type org-element-greater-elements)
21662 (let ((cend (org-element-property :contents-end element)))
21663 (and cend (<= cend pos))))
21664 ;; As a special case, if point is at the end of a footnote
21665 ;; definition or an item, indent like the very last element
21666 ;; within. If that last element is an item, indent like
21667 ;; its contents.
21668 (if (memq type '(footnote-definition item plain-list))
21669 (let ((last (org-element-at-point)))
21670 (goto-char pos)
21671 (org--get-expected-indentation
21672 last (eq (org-element-type last) 'item)))
21673 (goto-char start)
21674 (org-get-indentation)))
21675 ;; In any other case, indent like the current line.
21676 (t (org-get-indentation)))))))))
21678 (defun org--align-node-property ()
21679 "Align node property at point.
21680 Alignment is done according to `org-property-format', which see."
21681 (when (save-excursion
21682 (beginning-of-line)
21683 (looking-at org-property-re))
21684 (replace-match
21685 (concat (match-string 4)
21686 (org-trim
21687 (format org-property-format (match-string 1) (match-string 3))))
21688 t t)))
21690 (defun org-indent-line ()
21691 "Indent line depending on context.
21693 Indentation is done according to the following rules:
21695 - Footnote definitions, diary sexps, headlines and inline tasks
21696 have to start at column 0.
21698 - On the very first line of an element, consider, in order, the
21699 next rules until one matches:
21701 1. If there's a sibling element before, ignoring footnote
21702 definitions and inline tasks, indent like its first line.
21704 2. If element has a parent, indent like its contents. More
21705 precisely, if parent is an item, indent after the
21706 description part, if any, or the bullet (see
21707 `org-list-description-max-indent'). Else, indent like
21708 parent's first line.
21710 3. Otherwise, indent relatively to current level, if
21711 `org-adapt-indentation' is non-nil, or to left margin.
21713 - On a blank line at the end of an element, indent according to
21714 the type of the element. More precisely
21716 1. If element is a plain list, an item, or a footnote
21717 definition, indent like the very last element within.
21719 2. If element is a paragraph, indent like its last non blank
21720 line.
21722 3. Otherwise, indent like its very first line.
21724 - In the code part of a source block, use language major mode
21725 to indent current line if `org-src-tab-acts-natively' is
21726 non-nil. If it is nil, do nothing.
21728 - Otherwise, indent like the first non-blank line above.
21730 The function doesn't indent an item as it could break the whole
21731 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21732 `\\[org-shiftmetaright]'.
21734 Also align node properties according to `org-property-format'."
21735 (interactive)
21736 (cond
21737 ((org-at-heading-p) 'noindent)
21739 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21740 (type (org-element-type element)))
21741 (cond ((and (memq type '(plain-list item))
21742 (= (line-beginning-position)
21743 (org-element-property :post-affiliated element)))
21744 'noindent)
21745 ((and (eq type 'latex-environment)
21746 (>= (point) (org-element-property :post-affiliated element))
21747 (< (point) (org-with-wide-buffer
21748 (goto-char (org-element-property :end element))
21749 (skip-chars-backward " \r\t\n")
21750 (line-beginning-position 2))))
21751 'noindent)
21752 ((and (eq type 'src-block)
21753 org-src-tab-acts-natively
21754 (> (line-beginning-position)
21755 (org-element-property :post-affiliated element))
21756 (< (line-beginning-position)
21757 (org-with-wide-buffer
21758 (goto-char (org-element-property :end element))
21759 (skip-chars-backward " \r\t\n")
21760 (line-beginning-position))))
21761 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21763 (let ((column (org--get-expected-indentation element nil)))
21764 ;; Preserve current column.
21765 (if (<= (current-column) (current-indentation))
21766 (indent-line-to column)
21767 (save-excursion (indent-line-to column))))
21768 ;; Align node property. Also preserve current column.
21769 (when (eq type 'node-property)
21770 (let ((column (current-column)))
21771 (org--align-node-property)
21772 (org-move-to-column column)))))))))
21774 (defun org-indent-region (start end)
21775 "Indent each non-blank line in the region.
21776 Called from a program, START and END specify the region to
21777 indent. The function will not indent contents of example blocks,
21778 verse blocks and export blocks as leading white spaces are
21779 assumed to be significant there."
21780 (interactive "r")
21781 (save-excursion
21782 (goto-char start)
21783 (skip-chars-forward " \r\t\n")
21784 (unless (eobp) (beginning-of-line))
21785 (let ((indent-to
21786 (lambda (ind pos)
21787 ;; Set IND as indentation for all lines between point and
21788 ;; POS. Blank lines are ignored. Leave point after POS
21789 ;; once done.
21790 (let ((limit (copy-marker pos)))
21791 (while (< (point) limit)
21792 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21793 (forward-line))
21794 (set-marker limit nil))))
21795 (end (copy-marker end)))
21796 (while (< (point) end)
21797 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21798 (let* ((element (org-element-at-point))
21799 (type (org-element-type element))
21800 (element-end (copy-marker (org-element-property :end element)))
21801 (ind (org--get-expected-indentation element nil)))
21802 (cond
21803 ;; Element indented as a single block. Example blocks
21804 ;; preserving indentation are a special case since the
21805 ;; "contents" must not be indented whereas the block
21806 ;; boundaries can.
21807 ((or (memq type '(export-block latex-environment))
21808 (and (eq type 'example-block)
21809 (not
21810 (or org-src-preserve-indentation
21811 (org-element-property :preserve-indent element)))))
21812 (let ((offset (- ind (org-get-indentation))))
21813 (unless (zerop offset)
21814 (indent-rigidly (org-element-property :begin element)
21815 (org-element-property :end element)
21816 offset)))
21817 (goto-char element-end))
21818 ;; Elements indented line wise. Be sure to exclude
21819 ;; example blocks (preserving indentation) and source
21820 ;; blocks from this category as they are treated
21821 ;; specially later.
21822 ((or (memq type '(paragraph table table-row))
21823 (not (or (org-element-property :contents-begin element)
21824 (memq type '(example-block src-block)))))
21825 (when (eq type 'node-property)
21826 (org--align-node-property)
21827 (beginning-of-line))
21828 (funcall indent-to ind (min element-end end)))
21829 ;; Elements consisting of three parts: before the
21830 ;; contents, the contents, and after the contents. The
21831 ;; contents are treated specially, according to the
21832 ;; element type, or not indented at all. Other parts are
21833 ;; indented as a single block.
21835 (let* ((post (copy-marker
21836 (org-element-property :post-affiliated element)))
21837 (cbeg
21838 (copy-marker
21839 (cond
21840 ((not (org-element-property :contents-begin element))
21841 ;; Fake contents for source blocks.
21842 (org-with-wide-buffer
21843 (goto-char post)
21844 (line-beginning-position 2)))
21845 ((memq type '(footnote-definition item plain-list))
21846 ;; Contents in these elements could start on
21847 ;; the same line as the beginning of the
21848 ;; element. Make sure we start indenting
21849 ;; from the second line.
21850 (org-with-wide-buffer
21851 (goto-char post)
21852 (end-of-line)
21853 (skip-chars-forward " \r\t\n")
21854 (if (eobp) (point) (line-beginning-position))))
21855 (t (org-element-property :contents-begin element)))))
21856 (cend (copy-marker
21857 (or (org-element-property :contents-end element)
21858 ;; Fake contents for source blocks.
21859 (org-with-wide-buffer
21860 (goto-char element-end)
21861 (skip-chars-backward " \r\t\n")
21862 (line-beginning-position)))
21863 t)))
21864 ;; Do not change items indentation individually as it
21865 ;; might break the list as a whole. On the other
21866 ;; hand, when at a plain list, indent it as a whole.
21867 (cond ((eq type 'plain-list)
21868 (let ((offset (- ind (org-get-indentation))))
21869 (unless (zerop offset)
21870 (indent-rigidly (org-element-property :begin element)
21871 (org-element-property :end element)
21872 offset))
21873 (goto-char cbeg)))
21874 ((eq type 'item) (goto-char cbeg))
21875 (t (funcall indent-to ind (min cbeg end))))
21876 (when (< (point) end)
21877 (cl-case type
21878 ((example-block verse-block))
21879 (src-block
21880 ;; In a source block, indent source code
21881 ;; according to language major mode, but only if
21882 ;; `org-src-tab-acts-natively' is non-nil.
21883 (when (and (< (point) end) org-src-tab-acts-natively)
21884 (ignore-errors
21885 (org-babel-do-in-edit-buffer
21886 (indent-region (point-min) (point-max))))))
21887 (t (org-indent-region (point) (min cend end))))
21888 (goto-char (min cend end))
21889 (when (< (point) end)
21890 (funcall indent-to ind (min element-end end))))
21891 (set-marker post nil)
21892 (set-marker cbeg nil)
21893 (set-marker cend nil))))
21894 (set-marker element-end nil))))
21895 (set-marker end nil))))
21897 (defun org-indent-drawer ()
21898 "Indent the drawer at point."
21899 (interactive)
21900 (unless (save-excursion
21901 (beginning-of-line)
21902 (looking-at-p org-drawer-regexp))
21903 (user-error "Not at a drawer"))
21904 (let ((element (org-element-at-point)))
21905 (unless (memq (org-element-type element) '(drawer property-drawer))
21906 (user-error "Not at a drawer"))
21907 (org-with-wide-buffer
21908 (org-indent-region (org-element-property :begin element)
21909 (org-element-property :end element))))
21910 (message "Drawer at point indented"))
21912 (defun org-indent-block ()
21913 "Indent the block at point."
21914 (interactive)
21915 (unless (save-excursion
21916 (beginning-of-line)
21917 (let ((case-fold-search t))
21918 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21919 (user-error "Not at a block"))
21920 (let ((element (org-element-at-point)))
21921 (unless (memq (org-element-type element)
21922 '(comment-block center-block dynamic-block example-block
21923 export-block quote-block special-block
21924 src-block verse-block))
21925 (user-error "Not at a block"))
21926 (org-with-wide-buffer
21927 (org-indent-region (org-element-property :begin element)
21928 (org-element-property :end element))))
21929 (message "Block at point indented"))
21932 ;;; Filling
21934 ;; We use our own fill-paragraph and auto-fill functions.
21936 ;; `org-fill-paragraph' relies on adaptive filling and context
21937 ;; checking. Appropriate `fill-prefix' is computed with
21938 ;; `org-adaptive-fill-function'.
21940 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21941 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21942 ;; `org-adaptive-fill-function' value. Internally,
21943 ;; `org-comment-line-break-function' breaks the line.
21945 ;; `org-setup-filling' installs filling and auto-filling related
21946 ;; variables during `org-mode' initialization.
21948 (defun org-setup-filling ()
21949 (require 'org-element)
21950 ;; Prevent auto-fill from inserting unwanted new items.
21951 (when (boundp 'fill-nobreak-predicate)
21952 (setq-local
21953 fill-nobreak-predicate
21954 (org-uniquify
21955 (append fill-nobreak-predicate
21956 '(org-fill-line-break-nobreak-p
21957 org-fill-n-macro-as-item-nobreak-p
21958 org-fill-paragraph-with-timestamp-nobreak-p)))))
21959 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21960 (setq-local paragraph-start paragraph-ending)
21961 (setq-local paragraph-separate paragraph-ending))
21962 (setq-local fill-paragraph-function 'org-fill-paragraph)
21963 (setq-local auto-fill-inhibit-regexp nil)
21964 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21965 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21966 (setq-local comment-line-break-function 'org-comment-line-break-function))
21968 (defun org-fill-line-break-nobreak-p ()
21969 "Non-nil when a new line at point would create an Org line break."
21970 (save-excursion
21971 (skip-chars-backward "[ \t]")
21972 (skip-chars-backward "\\\\")
21973 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21975 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21976 "Non-nil when a new line at point would split a timestamp."
21977 (and (org-at-timestamp-p 'lax)
21978 (not (looking-at org-ts-regexp-both))))
21980 (defun org-fill-n-macro-as-item-nobreak-p ()
21981 "Non-nil when a new line at point would create a new list."
21982 ;; During export, a "n" macro followed by a dot or a closing
21983 ;; parenthesis can end up being parsed as a new list item.
21984 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21986 (defvar orgtbl-line-start-regexp) ; From org-table.el
21987 (defun org-adaptive-fill-function ()
21988 "Compute a fill prefix for the current line.
21989 Return fill prefix, as a string, or nil if current line isn't
21990 meant to be filled. For convenience, if `adaptive-fill-regexp'
21991 matches in paragraphs or comments, use it."
21992 (org-with-wide-buffer
21993 (unless (org-at-heading-p)
21994 (let* ((p (line-beginning-position))
21995 (element (save-excursion
21996 (beginning-of-line)
21997 (org-element-at-point)))
21998 (type (org-element-type element))
21999 (post-affiliated (org-element-property :post-affiliated element)))
22000 (unless (< p post-affiliated)
22001 (cl-case type
22002 (comment
22003 (save-excursion
22004 (beginning-of-line)
22005 (looking-at "[ \t]*")
22006 (concat (match-string 0) "# ")))
22007 (footnote-definition "")
22008 ((item plain-list)
22009 (make-string (org-list-item-body-column post-affiliated) ?\s))
22010 (paragraph
22011 ;; Fill prefix is usually the same as the current line,
22012 ;; unless the paragraph is at the beginning of an item.
22013 (let ((parent (org-element-property :parent element)))
22014 (save-excursion
22015 (beginning-of-line)
22016 (cond ((eq (org-element-type parent) 'item)
22017 (make-string (org-list-item-body-column
22018 (org-element-property :begin parent))
22019 ?\s))
22020 ((and adaptive-fill-regexp
22021 ;; Locally disable
22022 ;; `adaptive-fill-function' to let
22023 ;; `fill-context-prefix' handle
22024 ;; `adaptive-fill-regexp' variable.
22025 (let (adaptive-fill-function)
22026 (fill-context-prefix
22027 post-affiliated
22028 (org-element-property :end element)))))
22029 ((looking-at "[ \t]+") (match-string 0))
22030 (t "")))))
22031 (comment-block
22032 ;; Only fill contents if P is within block boundaries.
22033 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22034 (forward-line)
22035 (point)))
22036 (cend (save-excursion
22037 (goto-char (org-element-property :end element))
22038 (skip-chars-backward " \r\t\n")
22039 (line-beginning-position))))
22040 (when (and (>= p cbeg) (< p cend))
22041 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22042 (match-string 0)
22043 ""))))))))))
22045 (defun org-fill-element (&optional justify)
22046 "Fill element at point, when applicable.
22048 This function only applies to comment blocks, comments, example
22049 blocks and paragraphs. Also, as a special case, re-align table
22050 when point is at one.
22052 If JUSTIFY is non-nil (interactively, with prefix argument),
22053 justify as well. If `sentence-end-double-space' is non-nil, then
22054 period followed by one space does not end a sentence, so don't
22055 break a line there. The variable `fill-column' controls the
22056 width for filling.
22058 For convenience, when point is at a plain list, an item or
22059 a footnote definition, try to fill the first paragraph within."
22060 (with-syntax-table org-mode-transpose-word-syntax-table
22061 ;; Move to end of line in order to get the first paragraph within
22062 ;; a plain list or a footnote definition.
22063 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22064 ;; First check if point is in a blank line at the beginning of
22065 ;; the buffer. In that case, ignore filling.
22066 (cl-case (org-element-type element)
22067 ;; Use major mode filling function is src blocks.
22068 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22069 ;; Align Org tables, leave table.el tables as-is.
22070 (table-row (org-table-align) t)
22071 (table
22072 (when (eq (org-element-property :type element) 'org)
22073 (save-excursion
22074 (goto-char (org-element-property :post-affiliated element))
22075 (org-table-align)))
22077 (paragraph
22078 ;; Paragraphs may contain `line-break' type objects.
22079 (let ((beg (max (point-min)
22080 (org-element-property :contents-begin element)))
22081 (end (min (point-max)
22082 (org-element-property :contents-end element))))
22083 ;; Do nothing if point is at an affiliated keyword.
22084 (if (< (line-end-position) beg) t
22085 ;; Fill paragraph, taking line breaks into account.
22086 (save-excursion
22087 (goto-char beg)
22088 (let ((cuts (list beg)))
22089 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22090 (when (eq 'line-break
22091 (org-element-type
22092 (save-excursion (backward-char)
22093 (org-element-context))))
22094 (push (point) cuts)))
22095 (dolist (c (delq end cuts))
22096 (fill-region-as-paragraph c end justify)
22097 (setq end c))))
22098 t)))
22099 ;; Contents of `comment-block' type elements should be
22100 ;; filled as plain text, but only if point is within block
22101 ;; markers.
22102 (comment-block
22103 (let* ((case-fold-search t)
22104 (beg (save-excursion
22105 (goto-char (org-element-property :begin element))
22106 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22107 (forward-line)
22108 (point)))
22109 (end (save-excursion
22110 (goto-char (org-element-property :end element))
22111 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22112 (line-beginning-position))))
22113 (if (or (< (point) beg) (> (point) end)) t
22114 (fill-region-as-paragraph
22115 (save-excursion (end-of-line)
22116 (re-search-backward "^[ \t]*$" beg 'move)
22117 (line-beginning-position))
22118 (save-excursion (beginning-of-line)
22119 (re-search-forward "^[ \t]*$" end 'move)
22120 (line-beginning-position))
22121 justify))))
22122 ;; Fill comments.
22123 (comment
22124 (let ((begin (org-element-property :post-affiliated element))
22125 (end (org-element-property :end element)))
22126 (when (and (>= (point) begin) (<= (point) end))
22127 (let ((begin (save-excursion
22128 (end-of-line)
22129 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22130 (progn (forward-line) (point))
22131 begin)))
22132 (end (save-excursion
22133 (end-of-line)
22134 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22135 (1- (line-beginning-position))
22136 (skip-chars-backward " \r\t\n")
22137 (line-end-position)))))
22138 ;; Do not fill comments when at a blank line.
22139 (when (> end begin)
22140 (let ((fill-prefix
22141 (save-excursion
22142 (beginning-of-line)
22143 (looking-at "[ \t]*#")
22144 (let ((comment-prefix (match-string 0)))
22145 (goto-char (match-end 0))
22146 (if (looking-at adaptive-fill-regexp)
22147 (concat comment-prefix (match-string 0))
22148 (concat comment-prefix " "))))))
22149 (save-excursion
22150 (fill-region-as-paragraph begin end justify))))))
22152 ;; Ignore every other element.
22153 (otherwise t)))))
22155 (defun org-fill-paragraph (&optional justify region)
22156 "Fill element at point, when applicable.
22158 This function only applies to comment blocks, comments, example
22159 blocks and paragraphs. Also, as a special case, re-align table
22160 when point is at one.
22162 For convenience, when point is at a plain list, an item or
22163 a footnote definition, try to fill the first paragraph within.
22165 If JUSTIFY is non-nil (interactively, with prefix argument),
22166 justify as well. If `sentence-end-double-space' is non-nil, then
22167 period followed by one space does not end a sentence, so don't
22168 break a line there. The variable `fill-column' controls the
22169 width for filling.
22171 The REGION argument is non-nil if called interactively; in that
22172 case, if Transient Mark mode is enabled and the mark is active,
22173 fill each of the elements in the active region, instead of just
22174 filling the current element."
22175 (interactive (progn
22176 (barf-if-buffer-read-only)
22177 (list (if current-prefix-arg 'full) t)))
22178 (cond
22179 ((and region transient-mark-mode mark-active
22180 (not (eq (region-beginning) (region-end))))
22181 (let ((origin (point-marker))
22182 (start (region-beginning)))
22183 (unwind-protect
22184 (progn
22185 (goto-char (region-end))
22186 (while (> (point) start)
22187 (org-backward-paragraph)
22188 (org-fill-element justify)))
22189 (goto-char origin)
22190 (set-marker origin nil))))
22191 (t (org-fill-element justify))))
22193 (defun org-auto-fill-function ()
22194 "Auto-fill function."
22195 ;; Check if auto-filling is meaningful.
22196 (let ((fc (current-fill-column)))
22197 (when (and fc (> (current-column) fc))
22198 (let* ((fill-prefix (org-adaptive-fill-function))
22199 ;; Enforce empty fill prefix, if required. Otherwise, it
22200 ;; will be computed again.
22201 (adaptive-fill-mode (not (equal fill-prefix ""))))
22202 (when fill-prefix (do-auto-fill))))))
22204 (defun org-comment-line-break-function (&optional soft)
22205 "Break line at point and indent, continuing comment if within one.
22206 The inserted newline is marked hard if variable
22207 `use-hard-newlines' is true, unless optional argument SOFT is
22208 non-nil."
22209 (if soft (insert-and-inherit ?\n) (newline 1))
22210 (save-excursion (forward-char -1) (delete-horizontal-space))
22211 (delete-horizontal-space)
22212 (indent-to-left-margin)
22213 (insert-before-markers-and-inherit fill-prefix))
22216 ;;; Fixed Width Areas
22218 (defun org-toggle-fixed-width ()
22219 "Toggle fixed-width markup.
22221 Add or remove fixed-width markup on current line, whenever it
22222 makes sense. Return an error otherwise.
22224 If a region is active and if it contains only fixed-width areas
22225 or blank lines, remove all fixed-width markup in it. If the
22226 region contains anything else, convert all non-fixed-width lines
22227 to fixed-width ones.
22229 Blank lines at the end of the region are ignored unless the
22230 region only contains such lines."
22231 (interactive)
22232 (if (not (org-region-active-p))
22233 ;; No region:
22235 ;; Remove fixed width marker only in a fixed-with element.
22237 ;; Add fixed width maker in paragraphs, in blank lines after
22238 ;; elements or at the beginning of a headline or an inlinetask,
22239 ;; and before any one-line elements (e.g., a clock).
22240 (progn
22241 (beginning-of-line)
22242 (let* ((element (org-element-at-point))
22243 (type (org-element-type element)))
22244 (cond
22245 ((and (eq type 'fixed-width)
22246 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22247 (replace-match
22248 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22249 ((and (memq type '(babel-call clock comment diary-sexp headline
22250 horizontal-rule keyword paragraph
22251 planning))
22252 (<= (org-element-property :post-affiliated element) (point)))
22253 (skip-chars-forward " \t")
22254 (insert ": "))
22255 ((and (looking-at-p "[ \t]*$")
22256 (or (eq type 'inlinetask)
22257 (save-excursion
22258 (skip-chars-forward " \r\t\n")
22259 (<= (org-element-property :end element) (point)))))
22260 (delete-region (point) (line-end-position))
22261 (org-indent-line)
22262 (insert ": "))
22263 (t (user-error "Cannot insert a fixed-width line here")))))
22264 ;; Region active.
22265 (let* ((begin (save-excursion
22266 (goto-char (region-beginning))
22267 (line-beginning-position)))
22268 (end (copy-marker
22269 (save-excursion
22270 (goto-char (region-end))
22271 (unless (eolp) (beginning-of-line))
22272 (if (save-excursion (re-search-backward "\\S-" begin t))
22273 (progn (skip-chars-backward " \r\t\n") (point))
22274 (point)))))
22275 (all-fixed-width-p
22276 (catch 'not-all-p
22277 (save-excursion
22278 (goto-char begin)
22279 (skip-chars-forward " \r\t\n")
22280 (when (eobp) (throw 'not-all-p nil))
22281 (while (< (point) end)
22282 (let ((element (org-element-at-point)))
22283 (if (eq (org-element-type element) 'fixed-width)
22284 (goto-char (org-element-property :end element))
22285 (throw 'not-all-p nil))))
22286 t))))
22287 (if all-fixed-width-p
22288 (save-excursion
22289 (goto-char begin)
22290 (while (< (point) end)
22291 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22292 (replace-match
22293 "" nil nil nil
22294 (if (= (line-end-position) (match-end 0)) 0 1)))
22295 (forward-line)))
22296 (let ((min-ind (point-max)))
22297 ;; Find minimum indentation across all lines.
22298 (save-excursion
22299 (goto-char begin)
22300 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22301 (setq min-ind 0)
22302 (catch 'zerop
22303 (while (< (point) end)
22304 (unless (looking-at-p "[ \t]*$")
22305 (let ((ind (org-get-indentation)))
22306 (setq min-ind (min min-ind ind))
22307 (when (zerop ind) (throw 'zerop t))))
22308 (forward-line)))))
22309 ;; Loop over all lines and add fixed-width markup everywhere
22310 ;; but in fixed-width lines.
22311 (save-excursion
22312 (goto-char begin)
22313 (while (< (point) end)
22314 (cond
22315 ((org-at-heading-p)
22316 (insert ": ")
22317 (forward-line)
22318 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22319 (insert ":")
22320 (forward-line)))
22321 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22322 (let* ((element (org-element-at-point))
22323 (element-end (org-element-property :end element)))
22324 (if (eq (org-element-type element) 'fixed-width)
22325 (progn (goto-char element-end)
22326 (skip-chars-backward " \r\t\n")
22327 (forward-line))
22328 (let ((limit (min end element-end)))
22329 (while (< (point) limit)
22330 (org-move-to-column min-ind t)
22331 (insert ": ")
22332 (forward-line))))))
22334 (org-move-to-column min-ind t)
22335 (insert ": ")
22336 (forward-line)))))))
22337 (set-marker end nil))))
22340 ;;; Blocks
22342 (defun org-block-map (function &optional start end)
22343 "Call FUNCTION at the head of all source blocks in the current buffer.
22344 Optional arguments START and END can be used to limit the range."
22345 (let ((start (or start (point-min)))
22346 (end (or end (point-max))))
22347 (save-excursion
22348 (goto-char start)
22349 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22350 (save-excursion
22351 (save-match-data
22352 (goto-char (match-beginning 0))
22353 (funcall function)))))))
22355 (defun org-next-block (arg &optional backward block-regexp)
22356 "Jump to the next block.
22358 With a prefix argument ARG, jump forward ARG many blocks.
22360 When BACKWARD is non-nil, jump to the previous block.
22362 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22363 Match data is set according to this regexp when the function
22364 returns.
22366 Return point at beginning of the opening line of found block.
22367 Throw an error if no block is found."
22368 (interactive "p")
22369 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22370 (case-fold-search t)
22371 (search-fn (if backward #'re-search-backward #'re-search-forward))
22372 (count (or arg 1))
22373 (origin (point))
22374 last-element)
22375 (if backward (beginning-of-line) (end-of-line))
22376 (while (and (> count 0) (funcall search-fn re nil t))
22377 (let ((element (save-excursion
22378 (goto-char (match-beginning 0))
22379 (save-match-data (org-element-at-point)))))
22380 (when (and (memq (org-element-type element)
22381 '(center-block comment-block dynamic-block
22382 example-block export-block quote-block
22383 special-block src-block verse-block))
22384 (<= (match-beginning 0)
22385 (org-element-property :post-affiliated element)))
22386 (setq last-element element)
22387 (cl-decf count))))
22388 (if (= count 0)
22389 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22390 (save-match-data (org-show-context)))
22391 (goto-char origin)
22392 (user-error "No %s code blocks" (if backward "previous" "further")))))
22394 (defun org-previous-block (arg &optional block-regexp)
22395 "Jump to the previous block.
22396 With a prefix argument ARG, jump backward ARG many source blocks.
22397 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22398 (interactive "p")
22399 (org-next-block arg t block-regexp))
22402 ;;; Comments
22404 ;; Org comments syntax is quite complex. It requires the entire line
22405 ;; to be just a comment. Also, even with the right syntax at the
22406 ;; beginning of line, some elements (e.g., verse-block or
22407 ;; example-block) don't accept comments. Usual Emacs comment commands
22408 ;; cannot cope with those requirements. Therefore, Org replaces them.
22410 ;; Org still relies on `comment-dwim', but cannot trust
22411 ;; `comment-only-p'. So, `comment-region-function' and
22412 ;; `uncomment-region-function' both point
22413 ;; to`org-comment-or-uncomment-region'. Eventually,
22414 ;; `org-insert-comment' takes care of insertion of comments at the
22415 ;; beginning of line.
22417 ;; `org-setup-comments-handling' install comments related variables
22418 ;; during `org-mode' initialization.
22420 (defun org-setup-comments-handling ()
22421 (interactive)
22422 (setq-local comment-use-syntax nil)
22423 (setq-local comment-start "# ")
22424 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22425 (setq-local comment-insert-comment-function 'org-insert-comment)
22426 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22427 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22429 (defun org-insert-comment ()
22430 "Insert an empty comment above current line.
22431 If the line is empty, insert comment at its beginning. When
22432 point is within a source block, comment according to the related
22433 major mode."
22434 (if (let ((element (org-element-at-point)))
22435 (and (eq (org-element-type element) 'src-block)
22436 (< (save-excursion
22437 (goto-char (org-element-property :post-affiliated element))
22438 (line-end-position))
22439 (point))
22440 (> (save-excursion
22441 (goto-char (org-element-property :end element))
22442 (skip-chars-backward " \r\t\n")
22443 (line-beginning-position))
22444 (point))))
22445 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22446 (beginning-of-line)
22447 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22448 (open-line 1))
22449 (org-indent-line)
22450 (insert "# ")))
22452 (defvar comment-empty-lines) ; From newcomment.el.
22453 (defun org-comment-or-uncomment-region (beg end &rest _)
22454 "Comment or uncomment each non-blank line in the region.
22455 Uncomment each non-blank line between BEG and END if it only
22456 contains commented lines. Otherwise, comment them. If region is
22457 strictly within a source block, use appropriate comment syntax."
22458 (if (let ((element (org-element-at-point)))
22459 (and (eq (org-element-type element) 'src-block)
22460 (< (save-excursion
22461 (goto-char (org-element-property :post-affiliated element))
22462 (line-end-position))
22463 beg)
22464 (>= (save-excursion
22465 (goto-char (org-element-property :end element))
22466 (skip-chars-backward " \r\t\n")
22467 (line-beginning-position))
22468 end)))
22469 ;; Translate region boundaries for the Org buffer to the source
22470 ;; buffer.
22471 (let ((offset (- end beg)))
22472 (save-excursion
22473 (goto-char beg)
22474 (org-babel-do-in-edit-buffer
22475 (comment-or-uncomment-region (point) (+ offset (point))))))
22476 (save-restriction
22477 ;; Restrict region
22478 (narrow-to-region (save-excursion (goto-char beg)
22479 (skip-chars-forward " \r\t\n" end)
22480 (line-beginning-position))
22481 (save-excursion (goto-char end)
22482 (skip-chars-backward " \r\t\n" beg)
22483 (line-end-position)))
22484 (let ((uncommentp
22485 ;; UNCOMMENTP is non-nil when every non blank line between
22486 ;; BEG and END is a comment.
22487 (save-excursion
22488 (goto-char (point-min))
22489 (while (and (not (eobp))
22490 (let ((element (org-element-at-point)))
22491 (and (eq (org-element-type element) 'comment)
22492 (goto-char (min (point-max)
22493 (org-element-property
22494 :end element)))))))
22495 (eobp))))
22496 (if uncommentp
22497 ;; Only blank lines and comments in region: uncomment it.
22498 (save-excursion
22499 (goto-char (point-min))
22500 (while (not (eobp))
22501 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22502 (replace-match "" nil nil nil 1))
22503 (forward-line)))
22504 ;; Comment each line in region.
22505 (let ((min-indent (point-max)))
22506 ;; First find the minimum indentation across all lines.
22507 (save-excursion
22508 (goto-char (point-min))
22509 (while (and (not (eobp)) (not (zerop min-indent)))
22510 (unless (looking-at "[ \t]*$")
22511 (setq min-indent (min min-indent (current-indentation))))
22512 (forward-line)))
22513 ;; Then loop over all lines.
22514 (save-excursion
22515 (goto-char (point-min))
22516 (while (not (eobp))
22517 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22518 ;; Don't get fooled by invisible text (e.g. link path)
22519 ;; when moving to column MIN-INDENT.
22520 (let ((buffer-invisibility-spec nil))
22521 (org-move-to-column min-indent t))
22522 (insert comment-start))
22523 (forward-line)))))))))
22525 (defun org-comment-dwim (_arg)
22526 "Call the comment command you mean.
22527 Call `org-toggle-comment' if on a heading, otherwise call
22528 `comment-dwim', within a source edit buffer if needed."
22529 (interactive "*P")
22530 (cond ((org-at-heading-p)
22531 (call-interactively #'org-toggle-comment))
22532 ((org-in-src-block-p)
22533 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22534 (t (call-interactively #'comment-dwim))))
22537 ;;; Timestamps API
22539 ;; This section contains tools to operate on, or create, timestamp
22540 ;; objects, as returned by, e.g. `org-element-context'.
22542 (defun org-timestamp-from-string (s)
22543 "Convert Org timestamp S, as a string, into a timestamp object.
22544 Return nil if S is not a valid timestamp string."
22545 (when (org-string-nw-p s)
22546 (with-temp-buffer
22547 (save-excursion (insert s))
22548 (org-element-timestamp-parser))))
22550 (defun org-timestamp-from-time (time &optional with-time inactive)
22551 "Convert a time value into a timestamp object.
22553 TIME is an Emacs internal time representation, as returned, e.g.,
22554 by `current-time'.
22556 When optional argument WITH-TIME is non-nil, return a timestamp
22557 object with a time part, i.e., with hours and minutes.
22559 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22560 return an active timestamp."
22561 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22562 (org-element-create 'timestamp
22563 (list :type (if inactive 'inactive 'active)
22564 :year-start year
22565 :month-start month
22566 :day-start day
22567 :hour-start (and with-time hour)
22568 :minute-start (and with-time minute)))))
22570 (defun org-timestamp-to-time (timestamp &optional end)
22571 "Convert TIMESTAMP object into an Emacs internal time value.
22572 Use end of date range or time range when END is non-nil.
22573 Otherwise, use its start."
22574 (apply #'encode-time
22575 (cons 0
22576 (mapcar
22577 (lambda (prop) (or (org-element-property prop timestamp) 0))
22578 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22579 '(:minute-start :hour-start :day-start :month-start
22580 :year-start))))))
22582 (defun org-timestamp-has-time-p (timestamp)
22583 "Non-nil when TIMESTAMP has a time specified."
22584 (org-element-property :hour-start timestamp))
22586 (defun org-timestamp-format (timestamp format &optional end utc)
22587 "Format a TIMESTAMP object into a string.
22589 FORMAT is a format specifier to be passed to
22590 `format-time-string'.
22592 When optional argument END is non-nil, use end of date-range or
22593 time-range, if possible.
22595 When optional argument UTC is non-nil, time is be expressed as
22596 Universal Time."
22597 (format-time-string format (org-timestamp-to-time timestamp end)
22598 (and utc t)))
22600 (defun org-timestamp-split-range (timestamp &optional end)
22601 "Extract a TIMESTAMP object from a date or time range.
22603 END, when non-nil, means extract the end of the range.
22604 Otherwise, extract its start.
22606 Return a new timestamp object."
22607 (let ((type (org-element-property :type timestamp)))
22608 (if (memq type '(active inactive diary)) timestamp
22609 (let ((split-ts (org-element-copy timestamp)))
22610 ;; Set new type.
22611 (org-element-put-property
22612 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22613 ;; Copy start properties over end properties if END is
22614 ;; non-nil. Otherwise, copy end properties over `start' ones.
22615 (let ((p-alist '((:minute-start . :minute-end)
22616 (:hour-start . :hour-end)
22617 (:day-start . :day-end)
22618 (:month-start . :month-end)
22619 (:year-start . :year-end))))
22620 (dolist (p-cell p-alist)
22621 (org-element-put-property
22622 split-ts
22623 (funcall (if end #'car #'cdr) p-cell)
22624 (org-element-property
22625 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22626 ;; Eventually refresh `:raw-value'.
22627 (org-element-put-property split-ts :raw-value nil)
22628 (org-element-put-property
22629 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22631 (defun org-timestamp-translate (timestamp &optional boundary)
22632 "Translate TIMESTAMP object to custom format.
22634 Format string is defined in `org-time-stamp-custom-formats',
22635 which see.
22637 When optional argument BOUNDARY is non-nil, it is either the
22638 symbol `start' or `end'. In this case, only translate the
22639 starting or ending part of TIMESTAMP if it is a date or time
22640 range. Otherwise, translate both parts.
22642 Return timestamp as-is if `org-display-custom-times' is nil or if
22643 it has a `diary' type."
22644 (let ((type (org-element-property :type timestamp)))
22645 (if (or (not org-display-custom-times) (eq type 'diary))
22646 (org-element-interpret-data timestamp)
22647 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22648 org-time-stamp-custom-formats)))
22649 (if (and (not boundary) (memq type '(active-range inactive-range)))
22650 (concat (org-timestamp-format timestamp fmt)
22651 "--"
22652 (org-timestamp-format timestamp fmt t))
22653 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22655 ;;; Other stuff
22657 (defvar reftex-docstruct-symbol)
22658 (defvar org--rds)
22660 (defun org-reftex-citation ()
22661 "Use reftex-citation to insert a citation into the buffer.
22662 This looks for a line like
22664 #+BIBLIOGRAPHY: foo plain option:-d
22666 and derives from it that foo.bib is the bibliography file relevant
22667 for this document. It then installs the necessary environment for RefTeX
22668 to work in this buffer and calls `reftex-citation' to insert a citation
22669 into the buffer.
22671 Export of such citations to both LaTeX and HTML is handled by the contributed
22672 package ox-bibtex by Taru Karttunen."
22673 (interactive)
22674 (let ((reftex-docstruct-symbol 'org--rds)
22675 org--rds bib)
22676 (org-with-wide-buffer
22677 (let ((case-fold-search t)
22678 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22679 (if (not (save-excursion
22680 (or (re-search-forward re nil t)
22681 (re-search-backward re nil t))))
22682 (user-error "No bibliography defined in file")
22683 (setq bib (concat (match-string 1) ".bib")
22684 org--rds (list (list 'bib bib))))))
22685 (call-interactively 'reftex-citation)))
22687 ;;;; Functions extending outline functionality
22689 (defun org-beginning-of-line (&optional n)
22690 "Go to the beginning of the current visible line.
22692 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22693 symbol `reversed', on the first attempt move to where the
22694 headline text starts, and only move to beginning of line when the
22695 cursor is already before the start of the text of the headline.
22697 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22698 start of the text on the second attempt.
22700 With argument N not nil or 1, move forward N - 1 lines first."
22701 (interactive "^p")
22702 (let ((origin (point))
22703 (special (pcase org-special-ctrl-a/e
22704 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22705 deactivate-mark)
22706 ;; First move to a visible line.
22707 (if (bound-and-true-p visual-line-mode)
22708 (beginning-of-visual-line n)
22709 (move-beginning-of-line n)
22710 ;; `move-beginning-of-line' may leave point after invisible
22711 ;; characters if line starts with such of these (e.g., with
22712 ;; a link at column 0). Really move to the beginning of the
22713 ;; current visible line.
22714 (beginning-of-line))
22715 (cond
22716 ;; No special behavior. Point is already at the beginning of
22717 ;; a line, logical or visual.
22718 ((not special))
22719 ;; `beginning-of-visual-line' left point before logical beginning
22720 ;; of line: point is at the beginning of a visual line. Bail
22721 ;; out.
22722 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22723 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22724 ;; At a headline, special position is before the title, but
22725 ;; after any TODO keyword or priority cookie.
22726 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22727 (line-end-position)))
22728 (bol (point)))
22729 (if (eq special 'reversed)
22730 (when (and (= origin bol) (eq last-command this-command))
22731 (goto-char refpos))
22732 (when (or (> origin refpos) (= origin bol))
22733 (goto-char refpos)))))
22734 ((and (looking-at org-list-full-item-re)
22735 (memq (org-element-type (save-match-data (org-element-at-point)))
22736 '(item plain-list)))
22737 ;; Set special position at first white space character after
22738 ;; bullet, and check-box, if any.
22739 (let ((after-bullet
22740 (let ((box (match-end 3)))
22741 (cond ((not box) (match-end 1))
22742 ((eq (char-after box) ?\s) (1+ box))
22743 (t box)))))
22744 (if (eq special 'reversed)
22745 (when (and (= (point) origin) (eq last-command this-command))
22746 (goto-char after-bullet))
22747 (when (or (> origin after-bullet) (= (point) origin))
22748 (goto-char after-bullet)))))
22749 ;; No special context. Point is already at beginning of line.
22750 (t nil))))
22752 (defun org-end-of-line (&optional n)
22753 "Go to the end of the line, but before ellipsis, if any.
22755 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22756 symbol `reversed', ignore tags on the first attempt, and only
22757 move to after the tags when the cursor is already beyond the end
22758 of the headline.
22760 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22761 on the second attempt.
22763 With argument N not nil or 1, move forward N - 1 lines first."
22764 (interactive "^p")
22765 (let ((origin (point))
22766 (special (pcase org-special-ctrl-a/e
22767 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22768 deactivate-mark)
22769 ;; First move to a visible line.
22770 (if (bound-and-true-p visual-line-mode)
22771 (beginning-of-visual-line n)
22772 (move-beginning-of-line n))
22773 (cond
22774 ;; At a headline, with tags.
22775 ((and special
22776 (save-excursion
22777 (beginning-of-line)
22778 (let ((case-fold-search nil))
22779 (looking-at org-complex-heading-regexp)))
22780 (match-end 5))
22781 (let ((tags (save-excursion
22782 (goto-char (match-beginning 5))
22783 (skip-chars-backward " \t")
22784 (point)))
22785 (visual-end (and (bound-and-true-p visual-line-mode)
22786 (save-excursion
22787 (end-of-visual-line)
22788 (point)))))
22789 ;; If `end-of-visual-line' brings us before end of line or
22790 ;; even tags, i.e., the headline spans over multiple visual
22791 ;; lines, move there.
22792 (cond ((and visual-end
22793 (< visual-end tags)
22794 (<= origin visual-end))
22795 (goto-char visual-end))
22796 ((eq special 'reversed)
22797 (if (and (= origin (line-end-position))
22798 (eq this-command last-command))
22799 (goto-char tags)
22800 (end-of-line)))
22802 (if (or (< origin tags) (= origin (line-end-position)))
22803 (goto-char tags)
22804 (end-of-line))))))
22805 ((bound-and-true-p visual-line-mode)
22806 (let ((bol (line-beginning-position)))
22807 (end-of-visual-line)
22808 ;; If `end-of-visual-line' gets us past the ellipsis at the
22809 ;; end of a line, backtrack and use `end-of-line' instead.
22810 (when (/= bol (line-beginning-position))
22811 (goto-char bol)
22812 (end-of-line))))
22813 (t (end-of-line)))))
22815 (defun org-backward-sentence (&optional _arg)
22816 "Go to beginning of sentence, or beginning of table field.
22817 This will call `backward-sentence' or `org-table-beginning-of-field',
22818 depending on context."
22819 (interactive)
22820 (let* ((element (org-element-at-point))
22821 (contents-begin (org-element-property :contents-begin element))
22822 (table (org-element-lineage element '(table) t)))
22823 (if (and table
22824 (> (point) contents-begin)
22825 (<= (point) (org-element-property :contents-end table)))
22826 (call-interactively #'org-table-beginning-of-field)
22827 (save-restriction
22828 (when (and contents-begin
22829 (< (point-min) contents-begin)
22830 (> (point) contents-begin))
22831 (narrow-to-region contents-begin
22832 (org-element-property :contents-end element)))
22833 (call-interactively #'backward-sentence)))))
22835 (defun org-forward-sentence (&optional _arg)
22836 "Go to end of sentence, or end of table field.
22837 This will call `forward-sentence' or `org-table-end-of-field',
22838 depending on context."
22839 (interactive)
22840 (if (and (org-at-heading-p)
22841 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22842 (save-restriction
22843 (narrow-to-region (line-beginning-position) (line-end-position))
22844 (call-interactively #'forward-sentence))
22845 (let* ((element (org-element-at-point))
22846 (contents-end (org-element-property :contents-end element))
22847 (table (org-element-lineage element '(table) t)))
22848 (if (and table
22849 (>= (point) (org-element-property :contents-begin table))
22850 (< (point) contents-end))
22851 (call-interactively #'org-table-end-of-field)
22852 (save-restriction
22853 (when (and contents-end
22854 (> (point-max) contents-end)
22855 ;; Skip blank lines between elements.
22856 (< (org-element-property :end element)
22857 (save-excursion (goto-char contents-end)
22858 (skip-chars-forward " \r\t\n"))))
22859 (narrow-to-region (org-element-property :contents-begin element)
22860 contents-end))
22861 ;; End of heading is considered as the end of a sentence.
22862 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22863 (call-interactively #'forward-sentence)))))))
22865 (defun org-kill-line (&optional _arg)
22866 "Kill line, to tags or end of line."
22867 (interactive)
22868 (cond
22869 ((or (not org-special-ctrl-k)
22870 (bolp)
22871 (not (org-at-heading-p)))
22872 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22873 org-ctrl-k-protect-subtree
22874 (or (eq org-ctrl-k-protect-subtree 'error)
22875 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22876 (user-error
22877 (substitute-command-keys
22878 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22879 (call-interactively
22880 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22881 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22882 (kill-region (point) (match-beginning 1))
22883 (org-set-tags nil t))
22884 (t (kill-region (point) (point-at-eol)))))
22886 (defun org-yank (&optional arg)
22887 "Yank. If the kill is a subtree, treat it specially.
22888 This command will look at the current kill and check if is a single
22889 subtree, or a series of subtrees[1]. If it passes the test, and if the
22890 cursor is at the beginning of a line or after the stars of a currently
22891 empty headline, then the yank is handled specially. How exactly depends
22892 on the value of the following variables.
22894 `org-yank-folded-subtrees'
22895 By default, this variable is non-nil, which results in
22896 subtree(s) being folded after insertion, except if doing so
22897 would swallow text after the yanked text.
22899 `org-yank-adjusted-subtrees'
22900 When non-nil (the default value is nil), the subtree will be
22901 promoted or demoted in order to fit into the local outline tree
22902 structure, which means that the level will be adjusted so that it
22903 becomes the smaller one of the two *visible* surrounding headings.
22905 Any prefix to this command will cause `yank' to be called directly with
22906 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22907 will just
22908 plainly yank the text as it is.
22910 \[1] The test checks if the first non-white line is a heading
22911 and if there are no other headings with fewer stars."
22912 (interactive "P")
22913 (org-yank-generic 'yank arg))
22915 (defun org-yank-generic (command arg)
22916 "Perform some yank-like command.
22918 This function implements the behavior described in the `org-yank'
22919 documentation. However, it has been generalized to work for any
22920 interactive command with similar behavior."
22922 ;; pretend to be command COMMAND
22923 (setq this-command command)
22925 (if arg
22926 (call-interactively command)
22928 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22929 (and (org-kill-is-subtree-p)
22930 (or (bolp)
22931 (and (looking-at "[ \t]*$")
22932 (string-match
22933 "\\`\\*+\\'"
22934 (buffer-substring (point-at-bol) (point)))))))
22935 swallowp)
22936 (cond
22937 ((and subtreep org-yank-folded-subtrees)
22938 (let ((beg (point))
22939 end)
22940 (if (and subtreep org-yank-adjusted-subtrees)
22941 (org-paste-subtree nil nil 'for-yank)
22942 (call-interactively command))
22944 (setq end (point))
22945 (goto-char beg)
22946 (when (and (bolp) subtreep
22947 (not (setq swallowp
22948 (org-yank-folding-would-swallow-text beg end))))
22949 (org-with-limited-levels
22950 (or (looking-at org-outline-regexp)
22951 (re-search-forward org-outline-regexp-bol end t))
22952 (while (and (< (point) end) (looking-at org-outline-regexp))
22953 (outline-hide-subtree)
22954 (org-cycle-show-empty-lines 'folded)
22955 (condition-case nil
22956 (outline-forward-same-level 1)
22957 (error (goto-char end))))))
22958 (when swallowp
22959 (message
22960 "Inserted text not folded because that would swallow text"))
22962 (goto-char end)
22963 (skip-chars-forward " \t\n\r")
22964 (beginning-of-line 1)
22965 (push-mark beg 'nomsg)))
22966 ((and subtreep org-yank-adjusted-subtrees)
22967 (let ((beg (point-at-bol)))
22968 (org-paste-subtree nil nil 'for-yank)
22969 (push-mark beg 'nomsg)))
22971 (call-interactively command))))))
22973 (defun org-yank-folding-would-swallow-text (beg end)
22974 "Would hide-subtree at BEG swallow any text after END?"
22975 (let (level)
22976 (org-with-limited-levels
22977 (save-excursion
22978 (goto-char beg)
22979 (when (or (looking-at org-outline-regexp)
22980 (re-search-forward org-outline-regexp-bol end t))
22981 (setq level (org-outline-level)))
22982 (goto-char end)
22983 (skip-chars-forward " \t\r\n\v\f")
22984 (not (or (eobp)
22985 (and (bolp) (looking-at-p org-outline-regexp)
22986 (<= (org-outline-level) level))))))))
22988 (defun org-back-to-heading (&optional invisible-ok)
22989 "Call `outline-back-to-heading', but provide a better error message."
22990 (condition-case nil
22991 (outline-back-to-heading invisible-ok)
22992 (error (error "Before first headline at position %d in buffer %s"
22993 (point) (current-buffer)))))
22995 (defun org-before-first-heading-p ()
22996 "Before first heading?"
22997 (save-excursion
22998 (end-of-line)
22999 (null (re-search-backward org-outline-regexp-bol nil t))))
23001 (defun org-at-heading-p (&optional ignored)
23002 (outline-on-heading-p t))
23004 (defun org-in-commented-heading-p (&optional no-inheritance)
23005 "Non-nil if point is under a commented heading.
23006 This function also checks ancestors of the current headline,
23007 unless optional argument NO-INHERITANCE is non-nil."
23008 (cond
23009 ((org-before-first-heading-p) nil)
23010 ((let ((headline (nth 4 (org-heading-components))))
23011 (and headline
23012 (let ((case-fold-search nil))
23013 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23014 headline)))))
23015 (no-inheritance nil)
23017 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23019 (defun org-at-comment-p nil
23020 "Is cursor in a commented line?"
23021 (save-excursion
23022 (save-match-data
23023 (beginning-of-line)
23024 (looking-at "^[ \t]*# "))))
23026 (defun org-at-drawer-p nil
23027 "Is cursor at a drawer keyword?"
23028 (save-excursion
23029 (move-beginning-of-line 1)
23030 (looking-at org-drawer-regexp)))
23032 (defun org-at-block-p nil
23033 "Is cursor at a block keyword?"
23034 (save-excursion
23035 (move-beginning-of-line 1)
23036 (looking-at org-block-regexp)))
23038 (defun org-point-at-end-of-empty-headline ()
23039 "If point is at the end of an empty headline, return t, else nil.
23040 If the heading only contains a TODO keyword, it is still still considered
23041 empty."
23042 (let ((case-fold-search nil))
23043 (and (looking-at "[ \t]*$")
23044 org-todo-line-regexp
23045 (save-excursion
23046 (beginning-of-line)
23047 (looking-at org-todo-line-regexp)
23048 (string= (match-string 3) "")))))
23050 (defun org-at-heading-or-item-p ()
23051 (or (org-at-heading-p) (org-at-item-p)))
23053 (defun org-at-target-p ()
23054 (or (org-in-regexp org-radio-target-regexp)
23055 (org-in-regexp org-target-regexp)))
23056 ;; Compatibility alias with Org versions < 7.8.03
23057 (defalias 'org-on-target-p 'org-at-target-p)
23059 (defun org-up-heading-all (arg)
23060 "Move to the heading line of which the present line is a subheading.
23061 This function considers both visible and invisible heading lines.
23062 With argument, move up ARG levels."
23063 (outline-up-heading arg t))
23065 (defun org-up-heading-safe ()
23066 "Move to the heading line of which the present line is a subheading.
23067 This version will not throw an error. It will return the level of the
23068 headline found, or nil if no higher level is found.
23070 Also, this function will be a lot faster than `outline-up-heading',
23071 because it relies on stars being the outline starters. This can really
23072 make a significant difference in outlines with very many siblings."
23073 (when (ignore-errors (org-back-to-heading t))
23074 (let ((level-up (1- (funcall outline-level))))
23075 (and (> level-up 0)
23076 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23077 (funcall outline-level)))))
23079 (defun org-first-sibling-p ()
23080 "Is this heading the first child of its parents?"
23081 (interactive)
23082 (let ((re org-outline-regexp-bol)
23083 level l)
23084 (unless (org-at-heading-p t)
23085 (user-error "Not at a heading"))
23086 (setq level (funcall outline-level))
23087 (save-excursion
23088 (if (not (re-search-backward re nil t))
23090 (setq l (funcall outline-level))
23091 (< l level)))))
23093 (defun org-goto-sibling (&optional previous)
23094 "Goto the next sibling, even if it is invisible.
23095 When PREVIOUS is set, go to the previous sibling instead. Returns t
23096 when a sibling was found. When none is found, return nil and don't
23097 move point."
23098 (let ((fun (if previous 're-search-backward 're-search-forward))
23099 (pos (point))
23100 (re org-outline-regexp-bol)
23101 level l)
23102 (when (ignore-errors (org-back-to-heading t))
23103 (setq level (funcall outline-level))
23104 (catch 'exit
23105 (or previous (forward-char 1))
23106 (while (funcall fun re nil t)
23107 (setq l (funcall outline-level))
23108 (when (< l level) (goto-char pos) (throw 'exit nil))
23109 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23110 (goto-char pos)
23111 nil))))
23113 (defun org-show-siblings ()
23114 "Show all siblings of the current headline."
23115 (save-excursion
23116 (while (org-goto-sibling) (org-flag-heading nil)))
23117 (save-excursion
23118 (while (org-goto-sibling 'previous)
23119 (org-flag-heading nil))))
23121 (defun org-goto-first-child ()
23122 "Goto the first child, even if it is invisible.
23123 Return t when a child was found. Otherwise don't move point and
23124 return nil."
23125 (let (level (pos (point)) (re org-outline-regexp-bol))
23126 (when (ignore-errors (org-back-to-heading t))
23127 (setq level (outline-level))
23128 (forward-char 1)
23129 (if (and (re-search-forward re nil t) (> (outline-level) level))
23130 (progn (goto-char (match-beginning 0)) t)
23131 (goto-char pos) nil))))
23133 (defun org-show-hidden-entry ()
23134 "Show an entry where even the heading is hidden."
23135 (save-excursion
23136 (org-show-entry)))
23138 (defun org-flag-heading (flag &optional entry)
23139 "Flag the current heading. FLAG non-nil means make invisible.
23140 When ENTRY is non-nil, show the entire entry."
23141 (save-excursion
23142 (org-back-to-heading t)
23143 ;; Check if we should show the entire entry
23144 (if (not entry)
23145 (org-flag-region
23146 (line-end-position 0) (line-end-position) flag 'outline)
23147 (org-show-entry)
23148 (save-excursion
23149 (and (outline-next-heading)
23150 (org-flag-heading nil))))))
23152 (defun org-get-next-sibling ()
23153 "Move to next heading of the same level, and return point.
23154 If there is no such heading, return nil.
23155 This is like outline-next-sibling, but invisible headings are ok."
23156 (let ((level (funcall outline-level)))
23157 (outline-next-heading)
23158 (while (and (not (eobp)) (> (funcall outline-level) level))
23159 (outline-next-heading))
23160 (unless (or (eobp) (< (funcall outline-level) level))
23161 (point))))
23163 (defun org-get-last-sibling ()
23164 "Move to previous heading of the same level, and return point.
23165 If there is no such heading, return nil."
23166 (let ((opoint (point))
23167 (level (funcall outline-level)))
23168 (outline-previous-heading)
23169 (when (and (/= (point) opoint) (outline-on-heading-p t))
23170 (while (and (> (funcall outline-level) level)
23171 (not (bobp)))
23172 (outline-previous-heading))
23173 (unless (< (funcall outline-level) level)
23174 (point)))))
23176 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23177 "Goto to the end of a subtree."
23178 ;; This contains an exact copy of the original function, but it uses
23179 ;; `org-back-to-heading', to make it work also in invisible
23180 ;; trees. And is uses an invisible-ok argument.
23181 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23182 ;; Furthermore, when used inside Org, finding the end of a large subtree
23183 ;; with many children and grandchildren etc, this can be much faster
23184 ;; than the outline version.
23185 (org-back-to-heading invisible-ok)
23186 (let ((first t)
23187 (level (funcall outline-level)))
23188 (if (and (derived-mode-p 'org-mode) (< level 1000))
23189 ;; A true heading (not a plain list item), in Org
23190 ;; This means we can easily find the end by looking
23191 ;; only for the right number of stars. Using a regexp to do
23192 ;; this is so much faster than using a Lisp loop.
23193 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23194 (forward-char 1)
23195 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23196 ;; something else, do it the slow way
23197 (while (and (not (eobp))
23198 (or first (> (funcall outline-level) level)))
23199 (setq first nil)
23200 (outline-next-heading)))
23201 (unless to-heading
23202 (when (memq (preceding-char) '(?\n ?\^M))
23203 ;; Go to end of line before heading
23204 (forward-char -1)
23205 (when (memq (preceding-char) '(?\n ?\^M))
23206 ;; leave blank line before heading
23207 (forward-char -1)))))
23208 (point))
23210 (defun org-end-of-meta-data (&optional full)
23211 "Skip planning line and properties drawer in current entry.
23212 When optional argument FULL is non-nil, also skip empty lines,
23213 clocking lines and regular drawers at the beginning of the
23214 entry."
23215 (org-back-to-heading t)
23216 (forward-line)
23217 (when (looking-at-p org-planning-line-re) (forward-line))
23218 (when (looking-at org-property-drawer-re)
23219 (goto-char (match-end 0))
23220 (forward-line))
23221 (when (and full (not (org-at-heading-p)))
23222 (catch 'exit
23223 (let ((end (save-excursion (outline-next-heading) (point)))
23224 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23225 (while (not (eobp))
23226 (cond ((looking-at-p org-drawer-regexp)
23227 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23228 (forward-line)
23229 (throw 'exit t)))
23230 ((looking-at-p re) (forward-line))
23231 (t (throw 'exit t))))))))
23233 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23234 "Move forward to the ARG'th subheading at same level as this one.
23235 Stop at the first and last subheadings of a superior heading.
23236 Normally this only looks at visible headings, but when INVISIBLE-OK is
23237 non-nil it will also look at invisible ones."
23238 (interactive "p")
23239 (let ((backward? (and arg (< arg 0))))
23240 (if (org-before-first-heading-p)
23241 (if backward? (goto-char (point-min)) (outline-next-heading))
23242 (org-back-to-heading invisible-ok)
23243 (unless backward? (end-of-line)) ;do not match current headline
23244 (let ((level (- (match-end 0) (match-beginning 0) 1))
23245 (f (if backward? #'re-search-backward #'re-search-forward))
23246 (count (if arg (abs arg) 1))
23247 (result (point)))
23248 (while (and (> count 0)
23249 (funcall f org-outline-regexp-bol nil 'move))
23250 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23251 (cond ((< l level) (setq count 0))
23252 ((and (= l level)
23253 (or invisible-ok
23254 (not (org-invisible-p
23255 (line-beginning-position)))))
23256 (cl-decf count)
23257 (when (= l level) (setq result (point)))))))
23258 (goto-char result))
23259 (beginning-of-line))))
23261 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23262 "Move backward to the ARG'th subheading at same level as this one.
23263 Stop at the first and last subheadings of a superior heading."
23264 (interactive "p")
23265 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23267 (defun org-next-visible-heading (arg)
23268 "Move to the next visible heading.
23270 This function wraps `outline-next-visible-heading' with
23271 `org-with-limited-levels' in order to skip over inline tasks and
23272 respect customization of `org-odd-levels-only'."
23273 (interactive "p")
23274 (org-with-limited-levels
23275 (outline-next-visible-heading arg)))
23277 (defun org-previous-visible-heading (arg)
23278 "Move to the previous visible heading.
23280 This function wraps `outline-previous-visible-heading' with
23281 `org-with-limited-levels' in order to skip over inline tasks and
23282 respect customization of `org-odd-levels-only'."
23283 (interactive "p")
23284 (org-with-limited-levels
23285 (outline-previous-visible-heading arg)))
23287 (defun org-forward-paragraph ()
23288 "Move forward to beginning of next paragraph or equivalent.
23290 The function moves point to the beginning of the next visible
23291 structural element, which can be a paragraph, a table, a list
23292 item, etc. It also provides some special moves for convenience:
23294 - On an affiliated keyword, jump to the beginning of the
23295 relative element.
23296 - On an item or a footnote definition, move to the second
23297 element inside, if any.
23298 - On a table or a property drawer, jump after it.
23299 - On a verse or source block, stop after blank lines."
23300 (interactive)
23301 (unless (eobp)
23302 (let* ((deactivate-mark nil)
23303 (element (org-element-at-point))
23304 (type (org-element-type element))
23305 (post-affiliated (org-element-property :post-affiliated element))
23306 (contents-begin (org-element-property :contents-begin element))
23307 (contents-end (org-element-property :contents-end element))
23308 (end (let ((end (org-element-property :end element)) (parent element))
23309 (while (and (setq parent (org-element-property :parent parent))
23310 (= (org-element-property :contents-end parent) end))
23311 (setq end (org-element-property :end parent)))
23312 end)))
23313 (cond ((not element)
23314 (skip-chars-forward " \r\t\n")
23315 (or (eobp) (beginning-of-line)))
23316 ;; On affiliated keywords, move to element's beginning.
23317 ((< (point) post-affiliated)
23318 (goto-char post-affiliated))
23319 ;; At a table row, move to the end of the table. Similarly,
23320 ;; at a node property, move to the end of the property
23321 ;; drawer.
23322 ((memq type '(node-property table-row))
23323 (goto-char (org-element-property
23324 :end (org-element-property :parent element))))
23325 ((memq type '(property-drawer table)) (goto-char end))
23326 ;; Consider blank lines as separators in verse and source
23327 ;; blocks to ease editing.
23328 ((memq type '(src-block verse-block))
23329 (when (eq type 'src-block)
23330 (setq contents-end
23331 (save-excursion (goto-char end)
23332 (skip-chars-backward " \r\t\n")
23333 (line-beginning-position))))
23334 (beginning-of-line)
23335 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23336 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23337 (goto-char end)
23338 (skip-chars-forward " \r\t\n")
23339 (if (= (point) contents-end) (goto-char end)
23340 (beginning-of-line))))
23341 ;; With no contents, just skip element.
23342 ((not contents-begin) (goto-char end))
23343 ;; If contents are invisible, skip the element altogether.
23344 ((org-invisible-p (line-end-position))
23345 (cl-case type
23346 (headline
23347 (org-with-limited-levels (outline-next-visible-heading 1)))
23348 ;; At a plain list, make sure we move to the next item
23349 ;; instead of skipping the whole list.
23350 (plain-list (forward-char)
23351 (org-forward-paragraph))
23352 (otherwise (goto-char end))))
23353 ((>= (point) contents-end) (goto-char end))
23354 ((>= (point) contents-begin)
23355 ;; This can only happen on paragraphs and plain lists.
23356 (cl-case type
23357 (paragraph (goto-char end))
23358 ;; At a plain list, try to move to second element in
23359 ;; first item, if possible.
23360 (plain-list (end-of-line)
23361 (org-forward-paragraph))))
23362 ;; When contents start on the middle of a line (e.g. in
23363 ;; items and footnote definitions), try to reach first
23364 ;; element starting after current line.
23365 ((> (line-end-position) contents-begin)
23366 (end-of-line)
23367 (org-forward-paragraph))
23368 (t (goto-char contents-begin))))))
23370 (defun org-backward-paragraph ()
23371 "Move backward to start of previous paragraph or equivalent.
23373 The function moves point to the beginning of the current
23374 structural element, which can be a paragraph, a table, a list
23375 item, etc., or to the beginning of the previous visible one if
23376 point is already there. It also provides some special moves for
23377 convenience:
23379 - On an affiliated keyword, jump to the first one.
23380 - On a table or a property drawer, move to its beginning.
23381 - On comment, example, export, src and verse blocks, stop
23382 before blank lines."
23383 (interactive)
23384 (unless (bobp)
23385 (let* ((deactivate-mark nil)
23386 (element (org-element-at-point))
23387 (type (org-element-type element))
23388 (contents-end (org-element-property :contents-end element))
23389 (post-affiliated (org-element-property :post-affiliated element))
23390 (begin (org-element-property :begin element))
23391 (special? ;blocks handled specially
23392 (memq type '(comment-block example-block export-block src-block
23393 verse-block)))
23394 (contents-begin
23395 (if special?
23396 ;; These types have no proper contents. Fake line
23397 ;; below the block opening line as contents beginning.
23398 (save-excursion (goto-char begin) (line-beginning-position 2))
23399 (org-element-property :contents-begin element))))
23400 (cond
23401 ((not element) (goto-char (point-min)))
23402 ((= (point) begin)
23403 (backward-char)
23404 (org-backward-paragraph))
23405 ((<= (point) post-affiliated) (goto-char begin))
23406 ;; Special behavior: on a table or a property drawer, move to
23407 ;; its beginning.
23408 ((memq type '(node-property table-row))
23409 (goto-char (org-element-property
23410 :post-affiliated (org-element-property :parent element))))
23411 (special?
23412 (if (<= (point) contents-begin) (goto-char post-affiliated)
23413 ;; Inside a verse block, see blank lines as paragraph
23414 ;; separators.
23415 (let ((origin (point)))
23416 (skip-chars-backward " \r\t\n" contents-begin)
23417 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23418 (skip-chars-forward " \r\t\n" origin)
23419 (if (= (point) origin) (goto-char contents-begin)
23420 (beginning-of-line))))))
23421 ((eq type 'paragraph) (goto-char contents-begin)
23422 ;; When at first paragraph in an item or a footnote definition,
23423 ;; move directly to beginning of line.
23424 (let ((parent-contents
23425 (org-element-property
23426 :contents-begin (org-element-property :parent element))))
23427 (when (and parent-contents (= parent-contents contents-begin))
23428 (beginning-of-line))))
23429 ;; At the end of a greater element, move to the beginning of
23430 ;; the last element within.
23431 ((and contents-end (>= (point) contents-end))
23432 (goto-char (1- contents-end))
23433 (org-backward-paragraph))
23434 (t (goto-char (or post-affiliated begin))))
23435 ;; Ensure we never leave point invisible.
23436 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23438 (defun org-forward-element ()
23439 "Move forward by one element.
23440 Move to the next element at the same level, when possible."
23441 (interactive)
23442 (cond ((eobp) (user-error "Cannot move further down"))
23443 ((org-with-limited-levels (org-at-heading-p))
23444 (let ((origin (point)))
23445 (goto-char (org-end-of-subtree nil t))
23446 (unless (org-with-limited-levels (org-at-heading-p))
23447 (goto-char origin)
23448 (user-error "Cannot move further down"))))
23450 (let* ((elem (org-element-at-point))
23451 (end (org-element-property :end elem))
23452 (parent (org-element-property :parent elem)))
23453 (cond ((and parent (= (org-element-property :contents-end parent) end))
23454 (goto-char (org-element-property :end parent)))
23455 ((integer-or-marker-p end) (goto-char end))
23456 (t (message "No element at point")))))))
23458 (defun org-backward-element ()
23459 "Move backward by one element.
23460 Move to the previous element at the same level, when possible."
23461 (interactive)
23462 (cond ((bobp) (user-error "Cannot move further up"))
23463 ((org-with-limited-levels (org-at-heading-p))
23464 ;; At a headline, move to the previous one, if any, or stay
23465 ;; here.
23466 (let ((origin (point)))
23467 (org-with-limited-levels (org-backward-heading-same-level 1))
23468 ;; When current headline has no sibling above, move to its
23469 ;; parent.
23470 (when (= (point) origin)
23471 (or (org-with-limited-levels (org-up-heading-safe))
23472 (progn (goto-char origin)
23473 (user-error "Cannot move further up"))))))
23475 (let* ((elem (org-element-at-point))
23476 (beg (org-element-property :begin elem)))
23477 (cond
23478 ;; Move to beginning of current element if point isn't
23479 ;; there already.
23480 ((null beg) (message "No element at point"))
23481 ((/= (point) beg) (goto-char beg))
23482 (t (goto-char beg)
23483 (skip-chars-backward " \r\t\n")
23484 (unless (bobp)
23485 (let ((prev (org-element-at-point)))
23486 (goto-char (org-element-property :begin prev))
23487 (while (and (setq prev (org-element-property :parent prev))
23488 (<= (org-element-property :end prev) beg))
23489 (goto-char (org-element-property :begin prev)))))))))))
23491 (defun org-up-element ()
23492 "Move to upper element."
23493 (interactive)
23494 (if (org-with-limited-levels (org-at-heading-p))
23495 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23496 (let* ((elem (org-element-at-point))
23497 (parent (org-element-property :parent elem)))
23498 (if parent (goto-char (org-element-property :begin parent))
23499 (if (org-with-limited-levels (org-before-first-heading-p))
23500 (user-error "No surrounding element")
23501 (org-with-limited-levels (org-back-to-heading)))))))
23503 (defun org-down-element ()
23504 "Move to inner element."
23505 (interactive)
23506 (let ((element (org-element-at-point)))
23507 (cond
23508 ((memq (org-element-type element) '(plain-list table))
23509 (goto-char (org-element-property :contents-begin element))
23510 (forward-char))
23511 ((memq (org-element-type element) org-element-greater-elements)
23512 ;; If contents are hidden, first disclose them.
23513 (when (org-invisible-p (line-end-position)) (org-cycle))
23514 (goto-char (or (org-element-property :contents-begin element)
23515 (user-error "No content for this element"))))
23516 (t (user-error "No inner element")))))
23518 (defun org-drag-element-backward ()
23519 "Move backward element at point."
23520 (interactive)
23521 (let ((elem (or (org-element-at-point)
23522 (user-error "No element at point"))))
23523 (if (eq (org-element-type elem) 'headline)
23524 ;; Preserve point when moving a whole tree, even if point was
23525 ;; on blank lines below the headline.
23526 (let ((offset (skip-chars-backward " \t\n")))
23527 (unwind-protect (org-move-subtree-up)
23528 (forward-char (- offset))))
23529 (let ((prev-elem
23530 (save-excursion
23531 (goto-char (org-element-property :begin elem))
23532 (skip-chars-backward " \r\t\n")
23533 (unless (bobp)
23534 (let* ((beg (org-element-property :begin elem))
23535 (prev (org-element-at-point))
23536 (up prev))
23537 (while (and (setq up (org-element-property :parent up))
23538 (<= (org-element-property :end up) beg))
23539 (setq prev up))
23540 prev)))))
23541 ;; Error out if no previous element or previous element is
23542 ;; a parent of the current one.
23543 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23544 (user-error "Cannot drag element backward")
23545 (let ((pos (point)))
23546 (org-element-swap-A-B prev-elem elem)
23547 (goto-char (+ (org-element-property :begin prev-elem)
23548 (- pos (org-element-property :begin elem))))))))))
23550 (defun org-drag-element-forward ()
23551 "Move forward element at point."
23552 (interactive)
23553 (let* ((pos (point))
23554 (elem (or (org-element-at-point)
23555 (user-error "No element at point"))))
23556 (when (= (point-max) (org-element-property :end elem))
23557 (user-error "Cannot drag element forward"))
23558 (goto-char (org-element-property :end elem))
23559 (let ((next-elem (org-element-at-point)))
23560 (when (or (org-element-nested-p elem next-elem)
23561 (and (eq (org-element-type next-elem) 'headline)
23562 (not (eq (org-element-type elem) 'headline))))
23563 (goto-char pos)
23564 (user-error "Cannot drag element forward"))
23565 ;; Compute new position of point: it's shifted by NEXT-ELEM
23566 ;; body's length (without final blanks) and by the length of
23567 ;; blanks between ELEM and NEXT-ELEM.
23568 (let ((size-next (- (save-excursion
23569 (goto-char (org-element-property :end next-elem))
23570 (skip-chars-backward " \r\t\n")
23571 (forward-line)
23572 ;; Small correction if buffer doesn't end
23573 ;; with a newline character.
23574 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23575 (org-element-property :begin next-elem)))
23576 (size-blank (- (org-element-property :end elem)
23577 (save-excursion
23578 (goto-char (org-element-property :end elem))
23579 (skip-chars-backward " \r\t\n")
23580 (forward-line)
23581 (point)))))
23582 (org-element-swap-A-B elem next-elem)
23583 (goto-char (+ pos size-next size-blank))))))
23585 (defun org-drag-line-forward (arg)
23586 "Drag the line at point ARG lines forward."
23587 (interactive "p")
23588 (dotimes (_ (abs arg))
23589 (let ((c (current-column)))
23590 (if (< 0 arg)
23591 (progn
23592 (beginning-of-line 2)
23593 (transpose-lines 1)
23594 (beginning-of-line 0))
23595 (transpose-lines 1)
23596 (beginning-of-line -1))
23597 (org-move-to-column c))))
23599 (defun org-drag-line-backward (arg)
23600 "Drag the line at point ARG lines backward."
23601 (interactive "p")
23602 (org-drag-line-forward (- arg)))
23604 (defun org-mark-element ()
23605 "Put point at beginning of this element, mark at end.
23607 Interactively, if this command is repeated or (in Transient Mark
23608 mode) if the mark is active, it marks the next element after the
23609 ones already marked."
23610 (interactive)
23611 (let (deactivate-mark)
23612 (if (and (called-interactively-p 'any)
23613 (or (and (eq last-command this-command) (mark t))
23614 (and transient-mark-mode mark-active)))
23615 (set-mark
23616 (save-excursion
23617 (goto-char (mark))
23618 (goto-char (org-element-property :end (org-element-at-point)))))
23619 (let ((element (org-element-at-point)))
23620 (end-of-line)
23621 (push-mark (org-element-property :end element) t t)
23622 (goto-char (org-element-property :begin element))))))
23624 (defun org-narrow-to-element ()
23625 "Narrow buffer to current element."
23626 (interactive)
23627 (let ((elem (org-element-at-point)))
23628 (cond
23629 ((eq (car elem) 'headline)
23630 (narrow-to-region
23631 (org-element-property :begin elem)
23632 (org-element-property :end elem)))
23633 ((memq (car elem) org-element-greater-elements)
23634 (narrow-to-region
23635 (org-element-property :contents-begin elem)
23636 (org-element-property :contents-end elem)))
23638 (narrow-to-region
23639 (org-element-property :begin elem)
23640 (org-element-property :end elem))))))
23642 (defun org-transpose-element ()
23643 "Transpose current and previous elements, keeping blank lines between.
23644 Point is moved after both elements."
23645 (interactive)
23646 (org-skip-whitespace)
23647 (let ((end (org-element-property :end (org-element-at-point))))
23648 (org-drag-element-backward)
23649 (goto-char end)))
23651 (defun org-unindent-buffer ()
23652 "Un-indent the visible part of the buffer.
23653 Relative indentation (between items, inside blocks, etc.) isn't
23654 modified."
23655 (interactive)
23656 (unless (eq major-mode 'org-mode)
23657 (user-error "Cannot un-indent a buffer not in Org mode"))
23658 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23659 (unindent-tree
23660 (lambda (contents)
23661 (dolist (element (reverse contents))
23662 (if (memq (org-element-type element) '(headline section))
23663 (funcall unindent-tree (org-element-contents element))
23664 (save-excursion
23665 (save-restriction
23666 (narrow-to-region
23667 (org-element-property :begin element)
23668 (org-element-property :end element))
23669 (org-do-remove-indentation))))))))
23670 (funcall unindent-tree (org-element-contents parse-tree))))
23672 (defun org-make-options-regexp (kwds &optional extra)
23673 "Make a regular expression for keyword lines.
23674 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23675 when non-nil, is a regexp matching keywords names."
23676 (concat "^[ \t]*#\\+\\("
23677 (regexp-opt kwds)
23678 (and extra (concat (and kwds "\\|") extra))
23679 "\\):[ \t]*\\(.*\\)"))
23682 ;;; Finish up
23684 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23685 (lambda () (add-hook 'change-major-mode-hook
23686 'org-show-all 'append 'local)))
23688 (provide 'org)
23690 (run-hooks 'org-load-hook)
23692 ;;; org.el ends here